diff --git a/.gitattributes b/.gitattributes index 7c8495ad770360bf8e8b65845f6dc6a21fb6ccbf..bcb073f36b7e7bd59a2e396bc8de6e26ef6568a6 100644 --- a/.gitattributes +++ b/.gitattributes @@ -3489,3 +3489,20 @@ platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/series/__py platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/dtypes/__pycache__/test_inference.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/resample/__pycache__/test_datetime_index.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text platform/dataops/dto/.venv/lib/python3.12/site-packages/pandas/tests/copy_view/__pycache__/test_methods.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/hf_api.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust.abi3.so filter=lfs diff=lfs merge=lfs -text +platform/dataops/dto/.venv/lib/python3.12/site-packages/paramiko/__pycache__/transport.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/config/__pycache__/config_options_legacy_tests.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/config/__pycache__/config_options_tests.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/fonts/fontawesome-webfont.eot filter=lfs diff=lfs merge=lfs -text +platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/fonts/fontawesome-webfont.ttf filter=lfs diff=lfs merge=lfs -text +platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/readthedocs/css/fonts/fontawesome-webfont.eot filter=lfs diff=lfs merge=lfs -text +platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/readthedocs/css/fonts/fontawesome-webfont.ttf filter=lfs diff=lfs merge=lfs -text +platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/readthedocs/css/fonts/lato-bold-italic.woff filter=lfs diff=lfs merge=lfs -text +platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/readthedocs/css/fonts/lato-bold-italic.woff2 filter=lfs diff=lfs merge=lfs -text +platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/readthedocs/css/fonts/lato-bold.woff filter=lfs diff=lfs merge=lfs -text +platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/readthedocs/css/fonts/lato-bold.woff2 filter=lfs diff=lfs merge=lfs -text +platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/readthedocs/css/fonts/lato-normal-italic.woff filter=lfs diff=lfs merge=lfs -text +platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/readthedocs/css/fonts/lato-normal-italic.woff2 filter=lfs diff=lfs merge=lfs -text +platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/readthedocs/css/fonts/lato-normal.woff filter=lfs diff=lfs merge=lfs -text +platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/readthedocs/css/fonts/lato-normal.woff2 filter=lfs diff=lfs merge=lfs -text diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/.hash/_cparser.pxd.hash b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/.hash/_cparser.pxd.hash new file mode 100644 index 0000000000000000000000000000000000000000..65e3d4ba43c3f5919259385e83c8017caced6cf8 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/.hash/_cparser.pxd.hash @@ -0,0 +1 @@ +f2318883e549f69de597009a914603b0f1b10381e265ef5d98af499ad973fb98 /home/runner/work/aiohttp/aiohttp/aiohttp/_cparser.pxd diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/.hash/_find_header.pxd.hash b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/.hash/_find_header.pxd.hash new file mode 100644 index 0000000000000000000000000000000000000000..f006c2de5d24a1b5a9c26f83c858127b5e12b07c --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/.hash/_find_header.pxd.hash @@ -0,0 +1 @@ +d067f01423cddb3c442933b5fcc039b18ab651fcec1bc91c577693aafc25cf78 /home/runner/work/aiohttp/aiohttp/aiohttp/_find_header.pxd diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/.hash/_helpers.pyi.hash b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/.hash/_helpers.pyi.hash new file mode 100644 index 0000000000000000000000000000000000000000..6a30d6325b65d245377f888a6c06fc73c7db5600 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/.hash/_helpers.pyi.hash @@ -0,0 +1 @@ +6682a22524b9d4fc442e123672622be7bdfb6238d9709b7b15b2113b7ca6d52b /home/runner/work/aiohttp/aiohttp/aiohttp/_helpers.pyi diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/.hash/_helpers.pyx.hash b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/.hash/_helpers.pyx.hash new file mode 100644 index 0000000000000000000000000000000000000000..8f38727d780de1175391067d691c038658d03196 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/.hash/_helpers.pyx.hash @@ -0,0 +1 @@ +5de2db35fb795ffe227e2f1007c8ba4f2ad1b9aca28cc48edc80c779203cf6e3 /home/runner/work/aiohttp/aiohttp/aiohttp/_helpers.pyx diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/.hash/_http_parser.pyx.hash b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/.hash/_http_parser.pyx.hash new file mode 100644 index 0000000000000000000000000000000000000000..8e5a14159386d844fe0b1dd8ebce58264620c2af --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/.hash/_http_parser.pyx.hash @@ -0,0 +1 @@ +7f32b0c1595c1a71957a218ece8d3977ed9171caad97df8fcd82aa80addfc5d2 /home/runner/work/aiohttp/aiohttp/aiohttp/_http_parser.pyx diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/.hash/_http_writer.pyx.hash b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/.hash/_http_writer.pyx.hash new file mode 100644 index 0000000000000000000000000000000000000000..8e1aaab044c504f615263e632cd5a2474cda5d3e --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/.hash/_http_writer.pyx.hash @@ -0,0 +1 @@ +6881c0a7c838655e646c645d99971efaf5e310bc3633a7c62b226e39d81842ac /home/runner/work/aiohttp/aiohttp/aiohttp/_http_writer.pyx diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/.hash/_websocket.pyx.hash b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/.hash/_websocket.pyx.hash new file mode 100644 index 0000000000000000000000000000000000000000..ddbb4c7a6f87cba4affe640cac86c8a384302444 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/.hash/_websocket.pyx.hash @@ -0,0 +1 @@ +d57b8e48d0c26f20ebcc5e6e300da2b2a6aeb12b3c9768d64cb0e53432ccf48a /home/runner/work/aiohttp/aiohttp/aiohttp/_websocket.pyx diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/.hash/hdrs.py.hash b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/.hash/hdrs.py.hash new file mode 100644 index 0000000000000000000000000000000000000000..e0b81d7679b307d3f0ad38c39b54658360003f38 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/.hash/hdrs.py.hash @@ -0,0 +1 @@ +bb39f96a09ff8d789dda1fa4cba63464043c06b3de4c62c31abfb07a231cb6ca /home/runner/work/aiohttp/aiohttp/aiohttp/hdrs.py diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c662008c0570cbe3ad01fe64a681bf926d393a8a Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/abc.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/abc.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b575f940126abcbe805268ac2f0a1953fb563c70 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/abc.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/base_protocol.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/base_protocol.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb5aea4bd29a2384bfa87a59734458eb28285d7b Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/base_protocol.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/client.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/client.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3f0bf2c030bdc278ddf23f54b97f405f930601db Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/client.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/client_exceptions.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/client_exceptions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5e74bcfe6270127e52ee0a64d68800fe339ab934 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/client_exceptions.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/client_proto.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/client_proto.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..797a899d756c369f8dab73ead25d7c3bdca2f0b4 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/client_proto.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/client_reqrep.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/client_reqrep.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43da0fd23ca6066070c5820569b122430d473466 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/client_reqrep.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/client_ws.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/client_ws.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4732b1e733fdaa48e675c375c0624cc424f78aa0 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/client_ws.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/compression_utils.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/compression_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b3d060f872fc6e00b1dc819bb35f3627014a1de6 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/compression_utils.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/connector.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/connector.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2c5fd5fd677b4ba27e22855ab04551ac80945da9 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/connector.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/cookiejar.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/cookiejar.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..08cc98b7e5aa28485faf2fcee3333083dfd4956e Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/cookiejar.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/formdata.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/formdata.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..02c44b96875bc42972c48dbd81ee32047259aad1 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/formdata.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/hdrs.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/hdrs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5ed4f7dcb2ec5ca5e50c1f3e4b3215de5b4f378a Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/hdrs.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/helpers.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/helpers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..955e6eeda1a2b62cb5396240c0fdf3d1d8791e10 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/helpers.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/http.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/http.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d0b98d79df7865e28d81e8500ba1b066cdc8e935 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/http.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/http_exceptions.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/http_exceptions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..761d644b3439bd2afe3b3480c7fb85d836c45cd9 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/http_exceptions.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/http_parser.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/http_parser.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2035a8ab9f58fcb75ae1721e90fbc32cce3a76fc Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/http_parser.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/http_websocket.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/http_websocket.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..00a52b5da8aa63b0bcd70957a03cfeacd76b896b Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/http_websocket.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/http_writer.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/http_writer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2fdb110a87ccbf5ea7b927aa6e2583992faf57b8 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/http_writer.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/locks.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/locks.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d635d40cd01e9828d2d8a81743bdecb1b0716d46 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/locks.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/log.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/log.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0bbc3b85200f0e8cece0955509a151fa8f78b0a0 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/log.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/multipart.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/multipart.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5db1e3a1e76b31fe61cb43cbe2fbeb2f2f0bb765 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/multipart.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/payload.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/payload.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ad6a27732cc16f9c0a0c597a1cc45bcc6eb3d1b Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/payload.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/payload_streamer.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/payload_streamer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..651b3d628668e22ca9910c221dc702238523ffc4 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/payload_streamer.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/pytest_plugin.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/pytest_plugin.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1678b2df4c78ea7f04afa4225056b6ba9d5670b1 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/pytest_plugin.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/resolver.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/resolver.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a84adac29a6cb262d8cf45787f50ab53da64eb07 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/resolver.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/streams.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/streams.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0b774fcfffdc07165da9d37784c2016a584b5392 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/streams.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/tcp_helpers.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/tcp_helpers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bdb685ebd07555963151b84fcf76ec291287a6a3 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/tcp_helpers.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/test_utils.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/test_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5f68b10954ab5952194fc6b0b698bbed516701d0 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/test_utils.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/tracing.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/tracing.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5ec6be3dbb3da07e4cf468e5762105e13d616919 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/tracing.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/typedefs.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/typedefs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ed98b2571e9b707a9518e27f64873fc4143610cf Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/typedefs.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/web.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/web.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4fa96c97a5e9f960c0570028a88ad95e41ad3759 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/web.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/web_app.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/web_app.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5a070e7fcc5049f5606070754faf2b5b9800dd2b Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/web_app.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/web_exceptions.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/web_exceptions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9479461e0534916b0406ecd5042cc2c0ec0d7e32 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/web_exceptions.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/web_fileresponse.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/web_fileresponse.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a77a03516058455aa66a5b1ee4b97f526546f1ab Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/web_fileresponse.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/web_log.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/web_log.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f207aa6d7406976eb2b86362b75e83ceeedb4e79 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/web_log.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/web_middlewares.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/web_middlewares.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c04b562b010c643349dea17189ae200213d6a4ca Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/web_middlewares.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/web_protocol.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/web_protocol.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2cb2dbbd71105c855d7814f83f205b17b037dcbf Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/web_protocol.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/web_request.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/web_request.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..32c67ca1fe06ca0417e04ba552938585b04dc07d Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/web_request.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/web_response.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/web_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..54699d4e645787c1e4430194e8a266e169868b07 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/web_response.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/web_routedef.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/web_routedef.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e05ec6cefb811c8767ce12cd4eae425992d1674a Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/web_routedef.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/web_runner.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/web_runner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..67bf1c4b4ef88f8c9853d5d2c5fd830cf8132077 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/web_runner.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/web_server.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/web_server.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9166856796bb0848dc268a5840e2ee9112db8546 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/web_server.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/web_urldispatcher.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/web_urldispatcher.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..97ba4932061b15fc0009e2ce9f4934f72616f814 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/web_urldispatcher.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/web_ws.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/web_ws.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f94968cd302cc16dcedd316886c06174eef3f194 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/web_ws.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/worker.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/worker.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..516c689f1c927935b044cac37386b7673e608a3c Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/aiohttp/__pycache__/worker.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/__pycache__/__about__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/__pycache__/__about__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..020943df62b59dd069d9dc3f3f42579377988871 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/__pycache__/__about__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..833e5f951b2047281e0a2da72194592d5e346221 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/__pycache__/exceptions.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/__pycache__/exceptions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ba89e8da5ce944a24ec390f81c575bd83dedc997 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/__pycache__/exceptions.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/__pycache__/fernet.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/__pycache__/fernet.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9d10c22e2548aa554eb45d9ae8fb51e50fa00da3 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/__pycache__/fernet.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/__pycache__/utils.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b8c266905f36bcd819a9ac3e1f37d5643ed86415 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/__pycache__/utils.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b9f1187011bdaa0720bc462564582393700f3d4a --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/__init__.py @@ -0,0 +1,13 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +""" +Hazardous Materials + +This is a "Hazardous Materials" module. You should ONLY use it if you're +100% absolutely sure that you know what you're doing because this module +is full of land mines, dragons, and dinosaurs with laser guns. +""" diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ffe8f3127b8ed6318a42145456e48890c3afef8 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/__pycache__/_oid.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/__pycache__/_oid.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..386097602e8b31c94e2260540a3df206e5c4d449 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/__pycache__/_oid.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/_oid.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/_oid.py new file mode 100644 index 0000000000000000000000000000000000000000..01d4b3406062ad68aa7b6c658e3c60b406ed6d80 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/_oid.py @@ -0,0 +1,299 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import typing + +from cryptography.hazmat.bindings._rust import ( + ObjectIdentifier as ObjectIdentifier, +) +from cryptography.hazmat.primitives import hashes + + +class ExtensionOID: + SUBJECT_DIRECTORY_ATTRIBUTES = ObjectIdentifier("2.5.29.9") + SUBJECT_KEY_IDENTIFIER = ObjectIdentifier("2.5.29.14") + KEY_USAGE = ObjectIdentifier("2.5.29.15") + SUBJECT_ALTERNATIVE_NAME = ObjectIdentifier("2.5.29.17") + ISSUER_ALTERNATIVE_NAME = ObjectIdentifier("2.5.29.18") + BASIC_CONSTRAINTS = ObjectIdentifier("2.5.29.19") + NAME_CONSTRAINTS = ObjectIdentifier("2.5.29.30") + CRL_DISTRIBUTION_POINTS = ObjectIdentifier("2.5.29.31") + CERTIFICATE_POLICIES = ObjectIdentifier("2.5.29.32") + POLICY_MAPPINGS = ObjectIdentifier("2.5.29.33") + AUTHORITY_KEY_IDENTIFIER = ObjectIdentifier("2.5.29.35") + POLICY_CONSTRAINTS = ObjectIdentifier("2.5.29.36") + EXTENDED_KEY_USAGE = ObjectIdentifier("2.5.29.37") + FRESHEST_CRL = ObjectIdentifier("2.5.29.46") + INHIBIT_ANY_POLICY = ObjectIdentifier("2.5.29.54") + ISSUING_DISTRIBUTION_POINT = ObjectIdentifier("2.5.29.28") + AUTHORITY_INFORMATION_ACCESS = ObjectIdentifier("1.3.6.1.5.5.7.1.1") + SUBJECT_INFORMATION_ACCESS = ObjectIdentifier("1.3.6.1.5.5.7.1.11") + OCSP_NO_CHECK = ObjectIdentifier("1.3.6.1.5.5.7.48.1.5") + TLS_FEATURE = ObjectIdentifier("1.3.6.1.5.5.7.1.24") + CRL_NUMBER = ObjectIdentifier("2.5.29.20") + DELTA_CRL_INDICATOR = ObjectIdentifier("2.5.29.27") + PRECERT_SIGNED_CERTIFICATE_TIMESTAMPS = ObjectIdentifier( + "1.3.6.1.4.1.11129.2.4.2" + ) + PRECERT_POISON = ObjectIdentifier("1.3.6.1.4.1.11129.2.4.3") + SIGNED_CERTIFICATE_TIMESTAMPS = ObjectIdentifier("1.3.6.1.4.1.11129.2.4.5") + MS_CERTIFICATE_TEMPLATE = ObjectIdentifier("1.3.6.1.4.1.311.21.7") + + +class OCSPExtensionOID: + NONCE = ObjectIdentifier("1.3.6.1.5.5.7.48.1.2") + ACCEPTABLE_RESPONSES = ObjectIdentifier("1.3.6.1.5.5.7.48.1.4") + + +class CRLEntryExtensionOID: + CERTIFICATE_ISSUER = ObjectIdentifier("2.5.29.29") + CRL_REASON = ObjectIdentifier("2.5.29.21") + INVALIDITY_DATE = ObjectIdentifier("2.5.29.24") + + +class NameOID: + COMMON_NAME = ObjectIdentifier("2.5.4.3") + COUNTRY_NAME = ObjectIdentifier("2.5.4.6") + LOCALITY_NAME = ObjectIdentifier("2.5.4.7") + STATE_OR_PROVINCE_NAME = ObjectIdentifier("2.5.4.8") + STREET_ADDRESS = ObjectIdentifier("2.5.4.9") + ORGANIZATION_NAME = ObjectIdentifier("2.5.4.10") + ORGANIZATIONAL_UNIT_NAME = ObjectIdentifier("2.5.4.11") + SERIAL_NUMBER = ObjectIdentifier("2.5.4.5") + SURNAME = ObjectIdentifier("2.5.4.4") + GIVEN_NAME = ObjectIdentifier("2.5.4.42") + TITLE = ObjectIdentifier("2.5.4.12") + INITIALS = ObjectIdentifier("2.5.4.43") + GENERATION_QUALIFIER = ObjectIdentifier("2.5.4.44") + X500_UNIQUE_IDENTIFIER = ObjectIdentifier("2.5.4.45") + DN_QUALIFIER = ObjectIdentifier("2.5.4.46") + PSEUDONYM = ObjectIdentifier("2.5.4.65") + USER_ID = ObjectIdentifier("0.9.2342.19200300.100.1.1") + DOMAIN_COMPONENT = ObjectIdentifier("0.9.2342.19200300.100.1.25") + EMAIL_ADDRESS = ObjectIdentifier("1.2.840.113549.1.9.1") + JURISDICTION_COUNTRY_NAME = ObjectIdentifier("1.3.6.1.4.1.311.60.2.1.3") + JURISDICTION_LOCALITY_NAME = ObjectIdentifier("1.3.6.1.4.1.311.60.2.1.1") + JURISDICTION_STATE_OR_PROVINCE_NAME = ObjectIdentifier( + "1.3.6.1.4.1.311.60.2.1.2" + ) + BUSINESS_CATEGORY = ObjectIdentifier("2.5.4.15") + POSTAL_ADDRESS = ObjectIdentifier("2.5.4.16") + POSTAL_CODE = ObjectIdentifier("2.5.4.17") + INN = ObjectIdentifier("1.2.643.3.131.1.1") + OGRN = ObjectIdentifier("1.2.643.100.1") + SNILS = ObjectIdentifier("1.2.643.100.3") + UNSTRUCTURED_NAME = ObjectIdentifier("1.2.840.113549.1.9.2") + + +class SignatureAlgorithmOID: + RSA_WITH_MD5 = ObjectIdentifier("1.2.840.113549.1.1.4") + RSA_WITH_SHA1 = ObjectIdentifier("1.2.840.113549.1.1.5") + # This is an alternate OID for RSA with SHA1 that is occasionally seen + _RSA_WITH_SHA1 = ObjectIdentifier("1.3.14.3.2.29") + RSA_WITH_SHA224 = ObjectIdentifier("1.2.840.113549.1.1.14") + RSA_WITH_SHA256 = ObjectIdentifier("1.2.840.113549.1.1.11") + RSA_WITH_SHA384 = ObjectIdentifier("1.2.840.113549.1.1.12") + RSA_WITH_SHA512 = ObjectIdentifier("1.2.840.113549.1.1.13") + RSA_WITH_SHA3_224 = ObjectIdentifier("2.16.840.1.101.3.4.3.13") + RSA_WITH_SHA3_256 = ObjectIdentifier("2.16.840.1.101.3.4.3.14") + RSA_WITH_SHA3_384 = ObjectIdentifier("2.16.840.1.101.3.4.3.15") + RSA_WITH_SHA3_512 = ObjectIdentifier("2.16.840.1.101.3.4.3.16") + RSASSA_PSS = ObjectIdentifier("1.2.840.113549.1.1.10") + ECDSA_WITH_SHA1 = ObjectIdentifier("1.2.840.10045.4.1") + ECDSA_WITH_SHA224 = ObjectIdentifier("1.2.840.10045.4.3.1") + ECDSA_WITH_SHA256 = ObjectIdentifier("1.2.840.10045.4.3.2") + ECDSA_WITH_SHA384 = ObjectIdentifier("1.2.840.10045.4.3.3") + ECDSA_WITH_SHA512 = ObjectIdentifier("1.2.840.10045.4.3.4") + ECDSA_WITH_SHA3_224 = ObjectIdentifier("2.16.840.1.101.3.4.3.9") + ECDSA_WITH_SHA3_256 = ObjectIdentifier("2.16.840.1.101.3.4.3.10") + ECDSA_WITH_SHA3_384 = ObjectIdentifier("2.16.840.1.101.3.4.3.11") + ECDSA_WITH_SHA3_512 = ObjectIdentifier("2.16.840.1.101.3.4.3.12") + DSA_WITH_SHA1 = ObjectIdentifier("1.2.840.10040.4.3") + DSA_WITH_SHA224 = ObjectIdentifier("2.16.840.1.101.3.4.3.1") + DSA_WITH_SHA256 = ObjectIdentifier("2.16.840.1.101.3.4.3.2") + DSA_WITH_SHA384 = ObjectIdentifier("2.16.840.1.101.3.4.3.3") + DSA_WITH_SHA512 = ObjectIdentifier("2.16.840.1.101.3.4.3.4") + ED25519 = ObjectIdentifier("1.3.101.112") + ED448 = ObjectIdentifier("1.3.101.113") + GOSTR3411_94_WITH_3410_2001 = ObjectIdentifier("1.2.643.2.2.3") + GOSTR3410_2012_WITH_3411_2012_256 = ObjectIdentifier("1.2.643.7.1.1.3.2") + GOSTR3410_2012_WITH_3411_2012_512 = ObjectIdentifier("1.2.643.7.1.1.3.3") + + +_SIG_OIDS_TO_HASH: typing.Dict[ + ObjectIdentifier, typing.Optional[hashes.HashAlgorithm] +] = { + SignatureAlgorithmOID.RSA_WITH_MD5: hashes.MD5(), + SignatureAlgorithmOID.RSA_WITH_SHA1: hashes.SHA1(), + SignatureAlgorithmOID._RSA_WITH_SHA1: hashes.SHA1(), + SignatureAlgorithmOID.RSA_WITH_SHA224: hashes.SHA224(), + SignatureAlgorithmOID.RSA_WITH_SHA256: hashes.SHA256(), + SignatureAlgorithmOID.RSA_WITH_SHA384: hashes.SHA384(), + SignatureAlgorithmOID.RSA_WITH_SHA512: hashes.SHA512(), + SignatureAlgorithmOID.RSA_WITH_SHA3_224: hashes.SHA3_224(), + SignatureAlgorithmOID.RSA_WITH_SHA3_256: hashes.SHA3_256(), + SignatureAlgorithmOID.RSA_WITH_SHA3_384: hashes.SHA3_384(), + SignatureAlgorithmOID.RSA_WITH_SHA3_512: hashes.SHA3_512(), + SignatureAlgorithmOID.ECDSA_WITH_SHA1: hashes.SHA1(), + SignatureAlgorithmOID.ECDSA_WITH_SHA224: hashes.SHA224(), + SignatureAlgorithmOID.ECDSA_WITH_SHA256: hashes.SHA256(), + SignatureAlgorithmOID.ECDSA_WITH_SHA384: hashes.SHA384(), + SignatureAlgorithmOID.ECDSA_WITH_SHA512: hashes.SHA512(), + SignatureAlgorithmOID.ECDSA_WITH_SHA3_224: hashes.SHA3_224(), + SignatureAlgorithmOID.ECDSA_WITH_SHA3_256: hashes.SHA3_256(), + SignatureAlgorithmOID.ECDSA_WITH_SHA3_384: hashes.SHA3_384(), + SignatureAlgorithmOID.ECDSA_WITH_SHA3_512: hashes.SHA3_512(), + SignatureAlgorithmOID.DSA_WITH_SHA1: hashes.SHA1(), + SignatureAlgorithmOID.DSA_WITH_SHA224: hashes.SHA224(), + SignatureAlgorithmOID.DSA_WITH_SHA256: hashes.SHA256(), + SignatureAlgorithmOID.ED25519: None, + SignatureAlgorithmOID.ED448: None, + SignatureAlgorithmOID.GOSTR3411_94_WITH_3410_2001: None, + SignatureAlgorithmOID.GOSTR3410_2012_WITH_3411_2012_256: None, + SignatureAlgorithmOID.GOSTR3410_2012_WITH_3411_2012_512: None, +} + + +class ExtendedKeyUsageOID: + SERVER_AUTH = ObjectIdentifier("1.3.6.1.5.5.7.3.1") + CLIENT_AUTH = ObjectIdentifier("1.3.6.1.5.5.7.3.2") + CODE_SIGNING = ObjectIdentifier("1.3.6.1.5.5.7.3.3") + EMAIL_PROTECTION = ObjectIdentifier("1.3.6.1.5.5.7.3.4") + TIME_STAMPING = ObjectIdentifier("1.3.6.1.5.5.7.3.8") + OCSP_SIGNING = ObjectIdentifier("1.3.6.1.5.5.7.3.9") + ANY_EXTENDED_KEY_USAGE = ObjectIdentifier("2.5.29.37.0") + SMARTCARD_LOGON = ObjectIdentifier("1.3.6.1.4.1.311.20.2.2") + KERBEROS_PKINIT_KDC = ObjectIdentifier("1.3.6.1.5.2.3.5") + IPSEC_IKE = ObjectIdentifier("1.3.6.1.5.5.7.3.17") + CERTIFICATE_TRANSPARENCY = ObjectIdentifier("1.3.6.1.4.1.11129.2.4.4") + + +class AuthorityInformationAccessOID: + CA_ISSUERS = ObjectIdentifier("1.3.6.1.5.5.7.48.2") + OCSP = ObjectIdentifier("1.3.6.1.5.5.7.48.1") + + +class SubjectInformationAccessOID: + CA_REPOSITORY = ObjectIdentifier("1.3.6.1.5.5.7.48.5") + + +class CertificatePoliciesOID: + CPS_QUALIFIER = ObjectIdentifier("1.3.6.1.5.5.7.2.1") + CPS_USER_NOTICE = ObjectIdentifier("1.3.6.1.5.5.7.2.2") + ANY_POLICY = ObjectIdentifier("2.5.29.32.0") + + +class AttributeOID: + CHALLENGE_PASSWORD = ObjectIdentifier("1.2.840.113549.1.9.7") + UNSTRUCTURED_NAME = ObjectIdentifier("1.2.840.113549.1.9.2") + + +_OID_NAMES = { + NameOID.COMMON_NAME: "commonName", + NameOID.COUNTRY_NAME: "countryName", + NameOID.LOCALITY_NAME: "localityName", + NameOID.STATE_OR_PROVINCE_NAME: "stateOrProvinceName", + NameOID.STREET_ADDRESS: "streetAddress", + NameOID.ORGANIZATION_NAME: "organizationName", + NameOID.ORGANIZATIONAL_UNIT_NAME: "organizationalUnitName", + NameOID.SERIAL_NUMBER: "serialNumber", + NameOID.SURNAME: "surname", + NameOID.GIVEN_NAME: "givenName", + NameOID.TITLE: "title", + NameOID.GENERATION_QUALIFIER: "generationQualifier", + NameOID.X500_UNIQUE_IDENTIFIER: "x500UniqueIdentifier", + NameOID.DN_QUALIFIER: "dnQualifier", + NameOID.PSEUDONYM: "pseudonym", + NameOID.USER_ID: "userID", + NameOID.DOMAIN_COMPONENT: "domainComponent", + NameOID.EMAIL_ADDRESS: "emailAddress", + NameOID.JURISDICTION_COUNTRY_NAME: "jurisdictionCountryName", + NameOID.JURISDICTION_LOCALITY_NAME: "jurisdictionLocalityName", + NameOID.JURISDICTION_STATE_OR_PROVINCE_NAME: ( + "jurisdictionStateOrProvinceName" + ), + NameOID.BUSINESS_CATEGORY: "businessCategory", + NameOID.POSTAL_ADDRESS: "postalAddress", + NameOID.POSTAL_CODE: "postalCode", + NameOID.INN: "INN", + NameOID.OGRN: "OGRN", + NameOID.SNILS: "SNILS", + NameOID.UNSTRUCTURED_NAME: "unstructuredName", + SignatureAlgorithmOID.RSA_WITH_MD5: "md5WithRSAEncryption", + SignatureAlgorithmOID.RSA_WITH_SHA1: "sha1WithRSAEncryption", + SignatureAlgorithmOID.RSA_WITH_SHA224: "sha224WithRSAEncryption", + SignatureAlgorithmOID.RSA_WITH_SHA256: "sha256WithRSAEncryption", + SignatureAlgorithmOID.RSA_WITH_SHA384: "sha384WithRSAEncryption", + SignatureAlgorithmOID.RSA_WITH_SHA512: "sha512WithRSAEncryption", + SignatureAlgorithmOID.RSASSA_PSS: "RSASSA-PSS", + SignatureAlgorithmOID.ECDSA_WITH_SHA1: "ecdsa-with-SHA1", + SignatureAlgorithmOID.ECDSA_WITH_SHA224: "ecdsa-with-SHA224", + SignatureAlgorithmOID.ECDSA_WITH_SHA256: "ecdsa-with-SHA256", + SignatureAlgorithmOID.ECDSA_WITH_SHA384: "ecdsa-with-SHA384", + SignatureAlgorithmOID.ECDSA_WITH_SHA512: "ecdsa-with-SHA512", + SignatureAlgorithmOID.DSA_WITH_SHA1: "dsa-with-sha1", + SignatureAlgorithmOID.DSA_WITH_SHA224: "dsa-with-sha224", + SignatureAlgorithmOID.DSA_WITH_SHA256: "dsa-with-sha256", + SignatureAlgorithmOID.ED25519: "ed25519", + SignatureAlgorithmOID.ED448: "ed448", + SignatureAlgorithmOID.GOSTR3411_94_WITH_3410_2001: ( + "GOST R 34.11-94 with GOST R 34.10-2001" + ), + SignatureAlgorithmOID.GOSTR3410_2012_WITH_3411_2012_256: ( + "GOST R 34.10-2012 with GOST R 34.11-2012 (256 bit)" + ), + SignatureAlgorithmOID.GOSTR3410_2012_WITH_3411_2012_512: ( + "GOST R 34.10-2012 with GOST R 34.11-2012 (512 bit)" + ), + ExtendedKeyUsageOID.SERVER_AUTH: "serverAuth", + ExtendedKeyUsageOID.CLIENT_AUTH: "clientAuth", + ExtendedKeyUsageOID.CODE_SIGNING: "codeSigning", + ExtendedKeyUsageOID.EMAIL_PROTECTION: "emailProtection", + ExtendedKeyUsageOID.TIME_STAMPING: "timeStamping", + ExtendedKeyUsageOID.OCSP_SIGNING: "OCSPSigning", + ExtendedKeyUsageOID.SMARTCARD_LOGON: "msSmartcardLogin", + ExtendedKeyUsageOID.KERBEROS_PKINIT_KDC: "pkInitKDC", + ExtensionOID.SUBJECT_DIRECTORY_ATTRIBUTES: "subjectDirectoryAttributes", + ExtensionOID.SUBJECT_KEY_IDENTIFIER: "subjectKeyIdentifier", + ExtensionOID.KEY_USAGE: "keyUsage", + ExtensionOID.SUBJECT_ALTERNATIVE_NAME: "subjectAltName", + ExtensionOID.ISSUER_ALTERNATIVE_NAME: "issuerAltName", + ExtensionOID.BASIC_CONSTRAINTS: "basicConstraints", + ExtensionOID.PRECERT_SIGNED_CERTIFICATE_TIMESTAMPS: ( + "signedCertificateTimestampList" + ), + ExtensionOID.SIGNED_CERTIFICATE_TIMESTAMPS: ( + "signedCertificateTimestampList" + ), + ExtensionOID.PRECERT_POISON: "ctPoison", + ExtensionOID.MS_CERTIFICATE_TEMPLATE: "msCertificateTemplate", + CRLEntryExtensionOID.CRL_REASON: "cRLReason", + CRLEntryExtensionOID.INVALIDITY_DATE: "invalidityDate", + CRLEntryExtensionOID.CERTIFICATE_ISSUER: "certificateIssuer", + ExtensionOID.NAME_CONSTRAINTS: "nameConstraints", + ExtensionOID.CRL_DISTRIBUTION_POINTS: "cRLDistributionPoints", + ExtensionOID.CERTIFICATE_POLICIES: "certificatePolicies", + ExtensionOID.POLICY_MAPPINGS: "policyMappings", + ExtensionOID.AUTHORITY_KEY_IDENTIFIER: "authorityKeyIdentifier", + ExtensionOID.POLICY_CONSTRAINTS: "policyConstraints", + ExtensionOID.EXTENDED_KEY_USAGE: "extendedKeyUsage", + ExtensionOID.FRESHEST_CRL: "freshestCRL", + ExtensionOID.INHIBIT_ANY_POLICY: "inhibitAnyPolicy", + ExtensionOID.ISSUING_DISTRIBUTION_POINT: ("issuingDistributionPoint"), + ExtensionOID.AUTHORITY_INFORMATION_ACCESS: "authorityInfoAccess", + ExtensionOID.SUBJECT_INFORMATION_ACCESS: "subjectInfoAccess", + ExtensionOID.OCSP_NO_CHECK: "OCSPNoCheck", + ExtensionOID.CRL_NUMBER: "cRLNumber", + ExtensionOID.DELTA_CRL_INDICATOR: "deltaCRLIndicator", + ExtensionOID.TLS_FEATURE: "TLSFeature", + AuthorityInformationAccessOID.OCSP: "OCSP", + AuthorityInformationAccessOID.CA_ISSUERS: "caIssuers", + SubjectInformationAccessOID.CA_REPOSITORY: "caRepository", + CertificatePoliciesOID.CPS_QUALIFIER: "id-qt-cps", + CertificatePoliciesOID.CPS_USER_NOTICE: "id-qt-unotice", + OCSPExtensionOID.NONCE: "OCSPNonce", + AttributeOID.CHALLENGE_PASSWORD: "challengePassword", +} diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b4400aa037451d10d6bcadd455dcf98f9b72e221 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/__init__.py @@ -0,0 +1,13 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from typing import Any + + +def default_backend() -> Any: + from cryptography.hazmat.backends.openssl.backend import backend + + return backend diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..35d754563003bf5402cbbd4d38168d2e195474a7 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..51b04476cbb7f4a98051f2fc55bcc1aa35e22d05 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/__init__.py @@ -0,0 +1,9 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography.hazmat.backends.openssl.backend import backend + +__all__ = ["backend"] diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8b0b0808297cd8f19db9fafac4235dc41e950b40 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/__pycache__/aead.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/__pycache__/aead.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..434cc6eddba848807f8336b5875cfc839836e49c Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/__pycache__/aead.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/__pycache__/backend.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/__pycache__/backend.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9236508f1acc0aaa73d12a944fe9ad62a160acd2 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/__pycache__/backend.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/__pycache__/ciphers.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/__pycache__/ciphers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4f9076b16a0df8b3817f107c81266add20efecec Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/__pycache__/ciphers.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/__pycache__/cmac.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/__pycache__/cmac.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3f76b1f177b1ab60cf7ac6975b1a06c2e643c465 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/__pycache__/cmac.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/__pycache__/decode_asn1.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/__pycache__/decode_asn1.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0e46ef054933da561c1938b465cf44a14c1f7db4 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/__pycache__/decode_asn1.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/__pycache__/ec.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/__pycache__/ec.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7fa6ca4547d21a0c956d5b83e3e7c83db262b679 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/__pycache__/ec.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/__pycache__/rsa.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/__pycache__/rsa.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d1ca5b379d15a3d693d0cec4a8857b650ba5976f Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/__pycache__/rsa.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/__pycache__/utils.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..690037bd08df44a53cfd05357ebf461501fa19ec Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/__pycache__/utils.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/aead.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/aead.py new file mode 100644 index 0000000000000000000000000000000000000000..b36f535f3f8fa6061b26f1b91ad7b9aeb85e0aa5 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/aead.py @@ -0,0 +1,527 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import typing + +from cryptography.exceptions import InvalidTag + +if typing.TYPE_CHECKING: + from cryptography.hazmat.backends.openssl.backend import Backend + from cryptography.hazmat.primitives.ciphers.aead import ( + AESCCM, + AESGCM, + AESOCB3, + AESSIV, + ChaCha20Poly1305, + ) + + _AEADTypes = typing.Union[ + AESCCM, AESGCM, AESOCB3, AESSIV, ChaCha20Poly1305 + ] + + +def _is_evp_aead_supported_cipher( + backend: Backend, cipher: _AEADTypes +) -> bool: + """ + Checks whether the given cipher is supported through + EVP_AEAD rather than the normal OpenSSL EVP_CIPHER API. + """ + from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305 + + return backend._lib.Cryptography_HAS_EVP_AEAD and isinstance( + cipher, ChaCha20Poly1305 + ) + + +def _aead_cipher_supported(backend: Backend, cipher: _AEADTypes) -> bool: + if _is_evp_aead_supported_cipher(backend, cipher): + return True + else: + cipher_name = _evp_cipher_cipher_name(cipher) + if backend._fips_enabled and cipher_name not in backend._fips_aead: + return False + # SIV isn't loaded through get_cipherbyname but instead a new fetch API + # only available in 3.0+. But if we know we're on 3.0+ then we know + # it's supported. + if cipher_name.endswith(b"-siv"): + return backend._lib.CRYPTOGRAPHY_OPENSSL_300_OR_GREATER == 1 + else: + return ( + backend._lib.EVP_get_cipherbyname(cipher_name) + != backend._ffi.NULL + ) + + +def _aead_create_ctx( + backend: Backend, + cipher: _AEADTypes, + key: bytes, +): + if _is_evp_aead_supported_cipher(backend, cipher): + return _evp_aead_create_ctx(backend, cipher, key) + else: + return _evp_cipher_create_ctx(backend, cipher, key) + + +def _encrypt( + backend: Backend, + cipher: _AEADTypes, + nonce: bytes, + data: bytes, + associated_data: typing.List[bytes], + tag_length: int, + ctx: typing.Any = None, +) -> bytes: + if _is_evp_aead_supported_cipher(backend, cipher): + return _evp_aead_encrypt( + backend, cipher, nonce, data, associated_data, tag_length, ctx + ) + else: + return _evp_cipher_encrypt( + backend, cipher, nonce, data, associated_data, tag_length, ctx + ) + + +def _decrypt( + backend: Backend, + cipher: _AEADTypes, + nonce: bytes, + data: bytes, + associated_data: typing.List[bytes], + tag_length: int, + ctx: typing.Any = None, +) -> bytes: + if _is_evp_aead_supported_cipher(backend, cipher): + return _evp_aead_decrypt( + backend, cipher, nonce, data, associated_data, tag_length, ctx + ) + else: + return _evp_cipher_decrypt( + backend, cipher, nonce, data, associated_data, tag_length, ctx + ) + + +def _evp_aead_create_ctx( + backend: Backend, + cipher: _AEADTypes, + key: bytes, + tag_len: typing.Optional[int] = None, +): + aead_cipher = _evp_aead_get_cipher(backend, cipher) + assert aead_cipher is not None + key_ptr = backend._ffi.from_buffer(key) + tag_len = ( + backend._lib.EVP_AEAD_DEFAULT_TAG_LENGTH + if tag_len is None + else tag_len + ) + ctx = backend._lib.Cryptography_EVP_AEAD_CTX_new( + aead_cipher, key_ptr, len(key), tag_len + ) + backend.openssl_assert(ctx != backend._ffi.NULL) + ctx = backend._ffi.gc(ctx, backend._lib.EVP_AEAD_CTX_free) + return ctx + + +def _evp_aead_get_cipher(backend: Backend, cipher: _AEADTypes): + from cryptography.hazmat.primitives.ciphers.aead import ( + ChaCha20Poly1305, + ) + + # Currently only ChaCha20-Poly1305 is supported using this API + assert isinstance(cipher, ChaCha20Poly1305) + return backend._lib.EVP_aead_chacha20_poly1305() + + +def _evp_aead_encrypt( + backend: Backend, + cipher: _AEADTypes, + nonce: bytes, + data: bytes, + associated_data: typing.List[bytes], + tag_length: int, + ctx: typing.Any, +) -> bytes: + assert ctx is not None + + aead_cipher = _evp_aead_get_cipher(backend, cipher) + assert aead_cipher is not None + + out_len = backend._ffi.new("size_t *") + # max_out_len should be in_len plus the result of + # EVP_AEAD_max_overhead. + max_out_len = len(data) + backend._lib.EVP_AEAD_max_overhead(aead_cipher) + out_buf = backend._ffi.new("uint8_t[]", max_out_len) + data_ptr = backend._ffi.from_buffer(data) + nonce_ptr = backend._ffi.from_buffer(nonce) + aad = b"".join(associated_data) + aad_ptr = backend._ffi.from_buffer(aad) + + res = backend._lib.EVP_AEAD_CTX_seal( + ctx, + out_buf, + out_len, + max_out_len, + nonce_ptr, + len(nonce), + data_ptr, + len(data), + aad_ptr, + len(aad), + ) + backend.openssl_assert(res == 1) + encrypted_data = backend._ffi.buffer(out_buf, out_len[0])[:] + return encrypted_data + + +def _evp_aead_decrypt( + backend: Backend, + cipher: _AEADTypes, + nonce: bytes, + data: bytes, + associated_data: typing.List[bytes], + tag_length: int, + ctx: typing.Any, +) -> bytes: + if len(data) < tag_length: + raise InvalidTag + + assert ctx is not None + + out_len = backend._ffi.new("size_t *") + # max_out_len should at least in_len + max_out_len = len(data) + out_buf = backend._ffi.new("uint8_t[]", max_out_len) + data_ptr = backend._ffi.from_buffer(data) + nonce_ptr = backend._ffi.from_buffer(nonce) + aad = b"".join(associated_data) + aad_ptr = backend._ffi.from_buffer(aad) + + res = backend._lib.EVP_AEAD_CTX_open( + ctx, + out_buf, + out_len, + max_out_len, + nonce_ptr, + len(nonce), + data_ptr, + len(data), + aad_ptr, + len(aad), + ) + + if res == 0: + backend._consume_errors() + raise InvalidTag + + decrypted_data = backend._ffi.buffer(out_buf, out_len[0])[:] + return decrypted_data + + +_ENCRYPT = 1 +_DECRYPT = 0 + + +def _evp_cipher_cipher_name(cipher: _AEADTypes) -> bytes: + from cryptography.hazmat.primitives.ciphers.aead import ( + AESCCM, + AESGCM, + AESOCB3, + AESSIV, + ChaCha20Poly1305, + ) + + if isinstance(cipher, ChaCha20Poly1305): + return b"chacha20-poly1305" + elif isinstance(cipher, AESCCM): + return f"aes-{len(cipher._key) * 8}-ccm".encode("ascii") + elif isinstance(cipher, AESOCB3): + return f"aes-{len(cipher._key) * 8}-ocb".encode("ascii") + elif isinstance(cipher, AESSIV): + return f"aes-{len(cipher._key) * 8 // 2}-siv".encode("ascii") + else: + assert isinstance(cipher, AESGCM) + return f"aes-{len(cipher._key) * 8}-gcm".encode("ascii") + + +def _evp_cipher(cipher_name: bytes, backend: Backend): + if cipher_name.endswith(b"-siv"): + evp_cipher = backend._lib.EVP_CIPHER_fetch( + backend._ffi.NULL, + cipher_name, + backend._ffi.NULL, + ) + backend.openssl_assert(evp_cipher != backend._ffi.NULL) + evp_cipher = backend._ffi.gc(evp_cipher, backend._lib.EVP_CIPHER_free) + else: + evp_cipher = backend._lib.EVP_get_cipherbyname(cipher_name) + backend.openssl_assert(evp_cipher != backend._ffi.NULL) + + return evp_cipher + + +def _evp_cipher_create_ctx( + backend: Backend, + cipher: _AEADTypes, + key: bytes, +): + ctx = backend._lib.EVP_CIPHER_CTX_new() + backend.openssl_assert(ctx != backend._ffi.NULL) + ctx = backend._ffi.gc(ctx, backend._lib.EVP_CIPHER_CTX_free) + cipher_name = _evp_cipher_cipher_name(cipher) + evp_cipher = _evp_cipher(cipher_name, backend) + key_ptr = backend._ffi.from_buffer(key) + res = backend._lib.EVP_CipherInit_ex( + ctx, + evp_cipher, + backend._ffi.NULL, + key_ptr, + backend._ffi.NULL, + 0, + ) + backend.openssl_assert(res != 0) + return ctx + + +def _evp_cipher_aead_setup( + backend: Backend, + cipher_name: bytes, + key: bytes, + nonce: bytes, + tag: typing.Optional[bytes], + tag_len: int, + operation: int, +): + evp_cipher = _evp_cipher(cipher_name, backend) + ctx = backend._lib.EVP_CIPHER_CTX_new() + ctx = backend._ffi.gc(ctx, backend._lib.EVP_CIPHER_CTX_free) + res = backend._lib.EVP_CipherInit_ex( + ctx, + evp_cipher, + backend._ffi.NULL, + backend._ffi.NULL, + backend._ffi.NULL, + int(operation == _ENCRYPT), + ) + backend.openssl_assert(res != 0) + # CCM requires the IVLEN to be set before calling SET_TAG on decrypt + res = backend._lib.EVP_CIPHER_CTX_ctrl( + ctx, + backend._lib.EVP_CTRL_AEAD_SET_IVLEN, + len(nonce), + backend._ffi.NULL, + ) + backend.openssl_assert(res != 0) + if operation == _DECRYPT: + assert tag is not None + _evp_cipher_set_tag(backend, ctx, tag) + elif cipher_name.endswith(b"-ccm"): + res = backend._lib.EVP_CIPHER_CTX_ctrl( + ctx, + backend._lib.EVP_CTRL_AEAD_SET_TAG, + tag_len, + backend._ffi.NULL, + ) + backend.openssl_assert(res != 0) + + nonce_ptr = backend._ffi.from_buffer(nonce) + key_ptr = backend._ffi.from_buffer(key) + res = backend._lib.EVP_CipherInit_ex( + ctx, + backend._ffi.NULL, + backend._ffi.NULL, + key_ptr, + nonce_ptr, + int(operation == _ENCRYPT), + ) + backend.openssl_assert(res != 0) + return ctx + + +def _evp_cipher_set_tag(backend, ctx, tag: bytes) -> None: + tag_ptr = backend._ffi.from_buffer(tag) + res = backend._lib.EVP_CIPHER_CTX_ctrl( + ctx, backend._lib.EVP_CTRL_AEAD_SET_TAG, len(tag), tag_ptr + ) + backend.openssl_assert(res != 0) + + +def _evp_cipher_set_nonce_operation( + backend, ctx, nonce: bytes, operation: int +) -> None: + nonce_ptr = backend._ffi.from_buffer(nonce) + res = backend._lib.EVP_CipherInit_ex( + ctx, + backend._ffi.NULL, + backend._ffi.NULL, + backend._ffi.NULL, + nonce_ptr, + int(operation == _ENCRYPT), + ) + backend.openssl_assert(res != 0) + + +def _evp_cipher_set_length(backend: Backend, ctx, data_len: int) -> None: + intptr = backend._ffi.new("int *") + res = backend._lib.EVP_CipherUpdate( + ctx, backend._ffi.NULL, intptr, backend._ffi.NULL, data_len + ) + backend.openssl_assert(res != 0) + + +def _evp_cipher_process_aad( + backend: Backend, ctx, associated_data: bytes +) -> None: + outlen = backend._ffi.new("int *") + a_data_ptr = backend._ffi.from_buffer(associated_data) + res = backend._lib.EVP_CipherUpdate( + ctx, backend._ffi.NULL, outlen, a_data_ptr, len(associated_data) + ) + backend.openssl_assert(res != 0) + + +def _evp_cipher_process_data(backend: Backend, ctx, data: bytes) -> bytes: + outlen = backend._ffi.new("int *") + buf = backend._ffi.new("unsigned char[]", len(data)) + data_ptr = backend._ffi.from_buffer(data) + res = backend._lib.EVP_CipherUpdate(ctx, buf, outlen, data_ptr, len(data)) + if res == 0: + # AES SIV can error here if the data is invalid on decrypt + backend._consume_errors() + raise InvalidTag + return backend._ffi.buffer(buf, outlen[0])[:] + + +def _evp_cipher_encrypt( + backend: Backend, + cipher: _AEADTypes, + nonce: bytes, + data: bytes, + associated_data: typing.List[bytes], + tag_length: int, + ctx: typing.Any = None, +) -> bytes: + from cryptography.hazmat.primitives.ciphers.aead import AESCCM, AESSIV + + if ctx is None: + cipher_name = _evp_cipher_cipher_name(cipher) + ctx = _evp_cipher_aead_setup( + backend, + cipher_name, + cipher._key, + nonce, + None, + tag_length, + _ENCRYPT, + ) + else: + _evp_cipher_set_nonce_operation(backend, ctx, nonce, _ENCRYPT) + + # CCM requires us to pass the length of the data before processing + # anything. + # However calling this with any other AEAD results in an error + if isinstance(cipher, AESCCM): + _evp_cipher_set_length(backend, ctx, len(data)) + + for ad in associated_data: + _evp_cipher_process_aad(backend, ctx, ad) + processed_data = _evp_cipher_process_data(backend, ctx, data) + outlen = backend._ffi.new("int *") + # All AEADs we support besides OCB are streaming so they return nothing + # in finalization. OCB can return up to (16 byte block - 1) bytes so + # we need a buffer here too. + buf = backend._ffi.new("unsigned char[]", 16) + res = backend._lib.EVP_CipherFinal_ex(ctx, buf, outlen) + backend.openssl_assert(res != 0) + processed_data += backend._ffi.buffer(buf, outlen[0])[:] + tag_buf = backend._ffi.new("unsigned char[]", tag_length) + res = backend._lib.EVP_CIPHER_CTX_ctrl( + ctx, backend._lib.EVP_CTRL_AEAD_GET_TAG, tag_length, tag_buf + ) + backend.openssl_assert(res != 0) + tag = backend._ffi.buffer(tag_buf)[:] + + if isinstance(cipher, AESSIV): + # RFC 5297 defines the output as IV || C, where the tag we generate + # is the "IV" and C is the ciphertext. This is the opposite of our + # other AEADs, which are Ciphertext || Tag + backend.openssl_assert(len(tag) == 16) + return tag + processed_data + else: + return processed_data + tag + + +def _evp_cipher_decrypt( + backend: Backend, + cipher: _AEADTypes, + nonce: bytes, + data: bytes, + associated_data: typing.List[bytes], + tag_length: int, + ctx: typing.Any = None, +) -> bytes: + from cryptography.hazmat.primitives.ciphers.aead import AESCCM, AESSIV + + if len(data) < tag_length: + raise InvalidTag + + if isinstance(cipher, AESSIV): + # RFC 5297 defines the output as IV || C, where the tag we generate + # is the "IV" and C is the ciphertext. This is the opposite of our + # other AEADs, which are Ciphertext || Tag + tag = data[:tag_length] + data = data[tag_length:] + else: + tag = data[-tag_length:] + data = data[:-tag_length] + if ctx is None: + cipher_name = _evp_cipher_cipher_name(cipher) + ctx = _evp_cipher_aead_setup( + backend, + cipher_name, + cipher._key, + nonce, + tag, + tag_length, + _DECRYPT, + ) + else: + _evp_cipher_set_nonce_operation(backend, ctx, nonce, _DECRYPT) + _evp_cipher_set_tag(backend, ctx, tag) + + # CCM requires us to pass the length of the data before processing + # anything. + # However calling this with any other AEAD results in an error + if isinstance(cipher, AESCCM): + _evp_cipher_set_length(backend, ctx, len(data)) + + for ad in associated_data: + _evp_cipher_process_aad(backend, ctx, ad) + # CCM has a different error path if the tag doesn't match. Errors are + # raised in Update and Final is irrelevant. + if isinstance(cipher, AESCCM): + outlen = backend._ffi.new("int *") + buf = backend._ffi.new("unsigned char[]", len(data)) + d_ptr = backend._ffi.from_buffer(data) + res = backend._lib.EVP_CipherUpdate(ctx, buf, outlen, d_ptr, len(data)) + if res != 1: + backend._consume_errors() + raise InvalidTag + + processed_data = backend._ffi.buffer(buf, outlen[0])[:] + else: + processed_data = _evp_cipher_process_data(backend, ctx, data) + outlen = backend._ffi.new("int *") + # OCB can return up to 15 bytes (16 byte block - 1) in finalization + buf = backend._ffi.new("unsigned char[]", 16) + res = backend._lib.EVP_CipherFinal_ex(ctx, buf, outlen) + processed_data += backend._ffi.buffer(buf, outlen[0])[:] + if res == 0: + backend._consume_errors() + raise InvalidTag + + return processed_data diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/backend.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/backend.py new file mode 100644 index 0000000000000000000000000000000000000000..f1c79008b6893ac1bff68b429aa849ecd8a96886 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/backend.py @@ -0,0 +1,1938 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import collections +import contextlib +import itertools +import typing +from contextlib import contextmanager + +from cryptography import utils, x509 +from cryptography.exceptions import UnsupportedAlgorithm, _Reasons +from cryptography.hazmat.backends.openssl import aead +from cryptography.hazmat.backends.openssl.ciphers import _CipherContext +from cryptography.hazmat.backends.openssl.cmac import _CMACContext +from cryptography.hazmat.backends.openssl.ec import ( + _EllipticCurvePrivateKey, + _EllipticCurvePublicKey, +) +from cryptography.hazmat.backends.openssl.rsa import ( + _RSAPrivateKey, + _RSAPublicKey, +) +from cryptography.hazmat.bindings._rust import openssl as rust_openssl +from cryptography.hazmat.bindings.openssl import binding +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives._asymmetric import AsymmetricPadding +from cryptography.hazmat.primitives.asymmetric import ( + dh, + dsa, + ec, + ed448, + ed25519, + rsa, + x448, + x25519, +) +from cryptography.hazmat.primitives.asymmetric.padding import ( + MGF1, + OAEP, + PSS, + PKCS1v15, +) +from cryptography.hazmat.primitives.asymmetric.types import ( + PrivateKeyTypes, + PublicKeyTypes, +) +from cryptography.hazmat.primitives.ciphers import ( + BlockCipherAlgorithm, + CipherAlgorithm, +) +from cryptography.hazmat.primitives.ciphers.algorithms import ( + AES, + AES128, + AES256, + ARC4, + SM4, + Camellia, + ChaCha20, + TripleDES, + _BlowfishInternal, + _CAST5Internal, + _IDEAInternal, + _SEEDInternal, +) +from cryptography.hazmat.primitives.ciphers.modes import ( + CBC, + CFB, + CFB8, + CTR, + ECB, + GCM, + OFB, + XTS, + Mode, +) +from cryptography.hazmat.primitives.serialization import ssh +from cryptography.hazmat.primitives.serialization.pkcs12 import ( + PBES, + PKCS12Certificate, + PKCS12KeyAndCertificates, + PKCS12PrivateKeyTypes, + _PKCS12CATypes, +) + +_MemoryBIO = collections.namedtuple("_MemoryBIO", ["bio", "char_ptr"]) + + +# Not actually supported, just used as a marker for some serialization tests. +class _RC2: + pass + + +class Backend: + """ + OpenSSL API binding interfaces. + """ + + name = "openssl" + + # FIPS has opinions about acceptable algorithms and key sizes, but the + # disallowed algorithms are still present in OpenSSL. They just error if + # you try to use them. To avoid that we allowlist the algorithms in + # FIPS 140-3. This isn't ideal, but FIPS 140-3 is trash so here we are. + _fips_aead = { + b"aes-128-ccm", + b"aes-192-ccm", + b"aes-256-ccm", + b"aes-128-gcm", + b"aes-192-gcm", + b"aes-256-gcm", + } + # TripleDES encryption is disallowed/deprecated throughout 2023 in + # FIPS 140-3. To keep it simple we denylist any use of TripleDES (TDEA). + _fips_ciphers = (AES,) + # Sometimes SHA1 is still permissible. That logic is contained + # within the various *_supported methods. + _fips_hashes = ( + hashes.SHA224, + hashes.SHA256, + hashes.SHA384, + hashes.SHA512, + hashes.SHA512_224, + hashes.SHA512_256, + hashes.SHA3_224, + hashes.SHA3_256, + hashes.SHA3_384, + hashes.SHA3_512, + hashes.SHAKE128, + hashes.SHAKE256, + ) + _fips_ecdh_curves = ( + ec.SECP224R1, + ec.SECP256R1, + ec.SECP384R1, + ec.SECP521R1, + ) + _fips_rsa_min_key_size = 2048 + _fips_rsa_min_public_exponent = 65537 + _fips_dsa_min_modulus = 1 << 2048 + _fips_dh_min_key_size = 2048 + _fips_dh_min_modulus = 1 << _fips_dh_min_key_size + + def __init__(self) -> None: + self._binding = binding.Binding() + self._ffi = self._binding.ffi + self._lib = self._binding.lib + self._fips_enabled = rust_openssl.is_fips_enabled() + + self._cipher_registry: typing.Dict[ + typing.Tuple[typing.Type[CipherAlgorithm], typing.Type[Mode]], + typing.Callable, + ] = {} + self._register_default_ciphers() + self._dh_types = [self._lib.EVP_PKEY_DH] + if self._lib.Cryptography_HAS_EVP_PKEY_DHX: + self._dh_types.append(self._lib.EVP_PKEY_DHX) + + def __repr__(self) -> str: + return "".format( + self.openssl_version_text(), + self._fips_enabled, + self._binding._legacy_provider_loaded, + ) + + def openssl_assert( + self, + ok: bool, + errors: typing.Optional[typing.List[rust_openssl.OpenSSLError]] = None, + ) -> None: + return binding._openssl_assert(self._lib, ok, errors=errors) + + def _enable_fips(self) -> None: + # This function enables FIPS mode for OpenSSL 3.0.0 on installs that + # have the FIPS provider installed properly. + self._binding._enable_fips() + assert rust_openssl.is_fips_enabled() + self._fips_enabled = rust_openssl.is_fips_enabled() + + def openssl_version_text(self) -> str: + """ + Friendly string name of the loaded OpenSSL library. This is not + necessarily the same version as it was compiled against. + + Example: OpenSSL 1.1.1d 10 Sep 2019 + """ + return self._ffi.string( + self._lib.OpenSSL_version(self._lib.OPENSSL_VERSION) + ).decode("ascii") + + def openssl_version_number(self) -> int: + return self._lib.OpenSSL_version_num() + + def _evp_md_from_algorithm(self, algorithm: hashes.HashAlgorithm): + if algorithm.name == "blake2b" or algorithm.name == "blake2s": + alg = "{}{}".format( + algorithm.name, algorithm.digest_size * 8 + ).encode("ascii") + else: + alg = algorithm.name.encode("ascii") + + evp_md = self._lib.EVP_get_digestbyname(alg) + return evp_md + + def _evp_md_non_null_from_algorithm(self, algorithm: hashes.HashAlgorithm): + evp_md = self._evp_md_from_algorithm(algorithm) + self.openssl_assert(evp_md != self._ffi.NULL) + return evp_md + + def hash_supported(self, algorithm: hashes.HashAlgorithm) -> bool: + if self._fips_enabled and not isinstance(algorithm, self._fips_hashes): + return False + + evp_md = self._evp_md_from_algorithm(algorithm) + return evp_md != self._ffi.NULL + + def signature_hash_supported( + self, algorithm: hashes.HashAlgorithm + ) -> bool: + # Dedicated check for hashing algorithm use in message digest for + # signatures, e.g. RSA PKCS#1 v1.5 SHA1 (sha1WithRSAEncryption). + if self._fips_enabled and isinstance(algorithm, hashes.SHA1): + return False + return self.hash_supported(algorithm) + + def scrypt_supported(self) -> bool: + if self._fips_enabled: + return False + else: + return self._lib.Cryptography_HAS_SCRYPT == 1 + + def hmac_supported(self, algorithm: hashes.HashAlgorithm) -> bool: + # FIPS mode still allows SHA1 for HMAC + if self._fips_enabled and isinstance(algorithm, hashes.SHA1): + return True + + return self.hash_supported(algorithm) + + def cipher_supported(self, cipher: CipherAlgorithm, mode: Mode) -> bool: + if self._fips_enabled: + # FIPS mode requires AES. TripleDES is disallowed/deprecated in + # FIPS 140-3. + if not isinstance(cipher, self._fips_ciphers): + return False + + try: + adapter = self._cipher_registry[type(cipher), type(mode)] + except KeyError: + return False + evp_cipher = adapter(self, cipher, mode) + return self._ffi.NULL != evp_cipher + + def register_cipher_adapter(self, cipher_cls, mode_cls, adapter) -> None: + if (cipher_cls, mode_cls) in self._cipher_registry: + raise ValueError( + "Duplicate registration for: {} {}.".format( + cipher_cls, mode_cls + ) + ) + self._cipher_registry[cipher_cls, mode_cls] = adapter + + def _register_default_ciphers(self) -> None: + for cipher_cls in [AES, AES128, AES256]: + for mode_cls in [CBC, CTR, ECB, OFB, CFB, CFB8, GCM]: + self.register_cipher_adapter( + cipher_cls, + mode_cls, + GetCipherByName( + "{cipher.name}-{cipher.key_size}-{mode.name}" + ), + ) + for mode_cls in [CBC, CTR, ECB, OFB, CFB]: + self.register_cipher_adapter( + Camellia, + mode_cls, + GetCipherByName("{cipher.name}-{cipher.key_size}-{mode.name}"), + ) + for mode_cls in [CBC, CFB, CFB8, OFB]: + self.register_cipher_adapter( + TripleDES, mode_cls, GetCipherByName("des-ede3-{mode.name}") + ) + self.register_cipher_adapter( + TripleDES, ECB, GetCipherByName("des-ede3") + ) + self.register_cipher_adapter( + ChaCha20, type(None), GetCipherByName("chacha20") + ) + self.register_cipher_adapter(AES, XTS, _get_xts_cipher) + for mode_cls in [ECB, CBC, OFB, CFB, CTR]: + self.register_cipher_adapter( + SM4, mode_cls, GetCipherByName("sm4-{mode.name}") + ) + # Don't register legacy ciphers if they're unavailable. Hypothetically + # this wouldn't be necessary because we test availability by seeing if + # we get an EVP_CIPHER * in the _CipherContext __init__, but OpenSSL 3 + # will return a valid pointer even though the cipher is unavailable. + if ( + self._binding._legacy_provider_loaded + or not self._lib.CRYPTOGRAPHY_OPENSSL_300_OR_GREATER + ): + for mode_cls in [CBC, CFB, OFB, ECB]: + self.register_cipher_adapter( + _BlowfishInternal, + mode_cls, + GetCipherByName("bf-{mode.name}"), + ) + for mode_cls in [CBC, CFB, OFB, ECB]: + self.register_cipher_adapter( + _SEEDInternal, + mode_cls, + GetCipherByName("seed-{mode.name}"), + ) + for cipher_cls, mode_cls in itertools.product( + [_CAST5Internal, _IDEAInternal], + [CBC, OFB, CFB, ECB], + ): + self.register_cipher_adapter( + cipher_cls, + mode_cls, + GetCipherByName("{cipher.name}-{mode.name}"), + ) + self.register_cipher_adapter( + ARC4, type(None), GetCipherByName("rc4") + ) + # We don't actually support RC2, this is just used by some tests. + self.register_cipher_adapter( + _RC2, type(None), GetCipherByName("rc2") + ) + + def create_symmetric_encryption_ctx( + self, cipher: CipherAlgorithm, mode: Mode + ) -> _CipherContext: + return _CipherContext(self, cipher, mode, _CipherContext._ENCRYPT) + + def create_symmetric_decryption_ctx( + self, cipher: CipherAlgorithm, mode: Mode + ) -> _CipherContext: + return _CipherContext(self, cipher, mode, _CipherContext._DECRYPT) + + def pbkdf2_hmac_supported(self, algorithm: hashes.HashAlgorithm) -> bool: + return self.hmac_supported(algorithm) + + def _consume_errors(self) -> typing.List[rust_openssl.OpenSSLError]: + return rust_openssl.capture_error_stack() + + def _bn_to_int(self, bn) -> int: + assert bn != self._ffi.NULL + self.openssl_assert(not self._lib.BN_is_negative(bn)) + + bn_num_bytes = self._lib.BN_num_bytes(bn) + bin_ptr = self._ffi.new("unsigned char[]", bn_num_bytes) + bin_len = self._lib.BN_bn2bin(bn, bin_ptr) + # A zero length means the BN has value 0 + self.openssl_assert(bin_len >= 0) + val = int.from_bytes(self._ffi.buffer(bin_ptr)[:bin_len], "big") + return val + + def _int_to_bn(self, num: int): + """ + Converts a python integer to a BIGNUM. The returned BIGNUM will not + be garbage collected (to support adding them to structs that take + ownership of the object). Be sure to register it for GC if it will + be discarded after use. + """ + binary = num.to_bytes(int(num.bit_length() / 8.0 + 1), "big") + bn_ptr = self._lib.BN_bin2bn(binary, len(binary), self._ffi.NULL) + self.openssl_assert(bn_ptr != self._ffi.NULL) + return bn_ptr + + def generate_rsa_private_key( + self, public_exponent: int, key_size: int + ) -> rsa.RSAPrivateKey: + rsa._verify_rsa_parameters(public_exponent, key_size) + + rsa_cdata = self._lib.RSA_new() + self.openssl_assert(rsa_cdata != self._ffi.NULL) + rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free) + + bn = self._int_to_bn(public_exponent) + bn = self._ffi.gc(bn, self._lib.BN_free) + + res = self._lib.RSA_generate_key_ex( + rsa_cdata, key_size, bn, self._ffi.NULL + ) + self.openssl_assert(res == 1) + evp_pkey = self._rsa_cdata_to_evp_pkey(rsa_cdata) + + # We can skip RSA key validation here since we just generated the key + return _RSAPrivateKey( + self, rsa_cdata, evp_pkey, unsafe_skip_rsa_key_validation=True + ) + + def generate_rsa_parameters_supported( + self, public_exponent: int, key_size: int + ) -> bool: + return ( + public_exponent >= 3 + and public_exponent & 1 != 0 + and key_size >= 512 + ) + + def load_rsa_private_numbers( + self, + numbers: rsa.RSAPrivateNumbers, + unsafe_skip_rsa_key_validation: bool, + ) -> rsa.RSAPrivateKey: + rsa._check_private_key_components( + numbers.p, + numbers.q, + numbers.d, + numbers.dmp1, + numbers.dmq1, + numbers.iqmp, + numbers.public_numbers.e, + numbers.public_numbers.n, + ) + rsa_cdata = self._lib.RSA_new() + self.openssl_assert(rsa_cdata != self._ffi.NULL) + rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free) + p = self._int_to_bn(numbers.p) + q = self._int_to_bn(numbers.q) + d = self._int_to_bn(numbers.d) + dmp1 = self._int_to_bn(numbers.dmp1) + dmq1 = self._int_to_bn(numbers.dmq1) + iqmp = self._int_to_bn(numbers.iqmp) + e = self._int_to_bn(numbers.public_numbers.e) + n = self._int_to_bn(numbers.public_numbers.n) + res = self._lib.RSA_set0_factors(rsa_cdata, p, q) + self.openssl_assert(res == 1) + res = self._lib.RSA_set0_key(rsa_cdata, n, e, d) + self.openssl_assert(res == 1) + res = self._lib.RSA_set0_crt_params(rsa_cdata, dmp1, dmq1, iqmp) + self.openssl_assert(res == 1) + evp_pkey = self._rsa_cdata_to_evp_pkey(rsa_cdata) + + return _RSAPrivateKey( + self, + rsa_cdata, + evp_pkey, + unsafe_skip_rsa_key_validation=unsafe_skip_rsa_key_validation, + ) + + def load_rsa_public_numbers( + self, numbers: rsa.RSAPublicNumbers + ) -> rsa.RSAPublicKey: + rsa._check_public_key_components(numbers.e, numbers.n) + rsa_cdata = self._lib.RSA_new() + self.openssl_assert(rsa_cdata != self._ffi.NULL) + rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free) + e = self._int_to_bn(numbers.e) + n = self._int_to_bn(numbers.n) + res = self._lib.RSA_set0_key(rsa_cdata, n, e, self._ffi.NULL) + self.openssl_assert(res == 1) + evp_pkey = self._rsa_cdata_to_evp_pkey(rsa_cdata) + + return _RSAPublicKey(self, rsa_cdata, evp_pkey) + + def _create_evp_pkey_gc(self): + evp_pkey = self._lib.EVP_PKEY_new() + self.openssl_assert(evp_pkey != self._ffi.NULL) + evp_pkey = self._ffi.gc(evp_pkey, self._lib.EVP_PKEY_free) + return evp_pkey + + def _rsa_cdata_to_evp_pkey(self, rsa_cdata): + evp_pkey = self._create_evp_pkey_gc() + res = self._lib.EVP_PKEY_set1_RSA(evp_pkey, rsa_cdata) + self.openssl_assert(res == 1) + return evp_pkey + + def _bytes_to_bio(self, data: bytes) -> _MemoryBIO: + """ + Return a _MemoryBIO namedtuple of (BIO, char*). + + The char* is the storage for the BIO and it must stay alive until the + BIO is finished with. + """ + data_ptr = self._ffi.from_buffer(data) + bio = self._lib.BIO_new_mem_buf(data_ptr, len(data)) + self.openssl_assert(bio != self._ffi.NULL) + + return _MemoryBIO(self._ffi.gc(bio, self._lib.BIO_free), data_ptr) + + def _create_mem_bio_gc(self): + """ + Creates an empty memory BIO. + """ + bio_method = self._lib.BIO_s_mem() + self.openssl_assert(bio_method != self._ffi.NULL) + bio = self._lib.BIO_new(bio_method) + self.openssl_assert(bio != self._ffi.NULL) + bio = self._ffi.gc(bio, self._lib.BIO_free) + return bio + + def _read_mem_bio(self, bio) -> bytes: + """ + Reads a memory BIO. This only works on memory BIOs. + """ + buf = self._ffi.new("char **") + buf_len = self._lib.BIO_get_mem_data(bio, buf) + self.openssl_assert(buf_len > 0) + self.openssl_assert(buf[0] != self._ffi.NULL) + bio_data = self._ffi.buffer(buf[0], buf_len)[:] + return bio_data + + def _evp_pkey_to_private_key( + self, evp_pkey, unsafe_skip_rsa_key_validation: bool + ) -> PrivateKeyTypes: + """ + Return the appropriate type of PrivateKey given an evp_pkey cdata + pointer. + """ + + key_type = self._lib.EVP_PKEY_id(evp_pkey) + + if key_type == self._lib.EVP_PKEY_RSA: + rsa_cdata = self._lib.EVP_PKEY_get1_RSA(evp_pkey) + self.openssl_assert(rsa_cdata != self._ffi.NULL) + rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free) + return _RSAPrivateKey( + self, + rsa_cdata, + evp_pkey, + unsafe_skip_rsa_key_validation=unsafe_skip_rsa_key_validation, + ) + elif ( + key_type == self._lib.EVP_PKEY_RSA_PSS + and not self._lib.CRYPTOGRAPHY_IS_LIBRESSL + and not self._lib.CRYPTOGRAPHY_IS_BORINGSSL + and not self._lib.CRYPTOGRAPHY_OPENSSL_LESS_THAN_111E + ): + # At the moment the way we handle RSA PSS keys is to strip the + # PSS constraints from them and treat them as normal RSA keys + # Unfortunately the RSA * itself tracks this data so we need to + # extract, serialize, and reload it without the constraints. + rsa_cdata = self._lib.EVP_PKEY_get1_RSA(evp_pkey) + self.openssl_assert(rsa_cdata != self._ffi.NULL) + rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free) + bio = self._create_mem_bio_gc() + res = self._lib.i2d_RSAPrivateKey_bio(bio, rsa_cdata) + self.openssl_assert(res == 1) + return self.load_der_private_key( + self._read_mem_bio(bio), + password=None, + unsafe_skip_rsa_key_validation=unsafe_skip_rsa_key_validation, + ) + elif key_type == self._lib.EVP_PKEY_DSA: + return rust_openssl.dsa.private_key_from_ptr( + int(self._ffi.cast("uintptr_t", evp_pkey)) + ) + elif key_type == self._lib.EVP_PKEY_EC: + ec_cdata = self._lib.EVP_PKEY_get1_EC_KEY(evp_pkey) + self.openssl_assert(ec_cdata != self._ffi.NULL) + ec_cdata = self._ffi.gc(ec_cdata, self._lib.EC_KEY_free) + return _EllipticCurvePrivateKey(self, ec_cdata, evp_pkey) + elif key_type in self._dh_types: + return rust_openssl.dh.private_key_from_ptr( + int(self._ffi.cast("uintptr_t", evp_pkey)) + ) + elif key_type == getattr(self._lib, "EVP_PKEY_ED25519", None): + # EVP_PKEY_ED25519 is not present in CRYPTOGRAPHY_IS_LIBRESSL + return rust_openssl.ed25519.private_key_from_ptr( + int(self._ffi.cast("uintptr_t", evp_pkey)) + ) + elif key_type == getattr(self._lib, "EVP_PKEY_X448", None): + # EVP_PKEY_X448 is not present in CRYPTOGRAPHY_IS_LIBRESSL + return rust_openssl.x448.private_key_from_ptr( + int(self._ffi.cast("uintptr_t", evp_pkey)) + ) + elif key_type == self._lib.EVP_PKEY_X25519: + return rust_openssl.x25519.private_key_from_ptr( + int(self._ffi.cast("uintptr_t", evp_pkey)) + ) + elif key_type == getattr(self._lib, "EVP_PKEY_ED448", None): + # EVP_PKEY_ED448 is not present in CRYPTOGRAPHY_IS_LIBRESSL + return rust_openssl.ed448.private_key_from_ptr( + int(self._ffi.cast("uintptr_t", evp_pkey)) + ) + else: + raise UnsupportedAlgorithm("Unsupported key type.") + + def _evp_pkey_to_public_key(self, evp_pkey) -> PublicKeyTypes: + """ + Return the appropriate type of PublicKey given an evp_pkey cdata + pointer. + """ + + key_type = self._lib.EVP_PKEY_id(evp_pkey) + + if key_type == self._lib.EVP_PKEY_RSA: + rsa_cdata = self._lib.EVP_PKEY_get1_RSA(evp_pkey) + self.openssl_assert(rsa_cdata != self._ffi.NULL) + rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free) + return _RSAPublicKey(self, rsa_cdata, evp_pkey) + elif ( + key_type == self._lib.EVP_PKEY_RSA_PSS + and not self._lib.CRYPTOGRAPHY_IS_LIBRESSL + and not self._lib.CRYPTOGRAPHY_IS_BORINGSSL + and not self._lib.CRYPTOGRAPHY_OPENSSL_LESS_THAN_111E + ): + rsa_cdata = self._lib.EVP_PKEY_get1_RSA(evp_pkey) + self.openssl_assert(rsa_cdata != self._ffi.NULL) + rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free) + bio = self._create_mem_bio_gc() + res = self._lib.i2d_RSAPublicKey_bio(bio, rsa_cdata) + self.openssl_assert(res == 1) + return self.load_der_public_key(self._read_mem_bio(bio)) + elif key_type == self._lib.EVP_PKEY_DSA: + return rust_openssl.dsa.public_key_from_ptr( + int(self._ffi.cast("uintptr_t", evp_pkey)) + ) + elif key_type == self._lib.EVP_PKEY_EC: + ec_cdata = self._lib.EVP_PKEY_get1_EC_KEY(evp_pkey) + if ec_cdata == self._ffi.NULL: + errors = self._consume_errors() + raise ValueError("Unable to load EC key", errors) + ec_cdata = self._ffi.gc(ec_cdata, self._lib.EC_KEY_free) + return _EllipticCurvePublicKey(self, ec_cdata, evp_pkey) + elif key_type in self._dh_types: + return rust_openssl.dh.public_key_from_ptr( + int(self._ffi.cast("uintptr_t", evp_pkey)) + ) + elif key_type == getattr(self._lib, "EVP_PKEY_ED25519", None): + # EVP_PKEY_ED25519 is not present in CRYPTOGRAPHY_IS_LIBRESSL + return rust_openssl.ed25519.public_key_from_ptr( + int(self._ffi.cast("uintptr_t", evp_pkey)) + ) + elif key_type == getattr(self._lib, "EVP_PKEY_X448", None): + # EVP_PKEY_X448 is not present in CRYPTOGRAPHY_IS_LIBRESSL + return rust_openssl.x448.public_key_from_ptr( + int(self._ffi.cast("uintptr_t", evp_pkey)) + ) + elif key_type == self._lib.EVP_PKEY_X25519: + return rust_openssl.x25519.public_key_from_ptr( + int(self._ffi.cast("uintptr_t", evp_pkey)) + ) + elif key_type == getattr(self._lib, "EVP_PKEY_ED448", None): + # EVP_PKEY_ED448 is not present in CRYPTOGRAPHY_IS_LIBRESSL + return rust_openssl.ed448.public_key_from_ptr( + int(self._ffi.cast("uintptr_t", evp_pkey)) + ) + else: + raise UnsupportedAlgorithm("Unsupported key type.") + + def _oaep_hash_supported(self, algorithm: hashes.HashAlgorithm) -> bool: + if self._fips_enabled and isinstance(algorithm, hashes.SHA1): + return False + + return isinstance( + algorithm, + ( + hashes.SHA1, + hashes.SHA224, + hashes.SHA256, + hashes.SHA384, + hashes.SHA512, + ), + ) + + def rsa_padding_supported(self, padding: AsymmetricPadding) -> bool: + if isinstance(padding, PKCS1v15): + return True + elif isinstance(padding, PSS) and isinstance(padding._mgf, MGF1): + # SHA1 is permissible in MGF1 in FIPS even when SHA1 is blocked + # as signature algorithm. + if self._fips_enabled and isinstance( + padding._mgf._algorithm, hashes.SHA1 + ): + return True + else: + return self.hash_supported(padding._mgf._algorithm) + elif isinstance(padding, OAEP) and isinstance(padding._mgf, MGF1): + return self._oaep_hash_supported( + padding._mgf._algorithm + ) and self._oaep_hash_supported(padding._algorithm) + else: + return False + + def rsa_encryption_supported(self, padding: AsymmetricPadding) -> bool: + if self._fips_enabled and isinstance(padding, PKCS1v15): + return False + else: + return self.rsa_padding_supported(padding) + + def generate_dsa_parameters(self, key_size: int) -> dsa.DSAParameters: + if key_size not in (1024, 2048, 3072, 4096): + raise ValueError( + "Key size must be 1024, 2048, 3072, or 4096 bits." + ) + + return rust_openssl.dsa.generate_parameters(key_size) + + def generate_dsa_private_key( + self, parameters: dsa.DSAParameters + ) -> dsa.DSAPrivateKey: + return parameters.generate_private_key() + + def generate_dsa_private_key_and_parameters( + self, key_size: int + ) -> dsa.DSAPrivateKey: + parameters = self.generate_dsa_parameters(key_size) + return self.generate_dsa_private_key(parameters) + + def load_dsa_private_numbers( + self, numbers: dsa.DSAPrivateNumbers + ) -> dsa.DSAPrivateKey: + dsa._check_dsa_private_numbers(numbers) + return rust_openssl.dsa.from_private_numbers(numbers) + + def load_dsa_public_numbers( + self, numbers: dsa.DSAPublicNumbers + ) -> dsa.DSAPublicKey: + dsa._check_dsa_parameters(numbers.parameter_numbers) + return rust_openssl.dsa.from_public_numbers(numbers) + + def load_dsa_parameter_numbers( + self, numbers: dsa.DSAParameterNumbers + ) -> dsa.DSAParameters: + dsa._check_dsa_parameters(numbers) + return rust_openssl.dsa.from_parameter_numbers(numbers) + + def dsa_supported(self) -> bool: + return ( + not self._lib.CRYPTOGRAPHY_IS_BORINGSSL and not self._fips_enabled + ) + + def dsa_hash_supported(self, algorithm: hashes.HashAlgorithm) -> bool: + if not self.dsa_supported(): + return False + return self.signature_hash_supported(algorithm) + + def cmac_algorithm_supported(self, algorithm) -> bool: + return self.cipher_supported( + algorithm, CBC(b"\x00" * algorithm.block_size) + ) + + def create_cmac_ctx(self, algorithm: BlockCipherAlgorithm) -> _CMACContext: + return _CMACContext(self, algorithm) + + def load_pem_private_key( + self, + data: bytes, + password: typing.Optional[bytes], + unsafe_skip_rsa_key_validation: bool, + ) -> PrivateKeyTypes: + return self._load_key( + self._lib.PEM_read_bio_PrivateKey, + data, + password, + unsafe_skip_rsa_key_validation, + ) + + def load_pem_public_key(self, data: bytes) -> PublicKeyTypes: + mem_bio = self._bytes_to_bio(data) + # In OpenSSL 3.0.x the PEM_read_bio_PUBKEY function will invoke + # the default password callback if you pass an encrypted private + # key. This is very, very, very bad as the default callback can + # trigger an interactive console prompt, which will hang the + # Python process. We therefore provide our own callback to + # catch this and error out properly. + userdata = self._ffi.new("CRYPTOGRAPHY_PASSWORD_DATA *") + evp_pkey = self._lib.PEM_read_bio_PUBKEY( + mem_bio.bio, + self._ffi.NULL, + self._ffi.addressof( + self._lib._original_lib, "Cryptography_pem_password_cb" + ), + userdata, + ) + if evp_pkey != self._ffi.NULL: + evp_pkey = self._ffi.gc(evp_pkey, self._lib.EVP_PKEY_free) + return self._evp_pkey_to_public_key(evp_pkey) + else: + # It's not a (RSA/DSA/ECDSA) subjectPublicKeyInfo, but we still + # need to check to see if it is a pure PKCS1 RSA public key (not + # embedded in a subjectPublicKeyInfo) + self._consume_errors() + res = self._lib.BIO_reset(mem_bio.bio) + self.openssl_assert(res == 1) + rsa_cdata = self._lib.PEM_read_bio_RSAPublicKey( + mem_bio.bio, + self._ffi.NULL, + self._ffi.addressof( + self._lib._original_lib, "Cryptography_pem_password_cb" + ), + userdata, + ) + if rsa_cdata != self._ffi.NULL: + rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free) + evp_pkey = self._rsa_cdata_to_evp_pkey(rsa_cdata) + return _RSAPublicKey(self, rsa_cdata, evp_pkey) + else: + self._handle_key_loading_error() + + def load_pem_parameters(self, data: bytes) -> dh.DHParameters: + return rust_openssl.dh.from_pem_parameters(data) + + def load_der_private_key( + self, + data: bytes, + password: typing.Optional[bytes], + unsafe_skip_rsa_key_validation: bool, + ) -> PrivateKeyTypes: + # OpenSSL has a function called d2i_AutoPrivateKey that in theory + # handles this automatically, however it doesn't handle encrypted + # private keys. Instead we try to load the key two different ways. + # First we'll try to load it as a traditional key. + bio_data = self._bytes_to_bio(data) + key = self._evp_pkey_from_der_traditional_key(bio_data, password) + if key: + return self._evp_pkey_to_private_key( + key, unsafe_skip_rsa_key_validation + ) + else: + # Finally we try to load it with the method that handles encrypted + # PKCS8 properly. + return self._load_key( + self._lib.d2i_PKCS8PrivateKey_bio, + data, + password, + unsafe_skip_rsa_key_validation, + ) + + def _evp_pkey_from_der_traditional_key(self, bio_data, password): + key = self._lib.d2i_PrivateKey_bio(bio_data.bio, self._ffi.NULL) + if key != self._ffi.NULL: + key = self._ffi.gc(key, self._lib.EVP_PKEY_free) + if password is not None: + raise TypeError( + "Password was given but private key is not encrypted." + ) + + return key + else: + self._consume_errors() + return None + + def load_der_public_key(self, data: bytes) -> PublicKeyTypes: + mem_bio = self._bytes_to_bio(data) + evp_pkey = self._lib.d2i_PUBKEY_bio(mem_bio.bio, self._ffi.NULL) + if evp_pkey != self._ffi.NULL: + evp_pkey = self._ffi.gc(evp_pkey, self._lib.EVP_PKEY_free) + return self._evp_pkey_to_public_key(evp_pkey) + else: + # It's not a (RSA/DSA/ECDSA) subjectPublicKeyInfo, but we still + # need to check to see if it is a pure PKCS1 RSA public key (not + # embedded in a subjectPublicKeyInfo) + self._consume_errors() + res = self._lib.BIO_reset(mem_bio.bio) + self.openssl_assert(res == 1) + rsa_cdata = self._lib.d2i_RSAPublicKey_bio( + mem_bio.bio, self._ffi.NULL + ) + if rsa_cdata != self._ffi.NULL: + rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free) + evp_pkey = self._rsa_cdata_to_evp_pkey(rsa_cdata) + return _RSAPublicKey(self, rsa_cdata, evp_pkey) + else: + self._handle_key_loading_error() + + def load_der_parameters(self, data: bytes) -> dh.DHParameters: + return rust_openssl.dh.from_der_parameters(data) + + def _cert2ossl(self, cert: x509.Certificate) -> typing.Any: + data = cert.public_bytes(serialization.Encoding.DER) + mem_bio = self._bytes_to_bio(data) + x509 = self._lib.d2i_X509_bio(mem_bio.bio, self._ffi.NULL) + self.openssl_assert(x509 != self._ffi.NULL) + x509 = self._ffi.gc(x509, self._lib.X509_free) + return x509 + + def _ossl2cert(self, x509_ptr: typing.Any) -> x509.Certificate: + bio = self._create_mem_bio_gc() + res = self._lib.i2d_X509_bio(bio, x509_ptr) + self.openssl_assert(res == 1) + return x509.load_der_x509_certificate(self._read_mem_bio(bio)) + + def _key2ossl(self, key: PKCS12PrivateKeyTypes) -> typing.Any: + data = key.private_bytes( + serialization.Encoding.DER, + serialization.PrivateFormat.PKCS8, + serialization.NoEncryption(), + ) + mem_bio = self._bytes_to_bio(data) + + evp_pkey = self._lib.d2i_PrivateKey_bio( + mem_bio.bio, + self._ffi.NULL, + ) + self.openssl_assert(evp_pkey != self._ffi.NULL) + return self._ffi.gc(evp_pkey, self._lib.EVP_PKEY_free) + + def _load_key( + self, openssl_read_func, data, password, unsafe_skip_rsa_key_validation + ) -> PrivateKeyTypes: + mem_bio = self._bytes_to_bio(data) + + userdata = self._ffi.new("CRYPTOGRAPHY_PASSWORD_DATA *") + if password is not None: + utils._check_byteslike("password", password) + password_ptr = self._ffi.from_buffer(password) + userdata.password = password_ptr + userdata.length = len(password) + + evp_pkey = openssl_read_func( + mem_bio.bio, + self._ffi.NULL, + self._ffi.addressof( + self._lib._original_lib, "Cryptography_pem_password_cb" + ), + userdata, + ) + + if evp_pkey == self._ffi.NULL: + if userdata.error != 0: + self._consume_errors() + if userdata.error == -1: + raise TypeError( + "Password was not given but private key is encrypted" + ) + else: + assert userdata.error == -2 + raise ValueError( + "Passwords longer than {} bytes are not supported " + "by this backend.".format(userdata.maxsize - 1) + ) + else: + self._handle_key_loading_error() + + evp_pkey = self._ffi.gc(evp_pkey, self._lib.EVP_PKEY_free) + + if password is not None and userdata.called == 0: + raise TypeError( + "Password was given but private key is not encrypted." + ) + + assert ( + password is not None and userdata.called == 1 + ) or password is None + + return self._evp_pkey_to_private_key( + evp_pkey, unsafe_skip_rsa_key_validation + ) + + def _handle_key_loading_error(self) -> typing.NoReturn: + errors = self._consume_errors() + + if not errors: + raise ValueError( + "Could not deserialize key data. The data may be in an " + "incorrect format or it may be encrypted with an unsupported " + "algorithm." + ) + + elif ( + errors[0]._lib_reason_match( + self._lib.ERR_LIB_EVP, self._lib.EVP_R_BAD_DECRYPT + ) + or errors[0]._lib_reason_match( + self._lib.ERR_LIB_PKCS12, + self._lib.PKCS12_R_PKCS12_CIPHERFINAL_ERROR, + ) + or ( + self._lib.Cryptography_HAS_PROVIDERS + and errors[0]._lib_reason_match( + self._lib.ERR_LIB_PROV, + self._lib.PROV_R_BAD_DECRYPT, + ) + ) + ): + raise ValueError("Bad decrypt. Incorrect password?") + + elif any( + error._lib_reason_match( + self._lib.ERR_LIB_EVP, + self._lib.EVP_R_UNSUPPORTED_PRIVATE_KEY_ALGORITHM, + ) + for error in errors + ): + raise ValueError("Unsupported public key algorithm.") + + else: + raise ValueError( + "Could not deserialize key data. The data may be in an " + "incorrect format, it may be encrypted with an unsupported " + "algorithm, or it may be an unsupported key type (e.g. EC " + "curves with explicit parameters).", + errors, + ) + + def elliptic_curve_supported(self, curve: ec.EllipticCurve) -> bool: + try: + curve_nid = self._elliptic_curve_to_nid(curve) + except UnsupportedAlgorithm: + curve_nid = self._lib.NID_undef + + group = self._lib.EC_GROUP_new_by_curve_name(curve_nid) + + if group == self._ffi.NULL: + self._consume_errors() + return False + else: + self.openssl_assert(curve_nid != self._lib.NID_undef) + self._lib.EC_GROUP_free(group) + return True + + def elliptic_curve_signature_algorithm_supported( + self, + signature_algorithm: ec.EllipticCurveSignatureAlgorithm, + curve: ec.EllipticCurve, + ) -> bool: + # We only support ECDSA right now. + if not isinstance(signature_algorithm, ec.ECDSA): + return False + + return self.elliptic_curve_supported(curve) + + def generate_elliptic_curve_private_key( + self, curve: ec.EllipticCurve + ) -> ec.EllipticCurvePrivateKey: + """ + Generate a new private key on the named curve. + """ + + if self.elliptic_curve_supported(curve): + ec_cdata = self._ec_key_new_by_curve(curve) + + res = self._lib.EC_KEY_generate_key(ec_cdata) + self.openssl_assert(res == 1) + + evp_pkey = self._ec_cdata_to_evp_pkey(ec_cdata) + + return _EllipticCurvePrivateKey(self, ec_cdata, evp_pkey) + else: + raise UnsupportedAlgorithm( + f"Backend object does not support {curve.name}.", + _Reasons.UNSUPPORTED_ELLIPTIC_CURVE, + ) + + def load_elliptic_curve_private_numbers( + self, numbers: ec.EllipticCurvePrivateNumbers + ) -> ec.EllipticCurvePrivateKey: + public = numbers.public_numbers + + ec_cdata = self._ec_key_new_by_curve(public.curve) + + private_value = self._ffi.gc( + self._int_to_bn(numbers.private_value), self._lib.BN_clear_free + ) + res = self._lib.EC_KEY_set_private_key(ec_cdata, private_value) + if res != 1: + self._consume_errors() + raise ValueError("Invalid EC key.") + + with self._tmp_bn_ctx() as bn_ctx: + self._ec_key_set_public_key_affine_coordinates( + ec_cdata, public.x, public.y, bn_ctx + ) + # derive the expected public point and compare it to the one we + # just set based on the values we were given. If they don't match + # this isn't a valid key pair. + group = self._lib.EC_KEY_get0_group(ec_cdata) + self.openssl_assert(group != self._ffi.NULL) + set_point = backend._lib.EC_KEY_get0_public_key(ec_cdata) + self.openssl_assert(set_point != self._ffi.NULL) + computed_point = self._lib.EC_POINT_new(group) + self.openssl_assert(computed_point != self._ffi.NULL) + computed_point = self._ffi.gc( + computed_point, self._lib.EC_POINT_free + ) + res = self._lib.EC_POINT_mul( + group, + computed_point, + private_value, + self._ffi.NULL, + self._ffi.NULL, + bn_ctx, + ) + self.openssl_assert(res == 1) + if ( + self._lib.EC_POINT_cmp( + group, set_point, computed_point, bn_ctx + ) + != 0 + ): + raise ValueError("Invalid EC key.") + + evp_pkey = self._ec_cdata_to_evp_pkey(ec_cdata) + + return _EllipticCurvePrivateKey(self, ec_cdata, evp_pkey) + + def load_elliptic_curve_public_numbers( + self, numbers: ec.EllipticCurvePublicNumbers + ) -> ec.EllipticCurvePublicKey: + ec_cdata = self._ec_key_new_by_curve(numbers.curve) + with self._tmp_bn_ctx() as bn_ctx: + self._ec_key_set_public_key_affine_coordinates( + ec_cdata, numbers.x, numbers.y, bn_ctx + ) + evp_pkey = self._ec_cdata_to_evp_pkey(ec_cdata) + + return _EllipticCurvePublicKey(self, ec_cdata, evp_pkey) + + def load_elliptic_curve_public_bytes( + self, curve: ec.EllipticCurve, point_bytes: bytes + ) -> ec.EllipticCurvePublicKey: + ec_cdata = self._ec_key_new_by_curve(curve) + group = self._lib.EC_KEY_get0_group(ec_cdata) + self.openssl_assert(group != self._ffi.NULL) + point = self._lib.EC_POINT_new(group) + self.openssl_assert(point != self._ffi.NULL) + point = self._ffi.gc(point, self._lib.EC_POINT_free) + with self._tmp_bn_ctx() as bn_ctx: + res = self._lib.EC_POINT_oct2point( + group, point, point_bytes, len(point_bytes), bn_ctx + ) + if res != 1: + self._consume_errors() + raise ValueError("Invalid public bytes for the given curve") + + res = self._lib.EC_KEY_set_public_key(ec_cdata, point) + self.openssl_assert(res == 1) + evp_pkey = self._ec_cdata_to_evp_pkey(ec_cdata) + return _EllipticCurvePublicKey(self, ec_cdata, evp_pkey) + + def derive_elliptic_curve_private_key( + self, private_value: int, curve: ec.EllipticCurve + ) -> ec.EllipticCurvePrivateKey: + ec_cdata = self._ec_key_new_by_curve(curve) + + group = self._lib.EC_KEY_get0_group(ec_cdata) + self.openssl_assert(group != self._ffi.NULL) + + point = self._lib.EC_POINT_new(group) + self.openssl_assert(point != self._ffi.NULL) + point = self._ffi.gc(point, self._lib.EC_POINT_free) + + value = self._int_to_bn(private_value) + value = self._ffi.gc(value, self._lib.BN_clear_free) + + with self._tmp_bn_ctx() as bn_ctx: + res = self._lib.EC_POINT_mul( + group, point, value, self._ffi.NULL, self._ffi.NULL, bn_ctx + ) + self.openssl_assert(res == 1) + + bn_x = self._lib.BN_CTX_get(bn_ctx) + bn_y = self._lib.BN_CTX_get(bn_ctx) + + res = self._lib.EC_POINT_get_affine_coordinates( + group, point, bn_x, bn_y, bn_ctx + ) + if res != 1: + self._consume_errors() + raise ValueError("Unable to derive key from private_value") + + res = self._lib.EC_KEY_set_public_key(ec_cdata, point) + self.openssl_assert(res == 1) + private = self._int_to_bn(private_value) + private = self._ffi.gc(private, self._lib.BN_clear_free) + res = self._lib.EC_KEY_set_private_key(ec_cdata, private) + self.openssl_assert(res == 1) + + evp_pkey = self._ec_cdata_to_evp_pkey(ec_cdata) + + return _EllipticCurvePrivateKey(self, ec_cdata, evp_pkey) + + def _ec_key_new_by_curve(self, curve: ec.EllipticCurve): + curve_nid = self._elliptic_curve_to_nid(curve) + return self._ec_key_new_by_curve_nid(curve_nid) + + def _ec_key_new_by_curve_nid(self, curve_nid: int): + ec_cdata = self._lib.EC_KEY_new_by_curve_name(curve_nid) + self.openssl_assert(ec_cdata != self._ffi.NULL) + return self._ffi.gc(ec_cdata, self._lib.EC_KEY_free) + + def elliptic_curve_exchange_algorithm_supported( + self, algorithm: ec.ECDH, curve: ec.EllipticCurve + ) -> bool: + if self._fips_enabled and not isinstance( + curve, self._fips_ecdh_curves + ): + return False + + return self.elliptic_curve_supported(curve) and isinstance( + algorithm, ec.ECDH + ) + + def _ec_cdata_to_evp_pkey(self, ec_cdata): + evp_pkey = self._create_evp_pkey_gc() + res = self._lib.EVP_PKEY_set1_EC_KEY(evp_pkey, ec_cdata) + self.openssl_assert(res == 1) + return evp_pkey + + def _elliptic_curve_to_nid(self, curve: ec.EllipticCurve) -> int: + """ + Get the NID for a curve name. + """ + + curve_aliases = {"secp192r1": "prime192v1", "secp256r1": "prime256v1"} + + curve_name = curve_aliases.get(curve.name, curve.name) + + curve_nid = self._lib.OBJ_sn2nid(curve_name.encode()) + if curve_nid == self._lib.NID_undef: + raise UnsupportedAlgorithm( + f"{curve.name} is not a supported elliptic curve", + _Reasons.UNSUPPORTED_ELLIPTIC_CURVE, + ) + return curve_nid + + @contextmanager + def _tmp_bn_ctx(self): + bn_ctx = self._lib.BN_CTX_new() + self.openssl_assert(bn_ctx != self._ffi.NULL) + bn_ctx = self._ffi.gc(bn_ctx, self._lib.BN_CTX_free) + self._lib.BN_CTX_start(bn_ctx) + try: + yield bn_ctx + finally: + self._lib.BN_CTX_end(bn_ctx) + + def _ec_key_set_public_key_affine_coordinates( + self, + ec_cdata, + x: int, + y: int, + bn_ctx, + ) -> None: + """ + Sets the public key point in the EC_KEY context to the affine x and y + values. + """ + + if x < 0 or y < 0: + raise ValueError( + "Invalid EC key. Both x and y must be non-negative." + ) + + x = self._ffi.gc(self._int_to_bn(x), self._lib.BN_free) + y = self._ffi.gc(self._int_to_bn(y), self._lib.BN_free) + group = self._lib.EC_KEY_get0_group(ec_cdata) + self.openssl_assert(group != self._ffi.NULL) + point = self._lib.EC_POINT_new(group) + self.openssl_assert(point != self._ffi.NULL) + point = self._ffi.gc(point, self._lib.EC_POINT_free) + res = self._lib.EC_POINT_set_affine_coordinates( + group, point, x, y, bn_ctx + ) + if res != 1: + self._consume_errors() + raise ValueError("Invalid EC key.") + res = self._lib.EC_KEY_set_public_key(ec_cdata, point) + self.openssl_assert(res == 1) + + def _private_key_bytes( + self, + encoding: serialization.Encoding, + format: serialization.PrivateFormat, + encryption_algorithm: serialization.KeySerializationEncryption, + key, + evp_pkey, + cdata, + ) -> bytes: + # validate argument types + if not isinstance(encoding, serialization.Encoding): + raise TypeError("encoding must be an item from the Encoding enum") + if not isinstance(format, serialization.PrivateFormat): + raise TypeError( + "format must be an item from the PrivateFormat enum" + ) + if not isinstance( + encryption_algorithm, serialization.KeySerializationEncryption + ): + raise TypeError( + "Encryption algorithm must be a KeySerializationEncryption " + "instance" + ) + + # validate password + if isinstance(encryption_algorithm, serialization.NoEncryption): + password = b"" + elif isinstance( + encryption_algorithm, serialization.BestAvailableEncryption + ): + password = encryption_algorithm.password + if len(password) > 1023: + raise ValueError( + "Passwords longer than 1023 bytes are not supported by " + "this backend" + ) + elif ( + isinstance( + encryption_algorithm, serialization._KeySerializationEncryption + ) + and encryption_algorithm._format + is format + is serialization.PrivateFormat.OpenSSH + ): + password = encryption_algorithm.password + else: + raise ValueError("Unsupported encryption type") + + # PKCS8 + PEM/DER + if format is serialization.PrivateFormat.PKCS8: + if encoding is serialization.Encoding.PEM: + write_bio = self._lib.PEM_write_bio_PKCS8PrivateKey + elif encoding is serialization.Encoding.DER: + write_bio = self._lib.i2d_PKCS8PrivateKey_bio + else: + raise ValueError("Unsupported encoding for PKCS8") + return self._private_key_bytes_via_bio( + write_bio, evp_pkey, password + ) + + # TraditionalOpenSSL + PEM/DER + if format is serialization.PrivateFormat.TraditionalOpenSSL: + if self._fips_enabled and not isinstance( + encryption_algorithm, serialization.NoEncryption + ): + raise ValueError( + "Encrypted traditional OpenSSL format is not " + "supported in FIPS mode." + ) + key_type = self._lib.EVP_PKEY_id(evp_pkey) + + if encoding is serialization.Encoding.PEM: + if key_type == self._lib.EVP_PKEY_RSA: + write_bio = self._lib.PEM_write_bio_RSAPrivateKey + else: + assert key_type == self._lib.EVP_PKEY_EC + write_bio = self._lib.PEM_write_bio_ECPrivateKey + return self._private_key_bytes_via_bio( + write_bio, cdata, password + ) + + if encoding is serialization.Encoding.DER: + if password: + raise ValueError( + "Encryption is not supported for DER encoded " + "traditional OpenSSL keys" + ) + if key_type == self._lib.EVP_PKEY_RSA: + write_bio = self._lib.i2d_RSAPrivateKey_bio + else: + assert key_type == self._lib.EVP_PKEY_EC + write_bio = self._lib.i2d_ECPrivateKey_bio + return self._bio_func_output(write_bio, cdata) + + raise ValueError("Unsupported encoding for TraditionalOpenSSL") + + # OpenSSH + PEM + if format is serialization.PrivateFormat.OpenSSH: + if encoding is serialization.Encoding.PEM: + return ssh._serialize_ssh_private_key( + key, password, encryption_algorithm + ) + + raise ValueError( + "OpenSSH private key format can only be used" + " with PEM encoding" + ) + + # Anything that key-specific code was supposed to handle earlier, + # like Raw. + raise ValueError("format is invalid with this key") + + def _private_key_bytes_via_bio( + self, write_bio, evp_pkey, password + ) -> bytes: + if not password: + evp_cipher = self._ffi.NULL + else: + # This is a curated value that we will update over time. + evp_cipher = self._lib.EVP_get_cipherbyname(b"aes-256-cbc") + + return self._bio_func_output( + write_bio, + evp_pkey, + evp_cipher, + password, + len(password), + self._ffi.NULL, + self._ffi.NULL, + ) + + def _bio_func_output(self, write_bio, *args) -> bytes: + bio = self._create_mem_bio_gc() + res = write_bio(bio, *args) + self.openssl_assert(res == 1) + return self._read_mem_bio(bio) + + def _public_key_bytes( + self, + encoding: serialization.Encoding, + format: serialization.PublicFormat, + key, + evp_pkey, + cdata, + ) -> bytes: + if not isinstance(encoding, serialization.Encoding): + raise TypeError("encoding must be an item from the Encoding enum") + if not isinstance(format, serialization.PublicFormat): + raise TypeError( + "format must be an item from the PublicFormat enum" + ) + + # SubjectPublicKeyInfo + PEM/DER + if format is serialization.PublicFormat.SubjectPublicKeyInfo: + if encoding is serialization.Encoding.PEM: + write_bio = self._lib.PEM_write_bio_PUBKEY + elif encoding is serialization.Encoding.DER: + write_bio = self._lib.i2d_PUBKEY_bio + else: + raise ValueError( + "SubjectPublicKeyInfo works only with PEM or DER encoding" + ) + return self._bio_func_output(write_bio, evp_pkey) + + # PKCS1 + PEM/DER + if format is serialization.PublicFormat.PKCS1: + # Only RSA is supported here. + key_type = self._lib.EVP_PKEY_id(evp_pkey) + if key_type != self._lib.EVP_PKEY_RSA: + raise ValueError("PKCS1 format is supported only for RSA keys") + + if encoding is serialization.Encoding.PEM: + write_bio = self._lib.PEM_write_bio_RSAPublicKey + elif encoding is serialization.Encoding.DER: + write_bio = self._lib.i2d_RSAPublicKey_bio + else: + raise ValueError("PKCS1 works only with PEM or DER encoding") + return self._bio_func_output(write_bio, cdata) + + # OpenSSH + OpenSSH + if format is serialization.PublicFormat.OpenSSH: + if encoding is serialization.Encoding.OpenSSH: + return ssh.serialize_ssh_public_key(key) + + raise ValueError( + "OpenSSH format must be used with OpenSSH encoding" + ) + + # Anything that key-specific code was supposed to handle earlier, + # like Raw, CompressedPoint, UncompressedPoint + raise ValueError("format is invalid with this key") + + def dh_supported(self) -> bool: + return not self._lib.CRYPTOGRAPHY_IS_BORINGSSL + + def generate_dh_parameters( + self, generator: int, key_size: int + ) -> dh.DHParameters: + return rust_openssl.dh.generate_parameters(generator, key_size) + + def generate_dh_private_key( + self, parameters: dh.DHParameters + ) -> dh.DHPrivateKey: + return parameters.generate_private_key() + + def generate_dh_private_key_and_parameters( + self, generator: int, key_size: int + ) -> dh.DHPrivateKey: + return self.generate_dh_private_key( + self.generate_dh_parameters(generator, key_size) + ) + + def load_dh_private_numbers( + self, numbers: dh.DHPrivateNumbers + ) -> dh.DHPrivateKey: + return rust_openssl.dh.from_private_numbers(numbers) + + def load_dh_public_numbers( + self, numbers: dh.DHPublicNumbers + ) -> dh.DHPublicKey: + return rust_openssl.dh.from_public_numbers(numbers) + + def load_dh_parameter_numbers( + self, numbers: dh.DHParameterNumbers + ) -> dh.DHParameters: + return rust_openssl.dh.from_parameter_numbers(numbers) + + def dh_parameters_supported( + self, p: int, g: int, q: typing.Optional[int] = None + ) -> bool: + try: + rust_openssl.dh.from_parameter_numbers( + dh.DHParameterNumbers(p=p, g=g, q=q) + ) + except ValueError: + return False + else: + return True + + def dh_x942_serialization_supported(self) -> bool: + return self._lib.Cryptography_HAS_EVP_PKEY_DHX == 1 + + def x25519_load_public_bytes(self, data: bytes) -> x25519.X25519PublicKey: + return rust_openssl.x25519.from_public_bytes(data) + + def x25519_load_private_bytes( + self, data: bytes + ) -> x25519.X25519PrivateKey: + return rust_openssl.x25519.from_private_bytes(data) + + def x25519_generate_key(self) -> x25519.X25519PrivateKey: + return rust_openssl.x25519.generate_key() + + def x25519_supported(self) -> bool: + if self._fips_enabled: + return False + return not self._lib.CRYPTOGRAPHY_LIBRESSL_LESS_THAN_370 + + def x448_load_public_bytes(self, data: bytes) -> x448.X448PublicKey: + return rust_openssl.x448.from_public_bytes(data) + + def x448_load_private_bytes(self, data: bytes) -> x448.X448PrivateKey: + return rust_openssl.x448.from_private_bytes(data) + + def x448_generate_key(self) -> x448.X448PrivateKey: + return rust_openssl.x448.generate_key() + + def x448_supported(self) -> bool: + if self._fips_enabled: + return False + return ( + not self._lib.CRYPTOGRAPHY_IS_LIBRESSL + and not self._lib.CRYPTOGRAPHY_IS_BORINGSSL + ) + + def ed25519_supported(self) -> bool: + if self._fips_enabled: + return False + return self._lib.CRYPTOGRAPHY_HAS_WORKING_ED25519 + + def ed25519_load_public_bytes( + self, data: bytes + ) -> ed25519.Ed25519PublicKey: + return rust_openssl.ed25519.from_public_bytes(data) + + def ed25519_load_private_bytes( + self, data: bytes + ) -> ed25519.Ed25519PrivateKey: + return rust_openssl.ed25519.from_private_bytes(data) + + def ed25519_generate_key(self) -> ed25519.Ed25519PrivateKey: + return rust_openssl.ed25519.generate_key() + + def ed448_supported(self) -> bool: + if self._fips_enabled: + return False + return ( + not self._lib.CRYPTOGRAPHY_IS_LIBRESSL + and not self._lib.CRYPTOGRAPHY_IS_BORINGSSL + ) + + def ed448_load_public_bytes(self, data: bytes) -> ed448.Ed448PublicKey: + return rust_openssl.ed448.from_public_bytes(data) + + def ed448_load_private_bytes(self, data: bytes) -> ed448.Ed448PrivateKey: + return rust_openssl.ed448.from_private_bytes(data) + + def ed448_generate_key(self) -> ed448.Ed448PrivateKey: + return rust_openssl.ed448.generate_key() + + def aead_cipher_supported(self, cipher) -> bool: + return aead._aead_cipher_supported(self, cipher) + + def _zero_data(self, data, length: int) -> None: + # We clear things this way because at the moment we're not + # sure of a better way that can guarantee it overwrites the + # memory of a bytearray and doesn't just replace the underlying char *. + for i in range(length): + data[i] = 0 + + @contextlib.contextmanager + def _zeroed_null_terminated_buf(self, data): + """ + This method takes bytes, which can be a bytestring or a mutable + buffer like a bytearray, and yields a null-terminated version of that + data. This is required because PKCS12_parse doesn't take a length with + its password char * and ffi.from_buffer doesn't provide null + termination. So, to support zeroing the data via bytearray we + need to build this ridiculous construct that copies the memory, but + zeroes it after use. + """ + if data is None: + yield self._ffi.NULL + else: + data_len = len(data) + buf = self._ffi.new("char[]", data_len + 1) + self._ffi.memmove(buf, data, data_len) + try: + yield buf + finally: + # Cast to a uint8_t * so we can assign by integer + self._zero_data(self._ffi.cast("uint8_t *", buf), data_len) + + def load_key_and_certificates_from_pkcs12( + self, data: bytes, password: typing.Optional[bytes] + ) -> typing.Tuple[ + typing.Optional[PrivateKeyTypes], + typing.Optional[x509.Certificate], + typing.List[x509.Certificate], + ]: + pkcs12 = self.load_pkcs12(data, password) + return ( + pkcs12.key, + pkcs12.cert.certificate if pkcs12.cert else None, + [cert.certificate for cert in pkcs12.additional_certs], + ) + + def load_pkcs12( + self, data: bytes, password: typing.Optional[bytes] + ) -> PKCS12KeyAndCertificates: + if password is not None: + utils._check_byteslike("password", password) + + bio = self._bytes_to_bio(data) + p12 = self._lib.d2i_PKCS12_bio(bio.bio, self._ffi.NULL) + if p12 == self._ffi.NULL: + self._consume_errors() + raise ValueError("Could not deserialize PKCS12 data") + + p12 = self._ffi.gc(p12, self._lib.PKCS12_free) + evp_pkey_ptr = self._ffi.new("EVP_PKEY **") + x509_ptr = self._ffi.new("X509 **") + sk_x509_ptr = self._ffi.new("Cryptography_STACK_OF_X509 **") + with self._zeroed_null_terminated_buf(password) as password_buf: + res = self._lib.PKCS12_parse( + p12, password_buf, evp_pkey_ptr, x509_ptr, sk_x509_ptr + ) + if res == 0: + self._consume_errors() + raise ValueError("Invalid password or PKCS12 data") + + cert = None + key = None + additional_certificates = [] + + if evp_pkey_ptr[0] != self._ffi.NULL: + evp_pkey = self._ffi.gc(evp_pkey_ptr[0], self._lib.EVP_PKEY_free) + # We don't support turning off RSA key validation when loading + # PKCS12 keys + key = self._evp_pkey_to_private_key( + evp_pkey, unsafe_skip_rsa_key_validation=False + ) + + if x509_ptr[0] != self._ffi.NULL: + x509 = self._ffi.gc(x509_ptr[0], self._lib.X509_free) + cert_obj = self._ossl2cert(x509) + name = None + maybe_name = self._lib.X509_alias_get0(x509, self._ffi.NULL) + if maybe_name != self._ffi.NULL: + name = self._ffi.string(maybe_name) + cert = PKCS12Certificate(cert_obj, name) + + if sk_x509_ptr[0] != self._ffi.NULL: + sk_x509 = self._ffi.gc(sk_x509_ptr[0], self._lib.sk_X509_free) + num = self._lib.sk_X509_num(sk_x509_ptr[0]) + + # In OpenSSL < 3.0.0 PKCS12 parsing reverses the order of the + # certificates. + indices: typing.Iterable[int] + if ( + self._lib.CRYPTOGRAPHY_OPENSSL_300_OR_GREATER + or self._lib.CRYPTOGRAPHY_IS_BORINGSSL + ): + indices = range(num) + else: + indices = reversed(range(num)) + + for i in indices: + x509 = self._lib.sk_X509_value(sk_x509, i) + self.openssl_assert(x509 != self._ffi.NULL) + x509 = self._ffi.gc(x509, self._lib.X509_free) + addl_cert = self._ossl2cert(x509) + addl_name = None + maybe_name = self._lib.X509_alias_get0(x509, self._ffi.NULL) + if maybe_name != self._ffi.NULL: + addl_name = self._ffi.string(maybe_name) + additional_certificates.append( + PKCS12Certificate(addl_cert, addl_name) + ) + + return PKCS12KeyAndCertificates(key, cert, additional_certificates) + + def serialize_key_and_certificates_to_pkcs12( + self, + name: typing.Optional[bytes], + key: typing.Optional[PKCS12PrivateKeyTypes], + cert: typing.Optional[x509.Certificate], + cas: typing.Optional[typing.List[_PKCS12CATypes]], + encryption_algorithm: serialization.KeySerializationEncryption, + ) -> bytes: + password = None + if name is not None: + utils._check_bytes("name", name) + + if isinstance(encryption_algorithm, serialization.NoEncryption): + nid_cert = -1 + nid_key = -1 + pkcs12_iter = 0 + mac_iter = 0 + mac_alg = self._ffi.NULL + elif isinstance( + encryption_algorithm, serialization.BestAvailableEncryption + ): + # PKCS12 encryption is hopeless trash and can never be fixed. + # OpenSSL 3 supports PBESv2, but Libre and Boring do not, so + # we use PBESv1 with 3DES on the older paths. + if self._lib.CRYPTOGRAPHY_OPENSSL_300_OR_GREATER: + nid_cert = self._lib.NID_aes_256_cbc + nid_key = self._lib.NID_aes_256_cbc + else: + nid_cert = self._lib.NID_pbe_WithSHA1And3_Key_TripleDES_CBC + nid_key = self._lib.NID_pbe_WithSHA1And3_Key_TripleDES_CBC + # At least we can set this higher than OpenSSL's default + pkcs12_iter = 20000 + # mac_iter chosen for compatibility reasons, see: + # https://www.openssl.org/docs/man1.1.1/man3/PKCS12_create.html + # Did we mention how lousy PKCS12 encryption is? + mac_iter = 1 + # MAC algorithm can only be set on OpenSSL 3.0.0+ + mac_alg = self._ffi.NULL + password = encryption_algorithm.password + elif ( + isinstance( + encryption_algorithm, serialization._KeySerializationEncryption + ) + and encryption_algorithm._format + is serialization.PrivateFormat.PKCS12 + ): + # Default to OpenSSL's defaults. Behavior will vary based on the + # version of OpenSSL cryptography is compiled against. + nid_cert = 0 + nid_key = 0 + # Use the default iters we use in best available + pkcs12_iter = 20000 + # See the Best Available comment for why this is 1 + mac_iter = 1 + password = encryption_algorithm.password + keycertalg = encryption_algorithm._key_cert_algorithm + if keycertalg is PBES.PBESv1SHA1And3KeyTripleDESCBC: + nid_cert = self._lib.NID_pbe_WithSHA1And3_Key_TripleDES_CBC + nid_key = self._lib.NID_pbe_WithSHA1And3_Key_TripleDES_CBC + elif keycertalg is PBES.PBESv2SHA256AndAES256CBC: + if not self._lib.CRYPTOGRAPHY_OPENSSL_300_OR_GREATER: + raise UnsupportedAlgorithm( + "PBESv2 is not supported by this version of OpenSSL" + ) + nid_cert = self._lib.NID_aes_256_cbc + nid_key = self._lib.NID_aes_256_cbc + else: + assert keycertalg is None + # We use OpenSSL's defaults + + if encryption_algorithm._hmac_hash is not None: + if not self._lib.Cryptography_HAS_PKCS12_SET_MAC: + raise UnsupportedAlgorithm( + "Setting MAC algorithm is not supported by this " + "version of OpenSSL." + ) + mac_alg = self._evp_md_non_null_from_algorithm( + encryption_algorithm._hmac_hash + ) + self.openssl_assert(mac_alg != self._ffi.NULL) + else: + mac_alg = self._ffi.NULL + + if encryption_algorithm._kdf_rounds is not None: + pkcs12_iter = encryption_algorithm._kdf_rounds + + else: + raise ValueError("Unsupported key encryption type") + + if cas is None or len(cas) == 0: + sk_x509 = self._ffi.NULL + else: + sk_x509 = self._lib.sk_X509_new_null() + sk_x509 = self._ffi.gc(sk_x509, self._lib.sk_X509_free) + + # This list is to keep the x509 values alive until end of function + ossl_cas = [] + for ca in cas: + if isinstance(ca, PKCS12Certificate): + ca_alias = ca.friendly_name + ossl_ca = self._cert2ossl(ca.certificate) + if ca_alias is None: + res = self._lib.X509_alias_set1( + ossl_ca, self._ffi.NULL, -1 + ) + else: + res = self._lib.X509_alias_set1( + ossl_ca, ca_alias, len(ca_alias) + ) + self.openssl_assert(res == 1) + else: + ossl_ca = self._cert2ossl(ca) + ossl_cas.append(ossl_ca) + res = self._lib.sk_X509_push(sk_x509, ossl_ca) + backend.openssl_assert(res >= 1) + + with self._zeroed_null_terminated_buf(password) as password_buf: + with self._zeroed_null_terminated_buf(name) as name_buf: + ossl_cert = self._cert2ossl(cert) if cert else self._ffi.NULL + ossl_pkey = ( + self._key2ossl(key) if key is not None else self._ffi.NULL + ) + + p12 = self._lib.PKCS12_create( + password_buf, + name_buf, + ossl_pkey, + ossl_cert, + sk_x509, + nid_key, + nid_cert, + pkcs12_iter, + mac_iter, + 0, + ) + + if ( + self._lib.Cryptography_HAS_PKCS12_SET_MAC + and mac_alg != self._ffi.NULL + ): + self._lib.PKCS12_set_mac( + p12, + password_buf, + -1, + self._ffi.NULL, + 0, + mac_iter, + mac_alg, + ) + + self.openssl_assert(p12 != self._ffi.NULL) + p12 = self._ffi.gc(p12, self._lib.PKCS12_free) + + bio = self._create_mem_bio_gc() + res = self._lib.i2d_PKCS12_bio(bio, p12) + self.openssl_assert(res > 0) + return self._read_mem_bio(bio) + + def poly1305_supported(self) -> bool: + if self._fips_enabled: + return False + return self._lib.Cryptography_HAS_POLY1305 == 1 + + def pkcs7_supported(self) -> bool: + return not self._lib.CRYPTOGRAPHY_IS_BORINGSSL + + def load_pem_pkcs7_certificates( + self, data: bytes + ) -> typing.List[x509.Certificate]: + utils._check_bytes("data", data) + bio = self._bytes_to_bio(data) + p7 = self._lib.PEM_read_bio_PKCS7( + bio.bio, self._ffi.NULL, self._ffi.NULL, self._ffi.NULL + ) + if p7 == self._ffi.NULL: + self._consume_errors() + raise ValueError("Unable to parse PKCS7 data") + + p7 = self._ffi.gc(p7, self._lib.PKCS7_free) + return self._load_pkcs7_certificates(p7) + + def load_der_pkcs7_certificates( + self, data: bytes + ) -> typing.List[x509.Certificate]: + utils._check_bytes("data", data) + bio = self._bytes_to_bio(data) + p7 = self._lib.d2i_PKCS7_bio(bio.bio, self._ffi.NULL) + if p7 == self._ffi.NULL: + self._consume_errors() + raise ValueError("Unable to parse PKCS7 data") + + p7 = self._ffi.gc(p7, self._lib.PKCS7_free) + return self._load_pkcs7_certificates(p7) + + def _load_pkcs7_certificates(self, p7) -> typing.List[x509.Certificate]: + nid = self._lib.OBJ_obj2nid(p7.type) + self.openssl_assert(nid != self._lib.NID_undef) + if nid != self._lib.NID_pkcs7_signed: + raise UnsupportedAlgorithm( + "Only basic signed structures are currently supported. NID" + " for this data was {}".format(nid), + _Reasons.UNSUPPORTED_SERIALIZATION, + ) + + certs: list[x509.Certificate] = [] + if p7.d.sign == self._ffi.NULL: + return certs + + sk_x509 = p7.d.sign.cert + num = self._lib.sk_X509_num(sk_x509) + for i in range(num): + x509 = self._lib.sk_X509_value(sk_x509, i) + self.openssl_assert(x509 != self._ffi.NULL) + cert = self._ossl2cert(x509) + certs.append(cert) + + return certs + + +class GetCipherByName: + def __init__(self, fmt: str): + self._fmt = fmt + + def __call__(self, backend: Backend, cipher: CipherAlgorithm, mode: Mode): + cipher_name = self._fmt.format(cipher=cipher, mode=mode).lower() + evp_cipher = backend._lib.EVP_get_cipherbyname( + cipher_name.encode("ascii") + ) + + # try EVP_CIPHER_fetch if present + if ( + evp_cipher == backend._ffi.NULL + and backend._lib.Cryptography_HAS_300_EVP_CIPHER + ): + evp_cipher = backend._lib.EVP_CIPHER_fetch( + backend._ffi.NULL, + cipher_name.encode("ascii"), + backend._ffi.NULL, + ) + + backend._consume_errors() + return evp_cipher + + +def _get_xts_cipher(backend: Backend, cipher: AES, mode): + cipher_name = f"aes-{cipher.key_size // 2}-xts" + return backend._lib.EVP_get_cipherbyname(cipher_name.encode("ascii")) + + +backend = Backend() diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/ciphers.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/ciphers.py new file mode 100644 index 0000000000000000000000000000000000000000..bc42adbd49a52f21bae6594e364f212188332d27 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/ciphers.py @@ -0,0 +1,281 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import typing + +from cryptography.exceptions import InvalidTag, UnsupportedAlgorithm, _Reasons +from cryptography.hazmat.primitives import ciphers +from cryptography.hazmat.primitives.ciphers import algorithms, modes + +if typing.TYPE_CHECKING: + from cryptography.hazmat.backends.openssl.backend import Backend + + +class _CipherContext: + _ENCRYPT = 1 + _DECRYPT = 0 + _MAX_CHUNK_SIZE = 2**30 - 1 + + def __init__(self, backend: Backend, cipher, mode, operation: int) -> None: + self._backend = backend + self._cipher = cipher + self._mode = mode + self._operation = operation + self._tag: typing.Optional[bytes] = None + + if isinstance(self._cipher, ciphers.BlockCipherAlgorithm): + self._block_size_bytes = self._cipher.block_size // 8 + else: + self._block_size_bytes = 1 + + ctx = self._backend._lib.EVP_CIPHER_CTX_new() + ctx = self._backend._ffi.gc( + ctx, self._backend._lib.EVP_CIPHER_CTX_free + ) + + registry = self._backend._cipher_registry + try: + adapter = registry[type(cipher), type(mode)] + except KeyError: + raise UnsupportedAlgorithm( + "cipher {} in {} mode is not supported " + "by this backend.".format( + cipher.name, mode.name if mode else mode + ), + _Reasons.UNSUPPORTED_CIPHER, + ) + + evp_cipher = adapter(self._backend, cipher, mode) + if evp_cipher == self._backend._ffi.NULL: + msg = f"cipher {cipher.name} " + if mode is not None: + msg += f"in {mode.name} mode " + msg += ( + "is not supported by this backend (Your version of OpenSSL " + "may be too old. Current version: {}.)" + ).format(self._backend.openssl_version_text()) + raise UnsupportedAlgorithm(msg, _Reasons.UNSUPPORTED_CIPHER) + + if isinstance(mode, modes.ModeWithInitializationVector): + iv_nonce = self._backend._ffi.from_buffer( + mode.initialization_vector + ) + elif isinstance(mode, modes.ModeWithTweak): + iv_nonce = self._backend._ffi.from_buffer(mode.tweak) + elif isinstance(mode, modes.ModeWithNonce): + iv_nonce = self._backend._ffi.from_buffer(mode.nonce) + elif isinstance(cipher, algorithms.ChaCha20): + iv_nonce = self._backend._ffi.from_buffer(cipher.nonce) + else: + iv_nonce = self._backend._ffi.NULL + # begin init with cipher and operation type + res = self._backend._lib.EVP_CipherInit_ex( + ctx, + evp_cipher, + self._backend._ffi.NULL, + self._backend._ffi.NULL, + self._backend._ffi.NULL, + operation, + ) + self._backend.openssl_assert(res != 0) + # set the key length to handle variable key ciphers + res = self._backend._lib.EVP_CIPHER_CTX_set_key_length( + ctx, len(cipher.key) + ) + self._backend.openssl_assert(res != 0) + if isinstance(mode, modes.GCM): + res = self._backend._lib.EVP_CIPHER_CTX_ctrl( + ctx, + self._backend._lib.EVP_CTRL_AEAD_SET_IVLEN, + len(iv_nonce), + self._backend._ffi.NULL, + ) + self._backend.openssl_assert(res != 0) + if mode.tag is not None: + res = self._backend._lib.EVP_CIPHER_CTX_ctrl( + ctx, + self._backend._lib.EVP_CTRL_AEAD_SET_TAG, + len(mode.tag), + mode.tag, + ) + self._backend.openssl_assert(res != 0) + self._tag = mode.tag + + # pass key/iv + res = self._backend._lib.EVP_CipherInit_ex( + ctx, + self._backend._ffi.NULL, + self._backend._ffi.NULL, + self._backend._ffi.from_buffer(cipher.key), + iv_nonce, + operation, + ) + + # Check for XTS mode duplicate keys error + errors = self._backend._consume_errors() + lib = self._backend._lib + if res == 0 and ( + ( + not lib.CRYPTOGRAPHY_IS_LIBRESSL + and errors[0]._lib_reason_match( + lib.ERR_LIB_EVP, lib.EVP_R_XTS_DUPLICATED_KEYS + ) + ) + or ( + lib.Cryptography_HAS_PROVIDERS + and errors[0]._lib_reason_match( + lib.ERR_LIB_PROV, lib.PROV_R_XTS_DUPLICATED_KEYS + ) + ) + ): + raise ValueError("In XTS mode duplicated keys are not allowed") + + self._backend.openssl_assert(res != 0, errors=errors) + + # We purposely disable padding here as it's handled higher up in the + # API. + self._backend._lib.EVP_CIPHER_CTX_set_padding(ctx, 0) + self._ctx = ctx + + def update(self, data: bytes) -> bytes: + buf = bytearray(len(data) + self._block_size_bytes - 1) + n = self.update_into(data, buf) + return bytes(buf[:n]) + + def update_into(self, data: bytes, buf: bytes) -> int: + total_data_len = len(data) + if len(buf) < (total_data_len + self._block_size_bytes - 1): + raise ValueError( + "buffer must be at least {} bytes for this " + "payload".format(len(data) + self._block_size_bytes - 1) + ) + + data_processed = 0 + total_out = 0 + outlen = self._backend._ffi.new("int *") + baseoutbuf = self._backend._ffi.from_buffer(buf, require_writable=True) + baseinbuf = self._backend._ffi.from_buffer(data) + + while data_processed != total_data_len: + outbuf = baseoutbuf + total_out + inbuf = baseinbuf + data_processed + inlen = min(self._MAX_CHUNK_SIZE, total_data_len - data_processed) + + res = self._backend._lib.EVP_CipherUpdate( + self._ctx, outbuf, outlen, inbuf, inlen + ) + if res == 0 and isinstance(self._mode, modes.XTS): + self._backend._consume_errors() + raise ValueError( + "In XTS mode you must supply at least a full block in the " + "first update call. For AES this is 16 bytes." + ) + else: + self._backend.openssl_assert(res != 0) + data_processed += inlen + total_out += outlen[0] + + return total_out + + def finalize(self) -> bytes: + if ( + self._operation == self._DECRYPT + and isinstance(self._mode, modes.ModeWithAuthenticationTag) + and self.tag is None + ): + raise ValueError( + "Authentication tag must be provided when decrypting." + ) + + buf = self._backend._ffi.new("unsigned char[]", self._block_size_bytes) + outlen = self._backend._ffi.new("int *") + res = self._backend._lib.EVP_CipherFinal_ex(self._ctx, buf, outlen) + if res == 0: + errors = self._backend._consume_errors() + + if not errors and isinstance(self._mode, modes.GCM): + raise InvalidTag + + lib = self._backend._lib + self._backend.openssl_assert( + errors[0]._lib_reason_match( + lib.ERR_LIB_EVP, + lib.EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH, + ) + or ( + lib.Cryptography_HAS_PROVIDERS + and errors[0]._lib_reason_match( + lib.ERR_LIB_PROV, + lib.PROV_R_WRONG_FINAL_BLOCK_LENGTH, + ) + ) + or ( + lib.CRYPTOGRAPHY_IS_BORINGSSL + and errors[0].reason + == lib.CIPHER_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH + ), + errors=errors, + ) + raise ValueError( + "The length of the provided data is not a multiple of " + "the block length." + ) + + if ( + isinstance(self._mode, modes.GCM) + and self._operation == self._ENCRYPT + ): + tag_buf = self._backend._ffi.new( + "unsigned char[]", self._block_size_bytes + ) + res = self._backend._lib.EVP_CIPHER_CTX_ctrl( + self._ctx, + self._backend._lib.EVP_CTRL_AEAD_GET_TAG, + self._block_size_bytes, + tag_buf, + ) + self._backend.openssl_assert(res != 0) + self._tag = self._backend._ffi.buffer(tag_buf)[:] + + res = self._backend._lib.EVP_CIPHER_CTX_reset(self._ctx) + self._backend.openssl_assert(res == 1) + return self._backend._ffi.buffer(buf)[: outlen[0]] + + def finalize_with_tag(self, tag: bytes) -> bytes: + tag_len = len(tag) + if tag_len < self._mode._min_tag_length: + raise ValueError( + "Authentication tag must be {} bytes or longer.".format( + self._mode._min_tag_length + ) + ) + elif tag_len > self._block_size_bytes: + raise ValueError( + "Authentication tag cannot be more than {} bytes.".format( + self._block_size_bytes + ) + ) + res = self._backend._lib.EVP_CIPHER_CTX_ctrl( + self._ctx, self._backend._lib.EVP_CTRL_AEAD_SET_TAG, len(tag), tag + ) + self._backend.openssl_assert(res != 0) + self._tag = tag + return self.finalize() + + def authenticate_additional_data(self, data: bytes) -> None: + outlen = self._backend._ffi.new("int *") + res = self._backend._lib.EVP_CipherUpdate( + self._ctx, + self._backend._ffi.NULL, + outlen, + self._backend._ffi.from_buffer(data), + len(data), + ) + self._backend.openssl_assert(res != 0) + + @property + def tag(self) -> typing.Optional[bytes]: + return self._tag diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/cmac.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/cmac.py new file mode 100644 index 0000000000000000000000000000000000000000..bdd7fec611d194ec50a3df3efab9adf34b6373e6 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/cmac.py @@ -0,0 +1,89 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import typing + +from cryptography.exceptions import ( + InvalidSignature, + UnsupportedAlgorithm, + _Reasons, +) +from cryptography.hazmat.primitives import constant_time +from cryptography.hazmat.primitives.ciphers.modes import CBC + +if typing.TYPE_CHECKING: + from cryptography.hazmat.backends.openssl.backend import Backend + from cryptography.hazmat.primitives import ciphers + + +class _CMACContext: + def __init__( + self, + backend: Backend, + algorithm: ciphers.BlockCipherAlgorithm, + ctx=None, + ) -> None: + if not backend.cmac_algorithm_supported(algorithm): + raise UnsupportedAlgorithm( + "This backend does not support CMAC.", + _Reasons.UNSUPPORTED_CIPHER, + ) + + self._backend = backend + self._key = algorithm.key + self._algorithm = algorithm + self._output_length = algorithm.block_size // 8 + + if ctx is None: + registry = self._backend._cipher_registry + adapter = registry[type(algorithm), CBC] + + evp_cipher = adapter(self._backend, algorithm, CBC) + + ctx = self._backend._lib.CMAC_CTX_new() + + self._backend.openssl_assert(ctx != self._backend._ffi.NULL) + ctx = self._backend._ffi.gc(ctx, self._backend._lib.CMAC_CTX_free) + + key_ptr = self._backend._ffi.from_buffer(self._key) + res = self._backend._lib.CMAC_Init( + ctx, + key_ptr, + len(self._key), + evp_cipher, + self._backend._ffi.NULL, + ) + self._backend.openssl_assert(res == 1) + + self._ctx = ctx + + def update(self, data: bytes) -> None: + res = self._backend._lib.CMAC_Update(self._ctx, data, len(data)) + self._backend.openssl_assert(res == 1) + + def finalize(self) -> bytes: + buf = self._backend._ffi.new("unsigned char[]", self._output_length) + length = self._backend._ffi.new("size_t *", self._output_length) + res = self._backend._lib.CMAC_Final(self._ctx, buf, length) + self._backend.openssl_assert(res == 1) + + self._ctx = None + + return self._backend._ffi.buffer(buf)[:] + + def copy(self) -> _CMACContext: + copied_ctx = self._backend._lib.CMAC_CTX_new() + copied_ctx = self._backend._ffi.gc( + copied_ctx, self._backend._lib.CMAC_CTX_free + ) + res = self._backend._lib.CMAC_CTX_copy(copied_ctx, self._ctx) + self._backend.openssl_assert(res == 1) + return _CMACContext(self._backend, self._algorithm, ctx=copied_ctx) + + def verify(self, signature: bytes) -> None: + digest = self.finalize() + if not constant_time.bytes_eq(digest, signature): + raise InvalidSignature("Signature did not match digest.") diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/decode_asn1.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/decode_asn1.py new file mode 100644 index 0000000000000000000000000000000000000000..bf123b6285b64a5ac5a64c00c47975ea2285b9dc --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/decode_asn1.py @@ -0,0 +1,32 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography import x509 + +# CRLReason ::= ENUMERATED { +# unspecified (0), +# keyCompromise (1), +# cACompromise (2), +# affiliationChanged (3), +# superseded (4), +# cessationOfOperation (5), +# certificateHold (6), +# -- value 7 is not used +# removeFromCRL (8), +# privilegeWithdrawn (9), +# aACompromise (10) } +_CRL_ENTRY_REASON_ENUM_TO_CODE = { + x509.ReasonFlags.unspecified: 0, + x509.ReasonFlags.key_compromise: 1, + x509.ReasonFlags.ca_compromise: 2, + x509.ReasonFlags.affiliation_changed: 3, + x509.ReasonFlags.superseded: 4, + x509.ReasonFlags.cessation_of_operation: 5, + x509.ReasonFlags.certificate_hold: 6, + x509.ReasonFlags.remove_from_crl: 8, + x509.ReasonFlags.privilege_withdrawn: 9, + x509.ReasonFlags.aa_compromise: 10, +} diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/ec.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/ec.py new file mode 100644 index 0000000000000000000000000000000000000000..9821bd193e2954a916e80140b832b958c8368914 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/ec.py @@ -0,0 +1,328 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import typing + +from cryptography.exceptions import ( + InvalidSignature, + UnsupportedAlgorithm, + _Reasons, +) +from cryptography.hazmat.backends.openssl.utils import ( + _calculate_digest_and_algorithm, + _evp_pkey_derive, +) +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric import ec + +if typing.TYPE_CHECKING: + from cryptography.hazmat.backends.openssl.backend import Backend + + +def _check_signature_algorithm( + signature_algorithm: ec.EllipticCurveSignatureAlgorithm, +) -> None: + if not isinstance(signature_algorithm, ec.ECDSA): + raise UnsupportedAlgorithm( + "Unsupported elliptic curve signature algorithm.", + _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, + ) + + +def _ec_key_curve_sn(backend: Backend, ec_key) -> str: + group = backend._lib.EC_KEY_get0_group(ec_key) + backend.openssl_assert(group != backend._ffi.NULL) + + nid = backend._lib.EC_GROUP_get_curve_name(group) + # The following check is to find EC keys with unnamed curves and raise + # an error for now. + if nid == backend._lib.NID_undef: + raise ValueError( + "ECDSA keys with explicit parameters are unsupported at this time" + ) + + # This is like the above check, but it also catches the case where you + # explicitly encoded a curve with the same parameters as a named curve. + # Don't do that. + if ( + not backend._lib.CRYPTOGRAPHY_IS_LIBRESSL + and backend._lib.EC_GROUP_get_asn1_flag(group) == 0 + ): + raise ValueError( + "ECDSA keys with explicit parameters are unsupported at this time" + ) + + curve_name = backend._lib.OBJ_nid2sn(nid) + backend.openssl_assert(curve_name != backend._ffi.NULL) + + sn = backend._ffi.string(curve_name).decode("ascii") + return sn + + +def _mark_asn1_named_ec_curve(backend: Backend, ec_cdata): + """ + Set the named curve flag on the EC_KEY. This causes OpenSSL to + serialize EC keys along with their curve OID which makes + deserialization easier. + """ + + backend._lib.EC_KEY_set_asn1_flag( + ec_cdata, backend._lib.OPENSSL_EC_NAMED_CURVE + ) + + +def _check_key_infinity(backend: Backend, ec_cdata) -> None: + point = backend._lib.EC_KEY_get0_public_key(ec_cdata) + backend.openssl_assert(point != backend._ffi.NULL) + group = backend._lib.EC_KEY_get0_group(ec_cdata) + backend.openssl_assert(group != backend._ffi.NULL) + if backend._lib.EC_POINT_is_at_infinity(group, point): + raise ValueError( + "Cannot load an EC public key where the point is at infinity" + ) + + +def _sn_to_elliptic_curve(backend: Backend, sn: str) -> ec.EllipticCurve: + try: + return ec._CURVE_TYPES[sn]() + except KeyError: + raise UnsupportedAlgorithm( + f"{sn} is not a supported elliptic curve", + _Reasons.UNSUPPORTED_ELLIPTIC_CURVE, + ) + + +def _ecdsa_sig_sign( + backend: Backend, private_key: _EllipticCurvePrivateKey, data: bytes +) -> bytes: + max_size = backend._lib.ECDSA_size(private_key._ec_key) + backend.openssl_assert(max_size > 0) + + sigbuf = backend._ffi.new("unsigned char[]", max_size) + siglen_ptr = backend._ffi.new("unsigned int[]", 1) + res = backend._lib.ECDSA_sign( + 0, data, len(data), sigbuf, siglen_ptr, private_key._ec_key + ) + backend.openssl_assert(res == 1) + return backend._ffi.buffer(sigbuf)[: siglen_ptr[0]] + + +def _ecdsa_sig_verify( + backend: Backend, + public_key: _EllipticCurvePublicKey, + signature: bytes, + data: bytes, +) -> None: + res = backend._lib.ECDSA_verify( + 0, data, len(data), signature, len(signature), public_key._ec_key + ) + if res != 1: + backend._consume_errors() + raise InvalidSignature + + +class _EllipticCurvePrivateKey(ec.EllipticCurvePrivateKey): + def __init__(self, backend: Backend, ec_key_cdata, evp_pkey): + self._backend = backend + self._ec_key = ec_key_cdata + self._evp_pkey = evp_pkey + + sn = _ec_key_curve_sn(backend, ec_key_cdata) + self._curve = _sn_to_elliptic_curve(backend, sn) + _mark_asn1_named_ec_curve(backend, ec_key_cdata) + _check_key_infinity(backend, ec_key_cdata) + + @property + def curve(self) -> ec.EllipticCurve: + return self._curve + + @property + def key_size(self) -> int: + return self.curve.key_size + + def exchange( + self, algorithm: ec.ECDH, peer_public_key: ec.EllipticCurvePublicKey + ) -> bytes: + if not ( + self._backend.elliptic_curve_exchange_algorithm_supported( + algorithm, self.curve + ) + ): + raise UnsupportedAlgorithm( + "This backend does not support the ECDH algorithm.", + _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM, + ) + + if peer_public_key.curve.name != self.curve.name: + raise ValueError( + "peer_public_key and self are not on the same curve" + ) + + return _evp_pkey_derive(self._backend, self._evp_pkey, peer_public_key) + + def public_key(self) -> ec.EllipticCurvePublicKey: + group = self._backend._lib.EC_KEY_get0_group(self._ec_key) + self._backend.openssl_assert(group != self._backend._ffi.NULL) + + curve_nid = self._backend._lib.EC_GROUP_get_curve_name(group) + public_ec_key = self._backend._ec_key_new_by_curve_nid(curve_nid) + + point = self._backend._lib.EC_KEY_get0_public_key(self._ec_key) + self._backend.openssl_assert(point != self._backend._ffi.NULL) + + res = self._backend._lib.EC_KEY_set_public_key(public_ec_key, point) + self._backend.openssl_assert(res == 1) + + evp_pkey = self._backend._ec_cdata_to_evp_pkey(public_ec_key) + + return _EllipticCurvePublicKey(self._backend, public_ec_key, evp_pkey) + + def private_numbers(self) -> ec.EllipticCurvePrivateNumbers: + bn = self._backend._lib.EC_KEY_get0_private_key(self._ec_key) + private_value = self._backend._bn_to_int(bn) + return ec.EllipticCurvePrivateNumbers( + private_value=private_value, + public_numbers=self.public_key().public_numbers(), + ) + + def private_bytes( + self, + encoding: serialization.Encoding, + format: serialization.PrivateFormat, + encryption_algorithm: serialization.KeySerializationEncryption, + ) -> bytes: + return self._backend._private_key_bytes( + encoding, + format, + encryption_algorithm, + self, + self._evp_pkey, + self._ec_key, + ) + + def sign( + self, + data: bytes, + signature_algorithm: ec.EllipticCurveSignatureAlgorithm, + ) -> bytes: + _check_signature_algorithm(signature_algorithm) + data, _ = _calculate_digest_and_algorithm( + data, + signature_algorithm.algorithm, + ) + return _ecdsa_sig_sign(self._backend, self, data) + + +class _EllipticCurvePublicKey(ec.EllipticCurvePublicKey): + def __init__(self, backend: Backend, ec_key_cdata, evp_pkey): + self._backend = backend + self._ec_key = ec_key_cdata + self._evp_pkey = evp_pkey + + sn = _ec_key_curve_sn(backend, ec_key_cdata) + self._curve = _sn_to_elliptic_curve(backend, sn) + _mark_asn1_named_ec_curve(backend, ec_key_cdata) + _check_key_infinity(backend, ec_key_cdata) + + @property + def curve(self) -> ec.EllipticCurve: + return self._curve + + @property + def key_size(self) -> int: + return self.curve.key_size + + def __eq__(self, other: object) -> bool: + if not isinstance(other, _EllipticCurvePublicKey): + return NotImplemented + + return ( + self._backend._lib.EVP_PKEY_cmp(self._evp_pkey, other._evp_pkey) + == 1 + ) + + def public_numbers(self) -> ec.EllipticCurvePublicNumbers: + group = self._backend._lib.EC_KEY_get0_group(self._ec_key) + self._backend.openssl_assert(group != self._backend._ffi.NULL) + + point = self._backend._lib.EC_KEY_get0_public_key(self._ec_key) + self._backend.openssl_assert(point != self._backend._ffi.NULL) + + with self._backend._tmp_bn_ctx() as bn_ctx: + bn_x = self._backend._lib.BN_CTX_get(bn_ctx) + bn_y = self._backend._lib.BN_CTX_get(bn_ctx) + + res = self._backend._lib.EC_POINT_get_affine_coordinates( + group, point, bn_x, bn_y, bn_ctx + ) + self._backend.openssl_assert(res == 1) + + x = self._backend._bn_to_int(bn_x) + y = self._backend._bn_to_int(bn_y) + + return ec.EllipticCurvePublicNumbers(x=x, y=y, curve=self._curve) + + def _encode_point(self, format: serialization.PublicFormat) -> bytes: + if format is serialization.PublicFormat.CompressedPoint: + conversion = self._backend._lib.POINT_CONVERSION_COMPRESSED + else: + assert format is serialization.PublicFormat.UncompressedPoint + conversion = self._backend._lib.POINT_CONVERSION_UNCOMPRESSED + + group = self._backend._lib.EC_KEY_get0_group(self._ec_key) + self._backend.openssl_assert(group != self._backend._ffi.NULL) + point = self._backend._lib.EC_KEY_get0_public_key(self._ec_key) + self._backend.openssl_assert(point != self._backend._ffi.NULL) + with self._backend._tmp_bn_ctx() as bn_ctx: + buflen = self._backend._lib.EC_POINT_point2oct( + group, point, conversion, self._backend._ffi.NULL, 0, bn_ctx + ) + self._backend.openssl_assert(buflen > 0) + buf = self._backend._ffi.new("char[]", buflen) + res = self._backend._lib.EC_POINT_point2oct( + group, point, conversion, buf, buflen, bn_ctx + ) + self._backend.openssl_assert(buflen == res) + + return self._backend._ffi.buffer(buf)[:] + + def public_bytes( + self, + encoding: serialization.Encoding, + format: serialization.PublicFormat, + ) -> bytes: + if ( + encoding is serialization.Encoding.X962 + or format is serialization.PublicFormat.CompressedPoint + or format is serialization.PublicFormat.UncompressedPoint + ): + if encoding is not serialization.Encoding.X962 or format not in ( + serialization.PublicFormat.CompressedPoint, + serialization.PublicFormat.UncompressedPoint, + ): + raise ValueError( + "X962 encoding must be used with CompressedPoint or " + "UncompressedPoint format" + ) + + return self._encode_point(format) + else: + return self._backend._public_key_bytes( + encoding, format, self, self._evp_pkey, None + ) + + def verify( + self, + signature: bytes, + data: bytes, + signature_algorithm: ec.EllipticCurveSignatureAlgorithm, + ) -> None: + _check_signature_algorithm(signature_algorithm) + data, _ = _calculate_digest_and_algorithm( + data, + signature_algorithm.algorithm, + ) + _ecdsa_sig_verify(self._backend, self, signature, data) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/rsa.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/rsa.py new file mode 100644 index 0000000000000000000000000000000000000000..ef27d4ead570f94d7c7b2cd3847d62e816a44e96 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/rsa.py @@ -0,0 +1,599 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import threading +import typing + +from cryptography.exceptions import ( + InvalidSignature, + UnsupportedAlgorithm, + _Reasons, +) +from cryptography.hazmat.backends.openssl.utils import ( + _calculate_digest_and_algorithm, +) +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import utils as asym_utils +from cryptography.hazmat.primitives.asymmetric.padding import ( + MGF1, + OAEP, + PSS, + AsymmetricPadding, + PKCS1v15, + _Auto, + _DigestLength, + _MaxLength, + calculate_max_pss_salt_length, +) +from cryptography.hazmat.primitives.asymmetric.rsa import ( + RSAPrivateKey, + RSAPrivateNumbers, + RSAPublicKey, + RSAPublicNumbers, +) + +if typing.TYPE_CHECKING: + from cryptography.hazmat.backends.openssl.backend import Backend + + +def _get_rsa_pss_salt_length( + backend: Backend, + pss: PSS, + key: typing.Union[RSAPrivateKey, RSAPublicKey], + hash_algorithm: hashes.HashAlgorithm, +) -> int: + salt = pss._salt_length + + if isinstance(salt, _MaxLength): + return calculate_max_pss_salt_length(key, hash_algorithm) + elif isinstance(salt, _DigestLength): + return hash_algorithm.digest_size + elif isinstance(salt, _Auto): + if isinstance(key, RSAPrivateKey): + raise ValueError( + "PSS salt length can only be set to AUTO when verifying" + ) + return backend._lib.RSA_PSS_SALTLEN_AUTO + else: + return salt + + +def _enc_dec_rsa( + backend: Backend, + key: typing.Union[_RSAPrivateKey, _RSAPublicKey], + data: bytes, + padding: AsymmetricPadding, +) -> bytes: + if not isinstance(padding, AsymmetricPadding): + raise TypeError("Padding must be an instance of AsymmetricPadding.") + + if isinstance(padding, PKCS1v15): + padding_enum = backend._lib.RSA_PKCS1_PADDING + elif isinstance(padding, OAEP): + padding_enum = backend._lib.RSA_PKCS1_OAEP_PADDING + + if not isinstance(padding._mgf, MGF1): + raise UnsupportedAlgorithm( + "Only MGF1 is supported by this backend.", + _Reasons.UNSUPPORTED_MGF, + ) + + if not backend.rsa_padding_supported(padding): + raise UnsupportedAlgorithm( + "This combination of padding and hash algorithm is not " + "supported by this backend.", + _Reasons.UNSUPPORTED_PADDING, + ) + + else: + raise UnsupportedAlgorithm( + f"{padding.name} is not supported by this backend.", + _Reasons.UNSUPPORTED_PADDING, + ) + + return _enc_dec_rsa_pkey_ctx(backend, key, data, padding_enum, padding) + + +def _enc_dec_rsa_pkey_ctx( + backend: Backend, + key: typing.Union[_RSAPrivateKey, _RSAPublicKey], + data: bytes, + padding_enum: int, + padding: AsymmetricPadding, +) -> bytes: + init: typing.Callable[[typing.Any], int] + crypt: typing.Callable[[typing.Any, typing.Any, int, bytes, int], int] + if isinstance(key, _RSAPublicKey): + init = backend._lib.EVP_PKEY_encrypt_init + crypt = backend._lib.EVP_PKEY_encrypt + else: + init = backend._lib.EVP_PKEY_decrypt_init + crypt = backend._lib.EVP_PKEY_decrypt + + pkey_ctx = backend._lib.EVP_PKEY_CTX_new(key._evp_pkey, backend._ffi.NULL) + backend.openssl_assert(pkey_ctx != backend._ffi.NULL) + pkey_ctx = backend._ffi.gc(pkey_ctx, backend._lib.EVP_PKEY_CTX_free) + res = init(pkey_ctx) + backend.openssl_assert(res == 1) + res = backend._lib.EVP_PKEY_CTX_set_rsa_padding(pkey_ctx, padding_enum) + backend.openssl_assert(res > 0) + buf_size = backend._lib.EVP_PKEY_size(key._evp_pkey) + backend.openssl_assert(buf_size > 0) + if isinstance(padding, OAEP): + mgf1_md = backend._evp_md_non_null_from_algorithm( + padding._mgf._algorithm + ) + res = backend._lib.EVP_PKEY_CTX_set_rsa_mgf1_md(pkey_ctx, mgf1_md) + backend.openssl_assert(res > 0) + oaep_md = backend._evp_md_non_null_from_algorithm(padding._algorithm) + res = backend._lib.EVP_PKEY_CTX_set_rsa_oaep_md(pkey_ctx, oaep_md) + backend.openssl_assert(res > 0) + + if ( + isinstance(padding, OAEP) + and padding._label is not None + and len(padding._label) > 0 + ): + # set0_rsa_oaep_label takes ownership of the char * so we need to + # copy it into some new memory + labelptr = backend._lib.OPENSSL_malloc(len(padding._label)) + backend.openssl_assert(labelptr != backend._ffi.NULL) + backend._ffi.memmove(labelptr, padding._label, len(padding._label)) + res = backend._lib.EVP_PKEY_CTX_set0_rsa_oaep_label( + pkey_ctx, labelptr, len(padding._label) + ) + backend.openssl_assert(res == 1) + + outlen = backend._ffi.new("size_t *", buf_size) + buf = backend._ffi.new("unsigned char[]", buf_size) + # Everything from this line onwards is written with the goal of being as + # constant-time as is practical given the constraints of Python and our + # API. See Bleichenbacher's '98 attack on RSA, and its many many variants. + # As such, you should not attempt to change this (particularly to "clean it + # up") without understanding why it was written this way (see + # Chesterton's Fence), and without measuring to verify you have not + # introduced observable time differences. + res = crypt(pkey_ctx, buf, outlen, data, len(data)) + resbuf = backend._ffi.buffer(buf)[: outlen[0]] + backend._lib.ERR_clear_error() + if res <= 0: + raise ValueError("Encryption/decryption failed.") + return resbuf + + +def _rsa_sig_determine_padding( + backend: Backend, + key: typing.Union[_RSAPrivateKey, _RSAPublicKey], + padding: AsymmetricPadding, + algorithm: typing.Optional[hashes.HashAlgorithm], +) -> int: + if not isinstance(padding, AsymmetricPadding): + raise TypeError("Expected provider of AsymmetricPadding.") + + pkey_size = backend._lib.EVP_PKEY_size(key._evp_pkey) + backend.openssl_assert(pkey_size > 0) + + if isinstance(padding, PKCS1v15): + # Hash algorithm is ignored for PKCS1v15-padding, may be None. + padding_enum = backend._lib.RSA_PKCS1_PADDING + elif isinstance(padding, PSS): + if not isinstance(padding._mgf, MGF1): + raise UnsupportedAlgorithm( + "Only MGF1 is supported by this backend.", + _Reasons.UNSUPPORTED_MGF, + ) + + # PSS padding requires a hash algorithm + if not isinstance(algorithm, hashes.HashAlgorithm): + raise TypeError("Expected instance of hashes.HashAlgorithm.") + + # Size of key in bytes - 2 is the maximum + # PSS signature length (salt length is checked later) + if pkey_size - algorithm.digest_size - 2 < 0: + raise ValueError( + "Digest too large for key size. Use a larger " + "key or different digest." + ) + + padding_enum = backend._lib.RSA_PKCS1_PSS_PADDING + else: + raise UnsupportedAlgorithm( + f"{padding.name} is not supported by this backend.", + _Reasons.UNSUPPORTED_PADDING, + ) + + return padding_enum + + +# Hash algorithm can be absent (None) to initialize the context without setting +# any message digest algorithm. This is currently only valid for the PKCS1v15 +# padding type, where it means that the signature data is encoded/decoded +# as provided, without being wrapped in a DigestInfo structure. +def _rsa_sig_setup( + backend: Backend, + padding: AsymmetricPadding, + algorithm: typing.Optional[hashes.HashAlgorithm], + key: typing.Union[_RSAPublicKey, _RSAPrivateKey], + init_func: typing.Callable[[typing.Any], int], +): + padding_enum = _rsa_sig_determine_padding(backend, key, padding, algorithm) + pkey_ctx = backend._lib.EVP_PKEY_CTX_new(key._evp_pkey, backend._ffi.NULL) + backend.openssl_assert(pkey_ctx != backend._ffi.NULL) + pkey_ctx = backend._ffi.gc(pkey_ctx, backend._lib.EVP_PKEY_CTX_free) + res = init_func(pkey_ctx) + if res != 1: + errors = backend._consume_errors() + raise ValueError("Unable to sign/verify with this key", errors) + + if algorithm is not None: + evp_md = backend._evp_md_non_null_from_algorithm(algorithm) + res = backend._lib.EVP_PKEY_CTX_set_signature_md(pkey_ctx, evp_md) + if res <= 0: + backend._consume_errors() + raise UnsupportedAlgorithm( + "{} is not supported by this backend for RSA signing.".format( + algorithm.name + ), + _Reasons.UNSUPPORTED_HASH, + ) + res = backend._lib.EVP_PKEY_CTX_set_rsa_padding(pkey_ctx, padding_enum) + if res <= 0: + backend._consume_errors() + raise UnsupportedAlgorithm( + "{} is not supported for the RSA signature operation.".format( + padding.name + ), + _Reasons.UNSUPPORTED_PADDING, + ) + if isinstance(padding, PSS): + assert isinstance(algorithm, hashes.HashAlgorithm) + res = backend._lib.EVP_PKEY_CTX_set_rsa_pss_saltlen( + pkey_ctx, + _get_rsa_pss_salt_length(backend, padding, key, algorithm), + ) + backend.openssl_assert(res > 0) + + mgf1_md = backend._evp_md_non_null_from_algorithm( + padding._mgf._algorithm + ) + res = backend._lib.EVP_PKEY_CTX_set_rsa_mgf1_md(pkey_ctx, mgf1_md) + backend.openssl_assert(res > 0) + + return pkey_ctx + + +def _rsa_sig_sign( + backend: Backend, + padding: AsymmetricPadding, + algorithm: hashes.HashAlgorithm, + private_key: _RSAPrivateKey, + data: bytes, +) -> bytes: + pkey_ctx = _rsa_sig_setup( + backend, + padding, + algorithm, + private_key, + backend._lib.EVP_PKEY_sign_init, + ) + buflen = backend._ffi.new("size_t *") + res = backend._lib.EVP_PKEY_sign( + pkey_ctx, backend._ffi.NULL, buflen, data, len(data) + ) + backend.openssl_assert(res == 1) + buf = backend._ffi.new("unsigned char[]", buflen[0]) + res = backend._lib.EVP_PKEY_sign(pkey_ctx, buf, buflen, data, len(data)) + if res != 1: + errors = backend._consume_errors() + raise ValueError( + "Digest or salt length too long for key size. Use a larger key " + "or shorter salt length if you are specifying a PSS salt", + errors, + ) + + return backend._ffi.buffer(buf)[:] + + +def _rsa_sig_verify( + backend: Backend, + padding: AsymmetricPadding, + algorithm: hashes.HashAlgorithm, + public_key: _RSAPublicKey, + signature: bytes, + data: bytes, +) -> None: + pkey_ctx = _rsa_sig_setup( + backend, + padding, + algorithm, + public_key, + backend._lib.EVP_PKEY_verify_init, + ) + res = backend._lib.EVP_PKEY_verify( + pkey_ctx, signature, len(signature), data, len(data) + ) + # The previous call can return negative numbers in the event of an + # error. This is not a signature failure but we need to fail if it + # occurs. + backend.openssl_assert(res >= 0) + if res == 0: + backend._consume_errors() + raise InvalidSignature + + +def _rsa_sig_recover( + backend: Backend, + padding: AsymmetricPadding, + algorithm: typing.Optional[hashes.HashAlgorithm], + public_key: _RSAPublicKey, + signature: bytes, +) -> bytes: + pkey_ctx = _rsa_sig_setup( + backend, + padding, + algorithm, + public_key, + backend._lib.EVP_PKEY_verify_recover_init, + ) + + # Attempt to keep the rest of the code in this function as constant/time + # as possible. See the comment in _enc_dec_rsa_pkey_ctx. Note that the + # buflen parameter is used even though its value may be undefined in the + # error case. Due to the tolerant nature of Python slicing this does not + # trigger any exceptions. + maxlen = backend._lib.EVP_PKEY_size(public_key._evp_pkey) + backend.openssl_assert(maxlen > 0) + buf = backend._ffi.new("unsigned char[]", maxlen) + buflen = backend._ffi.new("size_t *", maxlen) + res = backend._lib.EVP_PKEY_verify_recover( + pkey_ctx, buf, buflen, signature, len(signature) + ) + resbuf = backend._ffi.buffer(buf)[: buflen[0]] + backend._lib.ERR_clear_error() + # Assume that all parameter errors are handled during the setup phase and + # any error here is due to invalid signature. + if res != 1: + raise InvalidSignature + return resbuf + + +class _RSAPrivateKey(RSAPrivateKey): + _evp_pkey: object + _rsa_cdata: object + _key_size: int + + def __init__( + self, + backend: Backend, + rsa_cdata, + evp_pkey, + *, + unsafe_skip_rsa_key_validation: bool, + ): + res: int + # RSA_check_key is slower in OpenSSL 3.0.0 due to improved + # primality checking. In normal use this is unlikely to be a problem + # since users don't load new keys constantly, but for TESTING we've + # added an init arg that allows skipping the checks. You should not + # use this in production code unless you understand the consequences. + if not unsafe_skip_rsa_key_validation: + res = backend._lib.RSA_check_key(rsa_cdata) + if res != 1: + errors = backend._consume_errors() + raise ValueError("Invalid private key", errors) + # 2 is prime and passes an RSA key check, so we also check + # if p and q are odd just to be safe. + p = backend._ffi.new("BIGNUM **") + q = backend._ffi.new("BIGNUM **") + backend._lib.RSA_get0_factors(rsa_cdata, p, q) + backend.openssl_assert(p[0] != backend._ffi.NULL) + backend.openssl_assert(q[0] != backend._ffi.NULL) + p_odd = backend._lib.BN_is_odd(p[0]) + q_odd = backend._lib.BN_is_odd(q[0]) + if p_odd != 1 or q_odd != 1: + errors = backend._consume_errors() + raise ValueError("Invalid private key", errors) + + self._backend = backend + self._rsa_cdata = rsa_cdata + self._evp_pkey = evp_pkey + # Used for lazy blinding + self._blinded = False + self._blinding_lock = threading.Lock() + + n = self._backend._ffi.new("BIGNUM **") + self._backend._lib.RSA_get0_key( + self._rsa_cdata, + n, + self._backend._ffi.NULL, + self._backend._ffi.NULL, + ) + self._backend.openssl_assert(n[0] != self._backend._ffi.NULL) + self._key_size = self._backend._lib.BN_num_bits(n[0]) + + def _enable_blinding(self) -> None: + # If you call blind on an already blinded RSA key OpenSSL will turn + # it off and back on, which is a performance hit we want to avoid. + if not self._blinded: + with self._blinding_lock: + self._non_threadsafe_enable_blinding() + + def _non_threadsafe_enable_blinding(self) -> None: + # This is only a separate function to allow for testing to cover both + # branches. It should never be invoked except through _enable_blinding. + # Check if it's not True again in case another thread raced past the + # first non-locked check. + if not self._blinded: + res = self._backend._lib.RSA_blinding_on( + self._rsa_cdata, self._backend._ffi.NULL + ) + self._backend.openssl_assert(res == 1) + self._blinded = True + + @property + def key_size(self) -> int: + return self._key_size + + def decrypt(self, ciphertext: bytes, padding: AsymmetricPadding) -> bytes: + self._enable_blinding() + key_size_bytes = (self.key_size + 7) // 8 + if key_size_bytes != len(ciphertext): + raise ValueError("Ciphertext length must be equal to key size.") + + return _enc_dec_rsa(self._backend, self, ciphertext, padding) + + def public_key(self) -> RSAPublicKey: + ctx = self._backend._lib.RSAPublicKey_dup(self._rsa_cdata) + self._backend.openssl_assert(ctx != self._backend._ffi.NULL) + ctx = self._backend._ffi.gc(ctx, self._backend._lib.RSA_free) + evp_pkey = self._backend._rsa_cdata_to_evp_pkey(ctx) + return _RSAPublicKey(self._backend, ctx, evp_pkey) + + def private_numbers(self) -> RSAPrivateNumbers: + n = self._backend._ffi.new("BIGNUM **") + e = self._backend._ffi.new("BIGNUM **") + d = self._backend._ffi.new("BIGNUM **") + p = self._backend._ffi.new("BIGNUM **") + q = self._backend._ffi.new("BIGNUM **") + dmp1 = self._backend._ffi.new("BIGNUM **") + dmq1 = self._backend._ffi.new("BIGNUM **") + iqmp = self._backend._ffi.new("BIGNUM **") + self._backend._lib.RSA_get0_key(self._rsa_cdata, n, e, d) + self._backend.openssl_assert(n[0] != self._backend._ffi.NULL) + self._backend.openssl_assert(e[0] != self._backend._ffi.NULL) + self._backend.openssl_assert(d[0] != self._backend._ffi.NULL) + self._backend._lib.RSA_get0_factors(self._rsa_cdata, p, q) + self._backend.openssl_assert(p[0] != self._backend._ffi.NULL) + self._backend.openssl_assert(q[0] != self._backend._ffi.NULL) + self._backend._lib.RSA_get0_crt_params( + self._rsa_cdata, dmp1, dmq1, iqmp + ) + self._backend.openssl_assert(dmp1[0] != self._backend._ffi.NULL) + self._backend.openssl_assert(dmq1[0] != self._backend._ffi.NULL) + self._backend.openssl_assert(iqmp[0] != self._backend._ffi.NULL) + return RSAPrivateNumbers( + p=self._backend._bn_to_int(p[0]), + q=self._backend._bn_to_int(q[0]), + d=self._backend._bn_to_int(d[0]), + dmp1=self._backend._bn_to_int(dmp1[0]), + dmq1=self._backend._bn_to_int(dmq1[0]), + iqmp=self._backend._bn_to_int(iqmp[0]), + public_numbers=RSAPublicNumbers( + e=self._backend._bn_to_int(e[0]), + n=self._backend._bn_to_int(n[0]), + ), + ) + + def private_bytes( + self, + encoding: serialization.Encoding, + format: serialization.PrivateFormat, + encryption_algorithm: serialization.KeySerializationEncryption, + ) -> bytes: + return self._backend._private_key_bytes( + encoding, + format, + encryption_algorithm, + self, + self._evp_pkey, + self._rsa_cdata, + ) + + def sign( + self, + data: bytes, + padding: AsymmetricPadding, + algorithm: typing.Union[asym_utils.Prehashed, hashes.HashAlgorithm], + ) -> bytes: + self._enable_blinding() + data, algorithm = _calculate_digest_and_algorithm(data, algorithm) + return _rsa_sig_sign(self._backend, padding, algorithm, self, data) + + +class _RSAPublicKey(RSAPublicKey): + _evp_pkey: object + _rsa_cdata: object + _key_size: int + + def __init__(self, backend: Backend, rsa_cdata, evp_pkey): + self._backend = backend + self._rsa_cdata = rsa_cdata + self._evp_pkey = evp_pkey + + n = self._backend._ffi.new("BIGNUM **") + self._backend._lib.RSA_get0_key( + self._rsa_cdata, + n, + self._backend._ffi.NULL, + self._backend._ffi.NULL, + ) + self._backend.openssl_assert(n[0] != self._backend._ffi.NULL) + self._key_size = self._backend._lib.BN_num_bits(n[0]) + + @property + def key_size(self) -> int: + return self._key_size + + def __eq__(self, other: object) -> bool: + if not isinstance(other, _RSAPublicKey): + return NotImplemented + + return ( + self._backend._lib.EVP_PKEY_cmp(self._evp_pkey, other._evp_pkey) + == 1 + ) + + def encrypt(self, plaintext: bytes, padding: AsymmetricPadding) -> bytes: + return _enc_dec_rsa(self._backend, self, plaintext, padding) + + def public_numbers(self) -> RSAPublicNumbers: + n = self._backend._ffi.new("BIGNUM **") + e = self._backend._ffi.new("BIGNUM **") + self._backend._lib.RSA_get0_key( + self._rsa_cdata, n, e, self._backend._ffi.NULL + ) + self._backend.openssl_assert(n[0] != self._backend._ffi.NULL) + self._backend.openssl_assert(e[0] != self._backend._ffi.NULL) + return RSAPublicNumbers( + e=self._backend._bn_to_int(e[0]), + n=self._backend._bn_to_int(n[0]), + ) + + def public_bytes( + self, + encoding: serialization.Encoding, + format: serialization.PublicFormat, + ) -> bytes: + return self._backend._public_key_bytes( + encoding, format, self, self._evp_pkey, self._rsa_cdata + ) + + def verify( + self, + signature: bytes, + data: bytes, + padding: AsymmetricPadding, + algorithm: typing.Union[asym_utils.Prehashed, hashes.HashAlgorithm], + ) -> None: + data, algorithm = _calculate_digest_and_algorithm(data, algorithm) + _rsa_sig_verify( + self._backend, padding, algorithm, self, signature, data + ) + + def recover_data_from_signature( + self, + signature: bytes, + padding: AsymmetricPadding, + algorithm: typing.Optional[hashes.HashAlgorithm], + ) -> bytes: + if isinstance(algorithm, asym_utils.Prehashed): + raise TypeError( + "Prehashed is only supported in the sign and verify methods. " + "It cannot be used with recover_data_from_signature." + ) + return _rsa_sig_recover( + self._backend, padding, algorithm, self, signature + ) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/utils.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..5b404defde33449e33da554a80aa28ac23230938 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/backends/openssl/utils.py @@ -0,0 +1,63 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import typing + +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives.asymmetric.utils import Prehashed + +if typing.TYPE_CHECKING: + from cryptography.hazmat.backends.openssl.backend import Backend + + +def _evp_pkey_derive(backend: Backend, evp_pkey, peer_public_key) -> bytes: + ctx = backend._lib.EVP_PKEY_CTX_new(evp_pkey, backend._ffi.NULL) + backend.openssl_assert(ctx != backend._ffi.NULL) + ctx = backend._ffi.gc(ctx, backend._lib.EVP_PKEY_CTX_free) + res = backend._lib.EVP_PKEY_derive_init(ctx) + backend.openssl_assert(res == 1) + + if backend._lib.Cryptography_HAS_EVP_PKEY_SET_PEER_EX: + res = backend._lib.EVP_PKEY_derive_set_peer_ex( + ctx, peer_public_key._evp_pkey, 0 + ) + else: + res = backend._lib.EVP_PKEY_derive_set_peer( + ctx, peer_public_key._evp_pkey + ) + backend.openssl_assert(res == 1) + + keylen = backend._ffi.new("size_t *") + res = backend._lib.EVP_PKEY_derive(ctx, backend._ffi.NULL, keylen) + backend.openssl_assert(res == 1) + backend.openssl_assert(keylen[0] > 0) + buf = backend._ffi.new("unsigned char[]", keylen[0]) + res = backend._lib.EVP_PKEY_derive(ctx, buf, keylen) + if res != 1: + errors = backend._consume_errors() + raise ValueError("Error computing shared key.", errors) + + return backend._ffi.buffer(buf, keylen[0])[:] + + +def _calculate_digest_and_algorithm( + data: bytes, + algorithm: typing.Union[Prehashed, hashes.HashAlgorithm], +) -> typing.Tuple[bytes, hashes.HashAlgorithm]: + if not isinstance(algorithm, Prehashed): + hash_ctx = hashes.Hash(algorithm) + hash_ctx.update(data) + data = hash_ctx.finalize() + else: + algorithm = algorithm._algorithm + + if len(data) != algorithm.digest_size: + raise ValueError( + "The provided data must be the same length as the hash " + "algorithm's digest size." + ) + + return (data, algorithm) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b509336233c2fafe4185a49da5909c8bbb38dfd7 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/__init__.py @@ -0,0 +1,3 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f81e2eaa929fd1040fe3076db8a0e995b4653352 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust.abi3.so b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..f1c2e946f830fb0cb51b2a1f189dce0da4065e62 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:aa46eb77bd9337bbe4d22bc0cff544f9979f3720f108bc0b4a2033860305f3e4 +size 13787648 diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/__init__.pyi b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..94a37a20aa962dccf5d403dcad17c69ffd57c455 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/__init__.pyi @@ -0,0 +1,34 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +import types +import typing + +def check_pkcs7_padding(data: bytes) -> bool: ... +def check_ansix923_padding(data: bytes) -> bool: ... + +class ObjectIdentifier: + def __init__(self, val: str) -> None: ... + @property + def dotted_string(self) -> str: ... + @property + def _name(self) -> str: ... + +T = typing.TypeVar("T") + +class FixedPool(typing.Generic[T]): + def __init__( + self, + create: typing.Callable[[], T], + ) -> None: ... + def acquire(self) -> PoolAcquisition[T]: ... + +class PoolAcquisition(typing.Generic[T]): + def __enter__(self) -> T: ... + def __exit__( + self, + exc_type: typing.Optional[typing.Type[BaseException]], + exc_value: typing.Optional[BaseException], + exc_tb: typing.Optional[types.TracebackType], + ) -> None: ... diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/_openssl.pyi b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/_openssl.pyi new file mode 100644 index 0000000000000000000000000000000000000000..80100082acd30b6bc69e5b8ab0972d77a33dc11a --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/_openssl.pyi @@ -0,0 +1,8 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +import typing + +lib = typing.Any +ffi = typing.Any diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/asn1.pyi b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/asn1.pyi new file mode 100644 index 0000000000000000000000000000000000000000..a8369ba8383e639c2b1173008051ecc72450bf8a --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/asn1.pyi @@ -0,0 +1,16 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +import typing + +class TestCertificate: + not_after_tag: int + not_before_tag: int + issuer_value_tags: typing.List[int] + subject_value_tags: typing.List[int] + +def decode_dss_signature(signature: bytes) -> typing.Tuple[int, int]: ... +def encode_dss_signature(r: int, s: int) -> bytes: ... +def parse_spki_for_data(data: bytes) -> bytes: ... +def test_parse_certificate(data: bytes) -> TestCertificate: ... diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/exceptions.pyi b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/exceptions.pyi new file mode 100644 index 0000000000000000000000000000000000000000..09f46b1e817f806873c4a4bdd7b8466046b5f64d --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/exceptions.pyi @@ -0,0 +1,17 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +class _Reasons: + BACKEND_MISSING_INTERFACE: _Reasons + UNSUPPORTED_HASH: _Reasons + UNSUPPORTED_CIPHER: _Reasons + UNSUPPORTED_PADDING: _Reasons + UNSUPPORTED_MGF: _Reasons + UNSUPPORTED_PUBLIC_KEY_ALGORITHM: _Reasons + UNSUPPORTED_ELLIPTIC_CURVE: _Reasons + UNSUPPORTED_SERIALIZATION: _Reasons + UNSUPPORTED_X509: _Reasons + UNSUPPORTED_EXCHANGE_ALGORITHM: _Reasons + UNSUPPORTED_DIFFIE_HELLMAN: _Reasons + UNSUPPORTED_MAC: _Reasons diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/ocsp.pyi b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/ocsp.pyi new file mode 100644 index 0000000000000000000000000000000000000000..4671eb9ba34df990a5e95c2aad354f67b500ba0c --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/ocsp.pyi @@ -0,0 +1,25 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +import typing + +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives.asymmetric.types import PrivateKeyTypes +from cryptography.x509.ocsp import ( + OCSPRequest, + OCSPRequestBuilder, + OCSPResponse, + OCSPResponseBuilder, + OCSPResponseStatus, +) + +def load_der_ocsp_request(data: bytes) -> OCSPRequest: ... +def load_der_ocsp_response(data: bytes) -> OCSPResponse: ... +def create_ocsp_request(builder: OCSPRequestBuilder) -> OCSPRequest: ... +def create_ocsp_response( + status: OCSPResponseStatus, + builder: typing.Optional[OCSPResponseBuilder], + private_key: typing.Optional[PrivateKeyTypes], + hash_algorithm: typing.Optional[hashes.HashAlgorithm], +) -> OCSPResponse: ... diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/openssl/__init__.pyi b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/openssl/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..82f30d20b0ab2a349fc160d55454854bb1362d5e --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/openssl/__init__.pyi @@ -0,0 +1,47 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +import typing + +from cryptography.hazmat.bindings._rust.openssl import ( + dh, + dsa, + ed448, + ed25519, + hashes, + hmac, + kdf, + poly1305, + x448, + x25519, +) + +__all__ = [ + "openssl_version", + "raise_openssl_error", + "dh", + "dsa", + "hashes", + "hmac", + "kdf", + "ed448", + "ed25519", + "poly1305", + "x448", + "x25519", +] + +def openssl_version() -> int: ... +def raise_openssl_error() -> typing.NoReturn: ... +def capture_error_stack() -> typing.List[OpenSSLError]: ... +def is_fips_enabled() -> bool: ... + +class OpenSSLError: + @property + def lib(self) -> int: ... + @property + def reason(self) -> int: ... + @property + def reason_text(self) -> bytes: ... + def _lib_reason_match(self, lib: int, reason: int) -> bool: ... diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/openssl/dh.pyi b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/openssl/dh.pyi new file mode 100644 index 0000000000000000000000000000000000000000..bfd005d99fec9f8f218ba055ef8c8aaae03e72e8 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/openssl/dh.pyi @@ -0,0 +1,22 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from cryptography.hazmat.primitives.asymmetric import dh + +MIN_MODULUS_SIZE: int + +class DHPrivateKey: ... +class DHPublicKey: ... +class DHParameters: ... + +def generate_parameters(generator: int, key_size: int) -> dh.DHParameters: ... +def private_key_from_ptr(ptr: int) -> dh.DHPrivateKey: ... +def public_key_from_ptr(ptr: int) -> dh.DHPublicKey: ... +def from_pem_parameters(data: bytes) -> dh.DHParameters: ... +def from_der_parameters(data: bytes) -> dh.DHParameters: ... +def from_private_numbers(numbers: dh.DHPrivateNumbers) -> dh.DHPrivateKey: ... +def from_public_numbers(numbers: dh.DHPublicNumbers) -> dh.DHPublicKey: ... +def from_parameter_numbers( + numbers: dh.DHParameterNumbers, +) -> dh.DHParameters: ... diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/openssl/dsa.pyi b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/openssl/dsa.pyi new file mode 100644 index 0000000000000000000000000000000000000000..5a56f256d52df9a5a3760df21ea26fce4a5b7070 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/openssl/dsa.pyi @@ -0,0 +1,20 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from cryptography.hazmat.primitives.asymmetric import dsa + +class DSAPrivateKey: ... +class DSAPublicKey: ... +class DSAParameters: ... + +def generate_parameters(key_size: int) -> dsa.DSAParameters: ... +def private_key_from_ptr(ptr: int) -> dsa.DSAPrivateKey: ... +def public_key_from_ptr(ptr: int) -> dsa.DSAPublicKey: ... +def from_private_numbers( + numbers: dsa.DSAPrivateNumbers, +) -> dsa.DSAPrivateKey: ... +def from_public_numbers(numbers: dsa.DSAPublicNumbers) -> dsa.DSAPublicKey: ... +def from_parameter_numbers( + numbers: dsa.DSAParameterNumbers, +) -> dsa.DSAParameters: ... diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/openssl/ed25519.pyi b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/openssl/ed25519.pyi new file mode 100644 index 0000000000000000000000000000000000000000..c7f127f0b157cf2c17804e218795f2363a8b0339 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/openssl/ed25519.pyi @@ -0,0 +1,14 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from cryptography.hazmat.primitives.asymmetric import ed25519 + +class Ed25519PrivateKey: ... +class Ed25519PublicKey: ... + +def generate_key() -> ed25519.Ed25519PrivateKey: ... +def private_key_from_ptr(ptr: int) -> ed25519.Ed25519PrivateKey: ... +def public_key_from_ptr(ptr: int) -> ed25519.Ed25519PublicKey: ... +def from_private_bytes(data: bytes) -> ed25519.Ed25519PrivateKey: ... +def from_public_bytes(data: bytes) -> ed25519.Ed25519PublicKey: ... diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/openssl/ed448.pyi b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/openssl/ed448.pyi new file mode 100644 index 0000000000000000000000000000000000000000..1cf5f1773a0bb86ffaec212e96f500b8ace26b5b --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/openssl/ed448.pyi @@ -0,0 +1,14 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from cryptography.hazmat.primitives.asymmetric import ed448 + +class Ed448PrivateKey: ... +class Ed448PublicKey: ... + +def generate_key() -> ed448.Ed448PrivateKey: ... +def private_key_from_ptr(ptr: int) -> ed448.Ed448PrivateKey: ... +def public_key_from_ptr(ptr: int) -> ed448.Ed448PublicKey: ... +def from_private_bytes(data: bytes) -> ed448.Ed448PrivateKey: ... +def from_public_bytes(data: bytes) -> ed448.Ed448PublicKey: ... diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/openssl/hashes.pyi b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/openssl/hashes.pyi new file mode 100644 index 0000000000000000000000000000000000000000..ca5f42a006158f9cddbaddc2d5b581d556f2914d --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/openssl/hashes.pyi @@ -0,0 +1,17 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +import typing + +from cryptography.hazmat.primitives import hashes + +class Hash(hashes.HashContext): + def __init__( + self, algorithm: hashes.HashAlgorithm, backend: typing.Any = None + ) -> None: ... + @property + def algorithm(self) -> hashes.HashAlgorithm: ... + def update(self, data: bytes) -> None: ... + def finalize(self) -> bytes: ... + def copy(self) -> Hash: ... diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/openssl/hmac.pyi b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/openssl/hmac.pyi new file mode 100644 index 0000000000000000000000000000000000000000..e38d9b54d01bc6e5baea24c2ac6c3d8631941f80 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/openssl/hmac.pyi @@ -0,0 +1,21 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +import typing + +from cryptography.hazmat.primitives import hashes + +class HMAC(hashes.HashContext): + def __init__( + self, + key: bytes, + algorithm: hashes.HashAlgorithm, + backend: typing.Any = None, + ) -> None: ... + @property + def algorithm(self) -> hashes.HashAlgorithm: ... + def update(self, data: bytes) -> None: ... + def finalize(self) -> bytes: ... + def verify(self, signature: bytes) -> None: ... + def copy(self) -> HMAC: ... diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/openssl/kdf.pyi b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/openssl/kdf.pyi new file mode 100644 index 0000000000000000000000000000000000000000..034a8fed2e7898baa5acb56ce01d96ba9fcbb89e --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/openssl/kdf.pyi @@ -0,0 +1,22 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from cryptography.hazmat.primitives.hashes import HashAlgorithm + +def derive_pbkdf2_hmac( + key_material: bytes, + algorithm: HashAlgorithm, + salt: bytes, + iterations: int, + length: int, +) -> bytes: ... +def derive_scrypt( + key_material: bytes, + salt: bytes, + n: int, + r: int, + p: int, + max_mem: int, + length: int, +) -> bytes: ... diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/openssl/poly1305.pyi b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/openssl/poly1305.pyi new file mode 100644 index 0000000000000000000000000000000000000000..2e9b0a9e1254361860942722a03281e9bb8a3bb3 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/openssl/poly1305.pyi @@ -0,0 +1,13 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +class Poly1305: + def __init__(self, key: bytes) -> None: ... + @staticmethod + def generate_tag(key: bytes, data: bytes) -> bytes: ... + @staticmethod + def verify_tag(key: bytes, data: bytes, tag: bytes) -> None: ... + def update(self, data: bytes) -> None: ... + def finalize(self) -> bytes: ... + def verify(self, tag: bytes) -> None: ... diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/openssl/x25519.pyi b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/openssl/x25519.pyi new file mode 100644 index 0000000000000000000000000000000000000000..90f7cbdda950b10e2fc160353e15fdb30f7250cf --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/openssl/x25519.pyi @@ -0,0 +1,14 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from cryptography.hazmat.primitives.asymmetric import x25519 + +class X25519PrivateKey: ... +class X25519PublicKey: ... + +def generate_key() -> x25519.X25519PrivateKey: ... +def private_key_from_ptr(ptr: int) -> x25519.X25519PrivateKey: ... +def public_key_from_ptr(ptr: int) -> x25519.X25519PublicKey: ... +def from_private_bytes(data: bytes) -> x25519.X25519PrivateKey: ... +def from_public_bytes(data: bytes) -> x25519.X25519PublicKey: ... diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/openssl/x448.pyi b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/openssl/x448.pyi new file mode 100644 index 0000000000000000000000000000000000000000..d326c8d2d7c585d8522eca0fac931673c1047a45 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/openssl/x448.pyi @@ -0,0 +1,14 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from cryptography.hazmat.primitives.asymmetric import x448 + +class X448PrivateKey: ... +class X448PublicKey: ... + +def generate_key() -> x448.X448PrivateKey: ... +def private_key_from_ptr(ptr: int) -> x448.X448PrivateKey: ... +def public_key_from_ptr(ptr: int) -> x448.X448PublicKey: ... +def from_private_bytes(data: bytes) -> x448.X448PrivateKey: ... +def from_public_bytes(data: bytes) -> x448.X448PublicKey: ... diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/pkcs7.pyi b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/pkcs7.pyi new file mode 100644 index 0000000000000000000000000000000000000000..66bd850981a6fa06eb7c7ecdec0e443c22b82c08 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/pkcs7.pyi @@ -0,0 +1,15 @@ +import typing + +from cryptography import x509 +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.serialization import pkcs7 + +def serialize_certificates( + certs: typing.List[x509.Certificate], + encoding: serialization.Encoding, +) -> bytes: ... +def sign_and_serialize( + builder: pkcs7.PKCS7SignatureBuilder, + encoding: serialization.Encoding, + options: typing.Iterable[pkcs7.PKCS7Options], +) -> bytes: ... diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/x509.pyi b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/x509.pyi new file mode 100644 index 0000000000000000000000000000000000000000..24b2f5e3a78c97622e8a4353de09934dde0d4026 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/_rust/x509.pyi @@ -0,0 +1,44 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +import typing + +from cryptography import x509 +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives.asymmetric.padding import PSS, PKCS1v15 +from cryptography.hazmat.primitives.asymmetric.types import PrivateKeyTypes + +def load_pem_x509_certificate(data: bytes) -> x509.Certificate: ... +def load_pem_x509_certificates( + data: bytes, +) -> typing.List[x509.Certificate]: ... +def load_der_x509_certificate(data: bytes) -> x509.Certificate: ... +def load_pem_x509_crl(data: bytes) -> x509.CertificateRevocationList: ... +def load_der_x509_crl(data: bytes) -> x509.CertificateRevocationList: ... +def load_pem_x509_csr(data: bytes) -> x509.CertificateSigningRequest: ... +def load_der_x509_csr(data: bytes) -> x509.CertificateSigningRequest: ... +def encode_name_bytes(name: x509.Name) -> bytes: ... +def encode_extension_value(extension: x509.ExtensionType) -> bytes: ... +def create_x509_certificate( + builder: x509.CertificateBuilder, + private_key: PrivateKeyTypes, + hash_algorithm: typing.Optional[hashes.HashAlgorithm], + padding: typing.Optional[typing.Union[PKCS1v15, PSS]], +) -> x509.Certificate: ... +def create_x509_csr( + builder: x509.CertificateSigningRequestBuilder, + private_key: PrivateKeyTypes, + hash_algorithm: typing.Optional[hashes.HashAlgorithm], +) -> x509.CertificateSigningRequest: ... +def create_x509_crl( + builder: x509.CertificateRevocationListBuilder, + private_key: PrivateKeyTypes, + hash_algorithm: typing.Optional[hashes.HashAlgorithm], +) -> x509.CertificateRevocationList: ... + +class Sct: ... +class Certificate: ... +class RevokedCertificate: ... +class CertificateRevocationList: ... +class CertificateSigningRequest: ... diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/openssl/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/openssl/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b509336233c2fafe4185a49da5909c8bbb38dfd7 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/openssl/__init__.py @@ -0,0 +1,3 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/openssl/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/openssl/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..69bb7cf711b74e61ec22d5f8183d1722763b855e Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/openssl/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/openssl/__pycache__/_conditional.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/openssl/__pycache__/_conditional.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..09249e0bb89189ca7acf2b3ce211df5938c5a0a2 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/openssl/__pycache__/_conditional.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/openssl/__pycache__/binding.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/openssl/__pycache__/binding.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7be4415cbff3418b4ccd334a735cc17c0a2e0a67 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/openssl/__pycache__/binding.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/openssl/_conditional.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/openssl/_conditional.py new file mode 100644 index 0000000000000000000000000000000000000000..5e8ecd04182ca6768b5a54bfac152e0b7a85baa7 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/openssl/_conditional.py @@ -0,0 +1,329 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import typing + + +def cryptography_has_set_cert_cb() -> typing.List[str]: + return [ + "SSL_CTX_set_cert_cb", + "SSL_set_cert_cb", + ] + + +def cryptography_has_ssl_st() -> typing.List[str]: + return [ + "SSL_ST_BEFORE", + "SSL_ST_OK", + "SSL_ST_INIT", + "SSL_ST_RENEGOTIATE", + ] + + +def cryptography_has_tls_st() -> typing.List[str]: + return [ + "TLS_ST_BEFORE", + "TLS_ST_OK", + ] + + +def cryptography_has_evp_pkey_dhx() -> typing.List[str]: + return [ + "EVP_PKEY_DHX", + ] + + +def cryptography_has_mem_functions() -> typing.List[str]: + return [ + "Cryptography_CRYPTO_set_mem_functions", + ] + + +def cryptography_has_x509_store_ctx_get_issuer() -> typing.List[str]: + return [ + "X509_STORE_set_get_issuer", + ] + + +def cryptography_has_ed448() -> typing.List[str]: + return [ + "EVP_PKEY_ED448", + "NID_ED448", + ] + + +def cryptography_has_ed25519() -> typing.List[str]: + return [ + "NID_ED25519", + "EVP_PKEY_ED25519", + ] + + +def cryptography_has_poly1305() -> typing.List[str]: + return [ + "NID_poly1305", + "EVP_PKEY_POLY1305", + ] + + +def cryptography_has_evp_digestfinal_xof() -> typing.List[str]: + return [ + "EVP_DigestFinalXOF", + ] + + +def cryptography_has_fips() -> typing.List[str]: + return [ + "FIPS_mode_set", + "FIPS_mode", + ] + + +def cryptography_has_ssl_sigalgs() -> typing.List[str]: + return [ + "SSL_CTX_set1_sigalgs_list", + ] + + +def cryptography_has_psk() -> typing.List[str]: + return [ + "SSL_CTX_use_psk_identity_hint", + "SSL_CTX_set_psk_server_callback", + "SSL_CTX_set_psk_client_callback", + ] + + +def cryptography_has_psk_tlsv13() -> typing.List[str]: + return [ + "SSL_CTX_set_psk_find_session_callback", + "SSL_CTX_set_psk_use_session_callback", + "Cryptography_SSL_SESSION_new", + "SSL_CIPHER_find", + "SSL_SESSION_set1_master_key", + "SSL_SESSION_set_cipher", + "SSL_SESSION_set_protocol_version", + ] + + +def cryptography_has_custom_ext() -> typing.List[str]: + return [ + "SSL_CTX_add_client_custom_ext", + "SSL_CTX_add_server_custom_ext", + "SSL_extension_supported", + ] + + +def cryptography_has_tlsv13_functions() -> typing.List[str]: + return [ + "SSL_VERIFY_POST_HANDSHAKE", + "SSL_CTX_set_ciphersuites", + "SSL_verify_client_post_handshake", + "SSL_CTX_set_post_handshake_auth", + "SSL_set_post_handshake_auth", + "SSL_SESSION_get_max_early_data", + "SSL_write_early_data", + "SSL_read_early_data", + "SSL_CTX_set_max_early_data", + ] + + +def cryptography_has_raw_key() -> typing.List[str]: + return [ + "EVP_PKEY_new_raw_private_key", + "EVP_PKEY_new_raw_public_key", + "EVP_PKEY_get_raw_private_key", + "EVP_PKEY_get_raw_public_key", + ] + + +def cryptography_has_engine() -> typing.List[str]: + return [ + "ENGINE_by_id", + "ENGINE_init", + "ENGINE_finish", + "ENGINE_get_default_RAND", + "ENGINE_set_default_RAND", + "ENGINE_unregister_RAND", + "ENGINE_ctrl_cmd", + "ENGINE_free", + "ENGINE_get_name", + "ENGINE_ctrl_cmd_string", + "ENGINE_load_builtin_engines", + "ENGINE_load_private_key", + "ENGINE_load_public_key", + "SSL_CTX_set_client_cert_engine", + ] + + +def cryptography_has_verified_chain() -> typing.List[str]: + return [ + "SSL_get0_verified_chain", + ] + + +def cryptography_has_srtp() -> typing.List[str]: + return [ + "SSL_CTX_set_tlsext_use_srtp", + "SSL_set_tlsext_use_srtp", + "SSL_get_selected_srtp_profile", + ] + + +def cryptography_has_providers() -> typing.List[str]: + return [ + "OSSL_PROVIDER_load", + "OSSL_PROVIDER_unload", + "ERR_LIB_PROV", + "PROV_R_WRONG_FINAL_BLOCK_LENGTH", + "PROV_R_BAD_DECRYPT", + ] + + +def cryptography_has_op_no_renegotiation() -> typing.List[str]: + return [ + "SSL_OP_NO_RENEGOTIATION", + ] + + +def cryptography_has_dtls_get_data_mtu() -> typing.List[str]: + return [ + "DTLS_get_data_mtu", + ] + + +def cryptography_has_300_fips() -> typing.List[str]: + return [ + "EVP_default_properties_is_fips_enabled", + "EVP_default_properties_enable_fips", + ] + + +def cryptography_has_ssl_cookie() -> typing.List[str]: + return [ + "SSL_OP_COOKIE_EXCHANGE", + "DTLSv1_listen", + "SSL_CTX_set_cookie_generate_cb", + "SSL_CTX_set_cookie_verify_cb", + ] + + +def cryptography_has_pkcs7_funcs() -> typing.List[str]: + return [ + "SMIME_write_PKCS7", + "PEM_write_bio_PKCS7_stream", + "PKCS7_sign_add_signer", + "PKCS7_final", + "PKCS7_verify", + "SMIME_read_PKCS7", + "PKCS7_get0_signers", + ] + + +def cryptography_has_bn_flags() -> typing.List[str]: + return [ + "BN_FLG_CONSTTIME", + "BN_set_flags", + "BN_prime_checks_for_size", + ] + + +def cryptography_has_evp_pkey_dh() -> typing.List[str]: + return [ + "EVP_PKEY_set1_DH", + ] + + +def cryptography_has_300_evp_cipher() -> typing.List[str]: + return ["EVP_CIPHER_fetch", "EVP_CIPHER_free"] + + +def cryptography_has_unexpected_eof_while_reading() -> typing.List[str]: + return ["SSL_R_UNEXPECTED_EOF_WHILE_READING"] + + +def cryptography_has_pkcs12_set_mac() -> typing.List[str]: + return ["PKCS12_set_mac"] + + +def cryptography_has_ssl_op_ignore_unexpected_eof() -> typing.List[str]: + return [ + "SSL_OP_IGNORE_UNEXPECTED_EOF", + ] + + +def cryptography_has_get_extms_support() -> typing.List[str]: + return ["SSL_get_extms_support"] + + +def cryptography_has_evp_pkey_set_peer_ex() -> typing.List[str]: + return ["EVP_PKEY_derive_set_peer_ex"] + + +def cryptography_has_evp_aead() -> typing.List[str]: + return [ + "EVP_aead_chacha20_poly1305", + "EVP_AEAD_CTX_free", + "EVP_AEAD_CTX_seal", + "EVP_AEAD_CTX_open", + "EVP_AEAD_max_overhead", + "Cryptography_EVP_AEAD_CTX_new", + ] + + +# This is a mapping of +# {condition: function-returning-names-dependent-on-that-condition} so we can +# loop over them and delete unsupported names at runtime. It will be removed +# when cffi supports #if in cdef. We use functions instead of just a dict of +# lists so we can use coverage to measure which are used. +CONDITIONAL_NAMES = { + "Cryptography_HAS_SET_CERT_CB": cryptography_has_set_cert_cb, + "Cryptography_HAS_SSL_ST": cryptography_has_ssl_st, + "Cryptography_HAS_TLS_ST": cryptography_has_tls_st, + "Cryptography_HAS_EVP_PKEY_DHX": cryptography_has_evp_pkey_dhx, + "Cryptography_HAS_MEM_FUNCTIONS": cryptography_has_mem_functions, + "Cryptography_HAS_X509_STORE_CTX_GET_ISSUER": ( + cryptography_has_x509_store_ctx_get_issuer + ), + "Cryptography_HAS_ED448": cryptography_has_ed448, + "Cryptography_HAS_ED25519": cryptography_has_ed25519, + "Cryptography_HAS_POLY1305": cryptography_has_poly1305, + "Cryptography_HAS_FIPS": cryptography_has_fips, + "Cryptography_HAS_SIGALGS": cryptography_has_ssl_sigalgs, + "Cryptography_HAS_PSK": cryptography_has_psk, + "Cryptography_HAS_PSK_TLSv1_3": cryptography_has_psk_tlsv13, + "Cryptography_HAS_CUSTOM_EXT": cryptography_has_custom_ext, + "Cryptography_HAS_TLSv1_3_FUNCTIONS": cryptography_has_tlsv13_functions, + "Cryptography_HAS_RAW_KEY": cryptography_has_raw_key, + "Cryptography_HAS_EVP_DIGESTFINAL_XOF": ( + cryptography_has_evp_digestfinal_xof + ), + "Cryptography_HAS_ENGINE": cryptography_has_engine, + "Cryptography_HAS_VERIFIED_CHAIN": cryptography_has_verified_chain, + "Cryptography_HAS_SRTP": cryptography_has_srtp, + "Cryptography_HAS_PROVIDERS": cryptography_has_providers, + "Cryptography_HAS_OP_NO_RENEGOTIATION": ( + cryptography_has_op_no_renegotiation + ), + "Cryptography_HAS_DTLS_GET_DATA_MTU": cryptography_has_dtls_get_data_mtu, + "Cryptography_HAS_300_FIPS": cryptography_has_300_fips, + "Cryptography_HAS_SSL_COOKIE": cryptography_has_ssl_cookie, + "Cryptography_HAS_PKCS7_FUNCS": cryptography_has_pkcs7_funcs, + "Cryptography_HAS_BN_FLAGS": cryptography_has_bn_flags, + "Cryptography_HAS_EVP_PKEY_DH": cryptography_has_evp_pkey_dh, + "Cryptography_HAS_300_EVP_CIPHER": cryptography_has_300_evp_cipher, + "Cryptography_HAS_UNEXPECTED_EOF_WHILE_READING": ( + cryptography_has_unexpected_eof_while_reading + ), + "Cryptography_HAS_PKCS12_SET_MAC": cryptography_has_pkcs12_set_mac, + "Cryptography_HAS_SSL_OP_IGNORE_UNEXPECTED_EOF": ( + cryptography_has_ssl_op_ignore_unexpected_eof + ), + "Cryptography_HAS_GET_EXTMS_SUPPORT": cryptography_has_get_extms_support, + "Cryptography_HAS_EVP_PKEY_SET_PEER_EX": ( + cryptography_has_evp_pkey_set_peer_ex + ), + "Cryptography_HAS_EVP_AEAD": (cryptography_has_evp_aead), +} diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/openssl/binding.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/openssl/binding.py new file mode 100644 index 0000000000000000000000000000000000000000..b50d631518c1ac7fe8d5e18d1a9ff86fcf661245 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/bindings/openssl/binding.py @@ -0,0 +1,179 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import os +import sys +import threading +import types +import typing +import warnings + +import cryptography +from cryptography.exceptions import InternalError +from cryptography.hazmat.bindings._rust import _openssl, openssl +from cryptography.hazmat.bindings.openssl._conditional import CONDITIONAL_NAMES + + +def _openssl_assert( + lib, + ok: bool, + errors: typing.Optional[typing.List[openssl.OpenSSLError]] = None, +) -> None: + if not ok: + if errors is None: + errors = openssl.capture_error_stack() + + raise InternalError( + "Unknown OpenSSL error. This error is commonly encountered when " + "another library is not cleaning up the OpenSSL error stack. If " + "you are using cryptography with another library that uses " + "OpenSSL try disabling it before reporting a bug. Otherwise " + "please file an issue at https://github.com/pyca/cryptography/" + "issues with information on how to reproduce " + "this. ({!r})".format(errors), + errors, + ) + + +def _legacy_provider_error(loaded: bool) -> None: + if not loaded: + raise RuntimeError( + "OpenSSL 3.0's legacy provider failed to load. This is a fatal " + "error by default, but cryptography supports running without " + "legacy algorithms by setting the environment variable " + "CRYPTOGRAPHY_OPENSSL_NO_LEGACY. If you did not expect this error," + " you have likely made a mistake with your OpenSSL configuration." + ) + + +def build_conditional_library( + lib: typing.Any, + conditional_names: typing.Dict[str, typing.Callable[[], typing.List[str]]], +) -> typing.Any: + conditional_lib = types.ModuleType("lib") + conditional_lib._original_lib = lib # type: ignore[attr-defined] + excluded_names = set() + for condition, names_cb in conditional_names.items(): + if not getattr(lib, condition): + excluded_names.update(names_cb()) + + for attr in dir(lib): + if attr not in excluded_names: + setattr(conditional_lib, attr, getattr(lib, attr)) + + return conditional_lib + + +class Binding: + """ + OpenSSL API wrapper. + """ + + lib: typing.ClassVar = None + ffi = _openssl.ffi + _lib_loaded = False + _init_lock = threading.Lock() + _legacy_provider: typing.Any = ffi.NULL + _legacy_provider_loaded = False + _default_provider: typing.Any = ffi.NULL + + def __init__(self) -> None: + self._ensure_ffi_initialized() + + def _enable_fips(self) -> None: + # This function enables FIPS mode for OpenSSL 3.0.0 on installs that + # have the FIPS provider installed properly. + _openssl_assert(self.lib, self.lib.CRYPTOGRAPHY_OPENSSL_300_OR_GREATER) + self._base_provider = self.lib.OSSL_PROVIDER_load( + self.ffi.NULL, b"base" + ) + _openssl_assert(self.lib, self._base_provider != self.ffi.NULL) + self.lib._fips_provider = self.lib.OSSL_PROVIDER_load( + self.ffi.NULL, b"fips" + ) + _openssl_assert(self.lib, self.lib._fips_provider != self.ffi.NULL) + + res = self.lib.EVP_default_properties_enable_fips(self.ffi.NULL, 1) + _openssl_assert(self.lib, res == 1) + + @classmethod + def _ensure_ffi_initialized(cls) -> None: + with cls._init_lock: + if not cls._lib_loaded: + cls.lib = build_conditional_library( + _openssl.lib, CONDITIONAL_NAMES + ) + cls._lib_loaded = True + # As of OpenSSL 3.0.0 we must register a legacy cipher provider + # to get RC2 (needed for junk asymmetric private key + # serialization), RC4, Blowfish, IDEA, SEED, etc. These things + # are ugly legacy, but we aren't going to get rid of them + # any time soon. + if cls.lib.CRYPTOGRAPHY_OPENSSL_300_OR_GREATER: + if not os.environ.get("CRYPTOGRAPHY_OPENSSL_NO_LEGACY"): + cls._legacy_provider = cls.lib.OSSL_PROVIDER_load( + cls.ffi.NULL, b"legacy" + ) + cls._legacy_provider_loaded = ( + cls._legacy_provider != cls.ffi.NULL + ) + _legacy_provider_error(cls._legacy_provider_loaded) + + cls._default_provider = cls.lib.OSSL_PROVIDER_load( + cls.ffi.NULL, b"default" + ) + _openssl_assert( + cls.lib, cls._default_provider != cls.ffi.NULL + ) + + @classmethod + def init_static_locks(cls) -> None: + cls._ensure_ffi_initialized() + + +def _verify_package_version(version: str) -> None: + # Occasionally we run into situations where the version of the Python + # package does not match the version of the shared object that is loaded. + # This may occur in environments where multiple versions of cryptography + # are installed and available in the python path. To avoid errors cropping + # up later this code checks that the currently imported package and the + # shared object that were loaded have the same version and raise an + # ImportError if they do not + so_package_version = _openssl.ffi.string( + _openssl.lib.CRYPTOGRAPHY_PACKAGE_VERSION + ) + if version.encode("ascii") != so_package_version: + raise ImportError( + "The version of cryptography does not match the loaded " + "shared object. This can happen if you have multiple copies of " + "cryptography installed in your Python path. Please try creating " + "a new virtual environment to resolve this issue. " + "Loaded python version: {}, shared object version: {}".format( + version, so_package_version + ) + ) + + _openssl_assert( + _openssl.lib, + _openssl.lib.OpenSSL_version_num() == openssl.openssl_version(), + ) + + +_verify_package_version(cryptography.__version__) + +Binding.init_static_locks() + +if ( + sys.platform == "win32" + and os.environ.get("PROCESSOR_ARCHITEW6432") is not None +): + warnings.warn( + "You are using cryptography on a 32-bit Python on a 64-bit Windows " + "Operating System. Cryptography will be significantly faster if you " + "switch to using a 64-bit Python.", + UserWarning, + stacklevel=2, + ) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b509336233c2fafe4185a49da5909c8bbb38dfd7 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/__init__.py @@ -0,0 +1,3 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8035ce3ab25d95c5eeffe0f6118647f4e8238e1c Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/__pycache__/_asymmetric.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/__pycache__/_asymmetric.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..615198035924283a8fc26dfd1280057d6212b770 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/__pycache__/_asymmetric.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/__pycache__/_cipheralgorithm.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/__pycache__/_cipheralgorithm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c88799e61d30a60152ca97f9f6cac6105c1fc356 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/__pycache__/_cipheralgorithm.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/__pycache__/_serialization.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/__pycache__/_serialization.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ceb63ea5b75b04a5c91b92be4f8ad48ce4195565 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/__pycache__/_serialization.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/__pycache__/cmac.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/__pycache__/cmac.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b65e5c5a85bcd9d0816f3576bf5c76bebb125f2 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/__pycache__/cmac.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/__pycache__/constant_time.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/__pycache__/constant_time.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d9e65781bdb7715853647146a1e4f5d2b3bc0804 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/__pycache__/constant_time.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/__pycache__/hashes.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/__pycache__/hashes.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e5bb3ec5d3cd1b78f3e1f5c30e3ca94d0a26ee4 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/__pycache__/hashes.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/__pycache__/hmac.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/__pycache__/hmac.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fd04c6ffa73a9b7eaf312cf8bcd84c0d59c4f9c4 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/__pycache__/hmac.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/__pycache__/keywrap.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/__pycache__/keywrap.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..548879fe8a7b391e3bde7b3f62b8a37a9269893a Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/__pycache__/keywrap.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/__pycache__/padding.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/__pycache__/padding.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2683921b243773c336a1040f40f6c94d9aaa71ed Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/__pycache__/padding.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/__pycache__/poly1305.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/__pycache__/poly1305.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..381ddd1c317f2b3850a95bc571998deaa21efdb1 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/__pycache__/poly1305.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/_asymmetric.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/_asymmetric.py new file mode 100644 index 0000000000000000000000000000000000000000..ea55ffdf1a721f8fd2de8ae67de913bc47cbf55d --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/_asymmetric.py @@ -0,0 +1,19 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc + +# This exists to break an import cycle. It is normally accessible from the +# asymmetric padding module. + + +class AsymmetricPadding(metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def name(self) -> str: + """ + A string naming this padding (e.g. "PSS", "PKCS1"). + """ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/_cipheralgorithm.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/_cipheralgorithm.py new file mode 100644 index 0000000000000000000000000000000000000000..3b880b64884954a46dcf2c513264e87cb6d6ed07 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/_cipheralgorithm.py @@ -0,0 +1,45 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc +import typing + +# This exists to break an import cycle. It is normally accessible from the +# ciphers module. + + +class CipherAlgorithm(metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def name(self) -> str: + """ + A string naming this mode (e.g. "AES", "Camellia"). + """ + + @property + @abc.abstractmethod + def key_sizes(self) -> typing.FrozenSet[int]: + """ + Valid key sizes for this algorithm in bits + """ + + @property + @abc.abstractmethod + def key_size(self) -> int: + """ + The size of the key being used as an integer in bits (e.g. 128, 256). + """ + + +class BlockCipherAlgorithm(CipherAlgorithm): + key: bytes + + @property + @abc.abstractmethod + def block_size(self) -> int: + """ + The size of a block as an integer in bits (e.g. 64, 128). + """ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/_serialization.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/_serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..34f3fbc860266d28e80275fe9e3900c8eba7eb59 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/_serialization.py @@ -0,0 +1,170 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc +import typing + +from cryptography import utils +from cryptography.hazmat.primitives.hashes import HashAlgorithm + +# This exists to break an import cycle. These classes are normally accessible +# from the serialization module. + + +class PBES(utils.Enum): + PBESv1SHA1And3KeyTripleDESCBC = "PBESv1 using SHA1 and 3-Key TripleDES" + PBESv2SHA256AndAES256CBC = "PBESv2 using SHA256 PBKDF2 and AES256 CBC" + + +class Encoding(utils.Enum): + PEM = "PEM" + DER = "DER" + OpenSSH = "OpenSSH" + Raw = "Raw" + X962 = "ANSI X9.62" + SMIME = "S/MIME" + + +class PrivateFormat(utils.Enum): + PKCS8 = "PKCS8" + TraditionalOpenSSL = "TraditionalOpenSSL" + Raw = "Raw" + OpenSSH = "OpenSSH" + PKCS12 = "PKCS12" + + def encryption_builder(self) -> KeySerializationEncryptionBuilder: + if self not in (PrivateFormat.OpenSSH, PrivateFormat.PKCS12): + raise ValueError( + "encryption_builder only supported with PrivateFormat.OpenSSH" + " and PrivateFormat.PKCS12" + ) + return KeySerializationEncryptionBuilder(self) + + +class PublicFormat(utils.Enum): + SubjectPublicKeyInfo = "X.509 subjectPublicKeyInfo with PKCS#1" + PKCS1 = "Raw PKCS#1" + OpenSSH = "OpenSSH" + Raw = "Raw" + CompressedPoint = "X9.62 Compressed Point" + UncompressedPoint = "X9.62 Uncompressed Point" + + +class ParameterFormat(utils.Enum): + PKCS3 = "PKCS3" + + +class KeySerializationEncryption(metaclass=abc.ABCMeta): + pass + + +class BestAvailableEncryption(KeySerializationEncryption): + def __init__(self, password: bytes): + if not isinstance(password, bytes) or len(password) == 0: + raise ValueError("Password must be 1 or more bytes.") + + self.password = password + + +class NoEncryption(KeySerializationEncryption): + pass + + +class KeySerializationEncryptionBuilder: + def __init__( + self, + format: PrivateFormat, + *, + _kdf_rounds: typing.Optional[int] = None, + _hmac_hash: typing.Optional[HashAlgorithm] = None, + _key_cert_algorithm: typing.Optional[PBES] = None, + ) -> None: + self._format = format + + self._kdf_rounds = _kdf_rounds + self._hmac_hash = _hmac_hash + self._key_cert_algorithm = _key_cert_algorithm + + def kdf_rounds(self, rounds: int) -> KeySerializationEncryptionBuilder: + if self._kdf_rounds is not None: + raise ValueError("kdf_rounds already set") + + if not isinstance(rounds, int): + raise TypeError("kdf_rounds must be an integer") + + if rounds < 1: + raise ValueError("kdf_rounds must be a positive integer") + + return KeySerializationEncryptionBuilder( + self._format, + _kdf_rounds=rounds, + _hmac_hash=self._hmac_hash, + _key_cert_algorithm=self._key_cert_algorithm, + ) + + def hmac_hash( + self, algorithm: HashAlgorithm + ) -> KeySerializationEncryptionBuilder: + if self._format is not PrivateFormat.PKCS12: + raise TypeError( + "hmac_hash only supported with PrivateFormat.PKCS12" + ) + + if self._hmac_hash is not None: + raise ValueError("hmac_hash already set") + return KeySerializationEncryptionBuilder( + self._format, + _kdf_rounds=self._kdf_rounds, + _hmac_hash=algorithm, + _key_cert_algorithm=self._key_cert_algorithm, + ) + + def key_cert_algorithm( + self, algorithm: PBES + ) -> KeySerializationEncryptionBuilder: + if self._format is not PrivateFormat.PKCS12: + raise TypeError( + "key_cert_algorithm only supported with " + "PrivateFormat.PKCS12" + ) + if self._key_cert_algorithm is not None: + raise ValueError("key_cert_algorithm already set") + return KeySerializationEncryptionBuilder( + self._format, + _kdf_rounds=self._kdf_rounds, + _hmac_hash=self._hmac_hash, + _key_cert_algorithm=algorithm, + ) + + def build(self, password: bytes) -> KeySerializationEncryption: + if not isinstance(password, bytes) or len(password) == 0: + raise ValueError("Password must be 1 or more bytes.") + + return _KeySerializationEncryption( + self._format, + password, + kdf_rounds=self._kdf_rounds, + hmac_hash=self._hmac_hash, + key_cert_algorithm=self._key_cert_algorithm, + ) + + +class _KeySerializationEncryption(KeySerializationEncryption): + def __init__( + self, + format: PrivateFormat, + password: bytes, + *, + kdf_rounds: typing.Optional[int], + hmac_hash: typing.Optional[HashAlgorithm], + key_cert_algorithm: typing.Optional[PBES], + ): + self._format = format + self.password = password + + self._kdf_rounds = kdf_rounds + self._hmac_hash = hmac_hash + self._key_cert_algorithm = key_cert_algorithm diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b509336233c2fafe4185a49da5909c8bbb38dfd7 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/__init__.py @@ -0,0 +1,3 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e345c79a09363a8900175b6613a2232483355fe3 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/dh.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/dh.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..618fb91fe5f3117521733f487a598e5175a67094 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/dh.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/dsa.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/dsa.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7aae555a757982409189f9ff6ec30567fdfc12fb Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/dsa.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/ec.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/ec.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6454061480ee747dd0c6dac96d13a7e151a8e49d Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/ec.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/ed25519.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/ed25519.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2056ceecb7f833af78c000318c9c329f886b52cf Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/ed25519.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/ed448.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/ed448.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a4d467bc602408bde5ec5e43206e126c146e244d Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/ed448.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/padding.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/padding.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b3f2a4da8f17d49802bd0d2f9a300d1477c929ae Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/padding.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/rsa.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/rsa.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..81c775f9faf4754c80becfc4a1b8b0041d186bea Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/rsa.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/types.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/types.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d7ba6867f1299a98fdf1152c76fa9d6570039079 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/types.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/utils.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f012c4a76be69ec11f257aea2f4ed8c96fbd859a Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/utils.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/x25519.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/x25519.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6624e56a794756d5baf395fab24aa2e15a8580dc Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/x25519.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/x448.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/x448.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..58bd9e1084a1bfc911b01f6d4fe56764265d76ac Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/x448.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/dh.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/dh.py new file mode 100644 index 0000000000000000000000000000000000000000..751bcc402e9417b6e7b9a72e92052c83fcc65751 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/dh.py @@ -0,0 +1,261 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc +import typing + +from cryptography.hazmat.bindings._rust import openssl as rust_openssl +from cryptography.hazmat.primitives import _serialization + + +def generate_parameters( + generator: int, key_size: int, backend: typing.Any = None +) -> DHParameters: + from cryptography.hazmat.backends.openssl.backend import backend as ossl + + return ossl.generate_dh_parameters(generator, key_size) + + +class DHParameterNumbers: + def __init__(self, p: int, g: int, q: typing.Optional[int] = None) -> None: + if not isinstance(p, int) or not isinstance(g, int): + raise TypeError("p and g must be integers") + if q is not None and not isinstance(q, int): + raise TypeError("q must be integer or None") + + if g < 2: + raise ValueError("DH generator must be 2 or greater") + + if p.bit_length() < rust_openssl.dh.MIN_MODULUS_SIZE: + raise ValueError( + f"p (modulus) must be at least " + f"{rust_openssl.dh.MIN_MODULUS_SIZE}-bit" + ) + + self._p = p + self._g = g + self._q = q + + def __eq__(self, other: object) -> bool: + if not isinstance(other, DHParameterNumbers): + return NotImplemented + + return ( + self._p == other._p and self._g == other._g and self._q == other._q + ) + + def parameters(self, backend: typing.Any = None) -> DHParameters: + from cryptography.hazmat.backends.openssl.backend import ( + backend as ossl, + ) + + return ossl.load_dh_parameter_numbers(self) + + @property + def p(self) -> int: + return self._p + + @property + def g(self) -> int: + return self._g + + @property + def q(self) -> typing.Optional[int]: + return self._q + + +class DHPublicNumbers: + def __init__(self, y: int, parameter_numbers: DHParameterNumbers) -> None: + if not isinstance(y, int): + raise TypeError("y must be an integer.") + + if not isinstance(parameter_numbers, DHParameterNumbers): + raise TypeError( + "parameters must be an instance of DHParameterNumbers." + ) + + self._y = y + self._parameter_numbers = parameter_numbers + + def __eq__(self, other: object) -> bool: + if not isinstance(other, DHPublicNumbers): + return NotImplemented + + return ( + self._y == other._y + and self._parameter_numbers == other._parameter_numbers + ) + + def public_key(self, backend: typing.Any = None) -> DHPublicKey: + from cryptography.hazmat.backends.openssl.backend import ( + backend as ossl, + ) + + return ossl.load_dh_public_numbers(self) + + @property + def y(self) -> int: + return self._y + + @property + def parameter_numbers(self) -> DHParameterNumbers: + return self._parameter_numbers + + +class DHPrivateNumbers: + def __init__(self, x: int, public_numbers: DHPublicNumbers) -> None: + if not isinstance(x, int): + raise TypeError("x must be an integer.") + + if not isinstance(public_numbers, DHPublicNumbers): + raise TypeError( + "public_numbers must be an instance of " "DHPublicNumbers." + ) + + self._x = x + self._public_numbers = public_numbers + + def __eq__(self, other: object) -> bool: + if not isinstance(other, DHPrivateNumbers): + return NotImplemented + + return ( + self._x == other._x + and self._public_numbers == other._public_numbers + ) + + def private_key(self, backend: typing.Any = None) -> DHPrivateKey: + from cryptography.hazmat.backends.openssl.backend import ( + backend as ossl, + ) + + return ossl.load_dh_private_numbers(self) + + @property + def public_numbers(self) -> DHPublicNumbers: + return self._public_numbers + + @property + def x(self) -> int: + return self._x + + +class DHParameters(metaclass=abc.ABCMeta): + @abc.abstractmethod + def generate_private_key(self) -> DHPrivateKey: + """ + Generates and returns a DHPrivateKey. + """ + + @abc.abstractmethod + def parameter_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.ParameterFormat, + ) -> bytes: + """ + Returns the parameters serialized as bytes. + """ + + @abc.abstractmethod + def parameter_numbers(self) -> DHParameterNumbers: + """ + Returns a DHParameterNumbers. + """ + + +DHParametersWithSerialization = DHParameters +DHParameters.register(rust_openssl.dh.DHParameters) + + +class DHPublicKey(metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def key_size(self) -> int: + """ + The bit length of the prime modulus. + """ + + @abc.abstractmethod + def parameters(self) -> DHParameters: + """ + The DHParameters object associated with this public key. + """ + + @abc.abstractmethod + def public_numbers(self) -> DHPublicNumbers: + """ + Returns a DHPublicNumbers. + """ + + @abc.abstractmethod + def public_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PublicFormat, + ) -> bytes: + """ + Returns the key serialized as bytes. + """ + + @abc.abstractmethod + def __eq__(self, other: object) -> bool: + """ + Checks equality. + """ + + +DHPublicKeyWithSerialization = DHPublicKey +DHPublicKey.register(rust_openssl.dh.DHPublicKey) + + +class DHPrivateKey(metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def key_size(self) -> int: + """ + The bit length of the prime modulus. + """ + + @abc.abstractmethod + def public_key(self) -> DHPublicKey: + """ + The DHPublicKey associated with this private key. + """ + + @abc.abstractmethod + def parameters(self) -> DHParameters: + """ + The DHParameters object associated with this private key. + """ + + @abc.abstractmethod + def exchange(self, peer_public_key: DHPublicKey) -> bytes: + """ + Given peer's DHPublicKey, carry out the key exchange and + return shared key as bytes. + """ + + @abc.abstractmethod + def private_numbers(self) -> DHPrivateNumbers: + """ + Returns a DHPrivateNumbers. + """ + + @abc.abstractmethod + def private_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PrivateFormat, + encryption_algorithm: _serialization.KeySerializationEncryption, + ) -> bytes: + """ + Returns the key serialized as bytes. + """ + + +DHPrivateKeyWithSerialization = DHPrivateKey +DHPrivateKey.register(rust_openssl.dh.DHPrivateKey) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/dsa.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/dsa.py new file mode 100644 index 0000000000000000000000000000000000000000..a8c52de4fb49fb1129e0acb806af1834be9d6b7d --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/dsa.py @@ -0,0 +1,299 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc +import typing + +from cryptography.hazmat.bindings._rust import openssl as rust_openssl +from cryptography.hazmat.primitives import _serialization, hashes +from cryptography.hazmat.primitives.asymmetric import utils as asym_utils + + +class DSAParameters(metaclass=abc.ABCMeta): + @abc.abstractmethod + def generate_private_key(self) -> DSAPrivateKey: + """ + Generates and returns a DSAPrivateKey. + """ + + @abc.abstractmethod + def parameter_numbers(self) -> DSAParameterNumbers: + """ + Returns a DSAParameterNumbers. + """ + + +DSAParametersWithNumbers = DSAParameters +DSAParameters.register(rust_openssl.dsa.DSAParameters) + + +class DSAPrivateKey(metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def key_size(self) -> int: + """ + The bit length of the prime modulus. + """ + + @abc.abstractmethod + def public_key(self) -> DSAPublicKey: + """ + The DSAPublicKey associated with this private key. + """ + + @abc.abstractmethod + def parameters(self) -> DSAParameters: + """ + The DSAParameters object associated with this private key. + """ + + @abc.abstractmethod + def sign( + self, + data: bytes, + algorithm: typing.Union[asym_utils.Prehashed, hashes.HashAlgorithm], + ) -> bytes: + """ + Signs the data + """ + + @abc.abstractmethod + def private_numbers(self) -> DSAPrivateNumbers: + """ + Returns a DSAPrivateNumbers. + """ + + @abc.abstractmethod + def private_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PrivateFormat, + encryption_algorithm: _serialization.KeySerializationEncryption, + ) -> bytes: + """ + Returns the key serialized as bytes. + """ + + +DSAPrivateKeyWithSerialization = DSAPrivateKey +DSAPrivateKey.register(rust_openssl.dsa.DSAPrivateKey) + + +class DSAPublicKey(metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def key_size(self) -> int: + """ + The bit length of the prime modulus. + """ + + @abc.abstractmethod + def parameters(self) -> DSAParameters: + """ + The DSAParameters object associated with this public key. + """ + + @abc.abstractmethod + def public_numbers(self) -> DSAPublicNumbers: + """ + Returns a DSAPublicNumbers. + """ + + @abc.abstractmethod + def public_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PublicFormat, + ) -> bytes: + """ + Returns the key serialized as bytes. + """ + + @abc.abstractmethod + def verify( + self, + signature: bytes, + data: bytes, + algorithm: typing.Union[asym_utils.Prehashed, hashes.HashAlgorithm], + ) -> None: + """ + Verifies the signature of the data. + """ + + @abc.abstractmethod + def __eq__(self, other: object) -> bool: + """ + Checks equality. + """ + + +DSAPublicKeyWithSerialization = DSAPublicKey +DSAPublicKey.register(rust_openssl.dsa.DSAPublicKey) + + +class DSAParameterNumbers: + def __init__(self, p: int, q: int, g: int): + if ( + not isinstance(p, int) + or not isinstance(q, int) + or not isinstance(g, int) + ): + raise TypeError( + "DSAParameterNumbers p, q, and g arguments must be integers." + ) + + self._p = p + self._q = q + self._g = g + + @property + def p(self) -> int: + return self._p + + @property + def q(self) -> int: + return self._q + + @property + def g(self) -> int: + return self._g + + def parameters(self, backend: typing.Any = None) -> DSAParameters: + from cryptography.hazmat.backends.openssl.backend import ( + backend as ossl, + ) + + return ossl.load_dsa_parameter_numbers(self) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, DSAParameterNumbers): + return NotImplemented + + return self.p == other.p and self.q == other.q and self.g == other.g + + def __repr__(self) -> str: + return ( + "".format(self=self) + ) + + +class DSAPublicNumbers: + def __init__(self, y: int, parameter_numbers: DSAParameterNumbers): + if not isinstance(y, int): + raise TypeError("DSAPublicNumbers y argument must be an integer.") + + if not isinstance(parameter_numbers, DSAParameterNumbers): + raise TypeError( + "parameter_numbers must be a DSAParameterNumbers instance." + ) + + self._y = y + self._parameter_numbers = parameter_numbers + + @property + def y(self) -> int: + return self._y + + @property + def parameter_numbers(self) -> DSAParameterNumbers: + return self._parameter_numbers + + def public_key(self, backend: typing.Any = None) -> DSAPublicKey: + from cryptography.hazmat.backends.openssl.backend import ( + backend as ossl, + ) + + return ossl.load_dsa_public_numbers(self) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, DSAPublicNumbers): + return NotImplemented + + return ( + self.y == other.y + and self.parameter_numbers == other.parameter_numbers + ) + + def __repr__(self) -> str: + return ( + "".format(self=self) + ) + + +class DSAPrivateNumbers: + def __init__(self, x: int, public_numbers: DSAPublicNumbers): + if not isinstance(x, int): + raise TypeError("DSAPrivateNumbers x argument must be an integer.") + + if not isinstance(public_numbers, DSAPublicNumbers): + raise TypeError( + "public_numbers must be a DSAPublicNumbers instance." + ) + self._public_numbers = public_numbers + self._x = x + + @property + def x(self) -> int: + return self._x + + @property + def public_numbers(self) -> DSAPublicNumbers: + return self._public_numbers + + def private_key(self, backend: typing.Any = None) -> DSAPrivateKey: + from cryptography.hazmat.backends.openssl.backend import ( + backend as ossl, + ) + + return ossl.load_dsa_private_numbers(self) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, DSAPrivateNumbers): + return NotImplemented + + return ( + self.x == other.x and self.public_numbers == other.public_numbers + ) + + +def generate_parameters( + key_size: int, backend: typing.Any = None +) -> DSAParameters: + from cryptography.hazmat.backends.openssl.backend import backend as ossl + + return ossl.generate_dsa_parameters(key_size) + + +def generate_private_key( + key_size: int, backend: typing.Any = None +) -> DSAPrivateKey: + from cryptography.hazmat.backends.openssl.backend import backend as ossl + + return ossl.generate_dsa_private_key_and_parameters(key_size) + + +def _check_dsa_parameters(parameters: DSAParameterNumbers) -> None: + if parameters.p.bit_length() not in [1024, 2048, 3072, 4096]: + raise ValueError( + "p must be exactly 1024, 2048, 3072, or 4096 bits long" + ) + if parameters.q.bit_length() not in [160, 224, 256]: + raise ValueError("q must be exactly 160, 224, or 256 bits long") + + if not (1 < parameters.g < parameters.p): + raise ValueError("g, p don't satisfy 1 < g < p.") + + +def _check_dsa_private_numbers(numbers: DSAPrivateNumbers) -> None: + parameters = numbers.public_numbers.parameter_numbers + _check_dsa_parameters(parameters) + if numbers.x <= 0 or numbers.x >= parameters.q: + raise ValueError("x must be > 0 and < q.") + + if numbers.public_numbers.y != pow(parameters.g, numbers.x, parameters.p): + raise ValueError("y must be equal to (g ** x % p).") diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/ec.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/ec.py new file mode 100644 index 0000000000000000000000000000000000000000..ddfaabf4f3e4e9807132e6fd6e1d23278f405f02 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/ec.py @@ -0,0 +1,490 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc +import typing + +from cryptography import utils +from cryptography.hazmat._oid import ObjectIdentifier +from cryptography.hazmat.primitives import _serialization, hashes +from cryptography.hazmat.primitives.asymmetric import utils as asym_utils + + +class EllipticCurveOID: + SECP192R1 = ObjectIdentifier("1.2.840.10045.3.1.1") + SECP224R1 = ObjectIdentifier("1.3.132.0.33") + SECP256K1 = ObjectIdentifier("1.3.132.0.10") + SECP256R1 = ObjectIdentifier("1.2.840.10045.3.1.7") + SECP384R1 = ObjectIdentifier("1.3.132.0.34") + SECP521R1 = ObjectIdentifier("1.3.132.0.35") + BRAINPOOLP256R1 = ObjectIdentifier("1.3.36.3.3.2.8.1.1.7") + BRAINPOOLP384R1 = ObjectIdentifier("1.3.36.3.3.2.8.1.1.11") + BRAINPOOLP512R1 = ObjectIdentifier("1.3.36.3.3.2.8.1.1.13") + SECT163K1 = ObjectIdentifier("1.3.132.0.1") + SECT163R2 = ObjectIdentifier("1.3.132.0.15") + SECT233K1 = ObjectIdentifier("1.3.132.0.26") + SECT233R1 = ObjectIdentifier("1.3.132.0.27") + SECT283K1 = ObjectIdentifier("1.3.132.0.16") + SECT283R1 = ObjectIdentifier("1.3.132.0.17") + SECT409K1 = ObjectIdentifier("1.3.132.0.36") + SECT409R1 = ObjectIdentifier("1.3.132.0.37") + SECT571K1 = ObjectIdentifier("1.3.132.0.38") + SECT571R1 = ObjectIdentifier("1.3.132.0.39") + + +class EllipticCurve(metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def name(self) -> str: + """ + The name of the curve. e.g. secp256r1. + """ + + @property + @abc.abstractmethod + def key_size(self) -> int: + """ + Bit size of a secret scalar for the curve. + """ + + +class EllipticCurveSignatureAlgorithm(metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def algorithm( + self, + ) -> typing.Union[asym_utils.Prehashed, hashes.HashAlgorithm]: + """ + The digest algorithm used with this signature. + """ + + +class EllipticCurvePrivateKey(metaclass=abc.ABCMeta): + @abc.abstractmethod + def exchange( + self, algorithm: ECDH, peer_public_key: EllipticCurvePublicKey + ) -> bytes: + """ + Performs a key exchange operation using the provided algorithm with the + provided peer's public key. + """ + + @abc.abstractmethod + def public_key(self) -> EllipticCurvePublicKey: + """ + The EllipticCurvePublicKey for this private key. + """ + + @property + @abc.abstractmethod + def curve(self) -> EllipticCurve: + """ + The EllipticCurve that this key is on. + """ + + @property + @abc.abstractmethod + def key_size(self) -> int: + """ + Bit size of a secret scalar for the curve. + """ + + @abc.abstractmethod + def sign( + self, + data: bytes, + signature_algorithm: EllipticCurveSignatureAlgorithm, + ) -> bytes: + """ + Signs the data + """ + + @abc.abstractmethod + def private_numbers(self) -> EllipticCurvePrivateNumbers: + """ + Returns an EllipticCurvePrivateNumbers. + """ + + @abc.abstractmethod + def private_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PrivateFormat, + encryption_algorithm: _serialization.KeySerializationEncryption, + ) -> bytes: + """ + Returns the key serialized as bytes. + """ + + +EllipticCurvePrivateKeyWithSerialization = EllipticCurvePrivateKey + + +class EllipticCurvePublicKey(metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def curve(self) -> EllipticCurve: + """ + The EllipticCurve that this key is on. + """ + + @property + @abc.abstractmethod + def key_size(self) -> int: + """ + Bit size of a secret scalar for the curve. + """ + + @abc.abstractmethod + def public_numbers(self) -> EllipticCurvePublicNumbers: + """ + Returns an EllipticCurvePublicNumbers. + """ + + @abc.abstractmethod + def public_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PublicFormat, + ) -> bytes: + """ + Returns the key serialized as bytes. + """ + + @abc.abstractmethod + def verify( + self, + signature: bytes, + data: bytes, + signature_algorithm: EllipticCurveSignatureAlgorithm, + ) -> None: + """ + Verifies the signature of the data. + """ + + @classmethod + def from_encoded_point( + cls, curve: EllipticCurve, data: bytes + ) -> EllipticCurvePublicKey: + utils._check_bytes("data", data) + + if not isinstance(curve, EllipticCurve): + raise TypeError("curve must be an EllipticCurve instance") + + if len(data) == 0: + raise ValueError("data must not be an empty byte string") + + if data[0] not in [0x02, 0x03, 0x04]: + raise ValueError("Unsupported elliptic curve point type") + + from cryptography.hazmat.backends.openssl.backend import backend + + return backend.load_elliptic_curve_public_bytes(curve, data) + + @abc.abstractmethod + def __eq__(self, other: object) -> bool: + """ + Checks equality. + """ + + +EllipticCurvePublicKeyWithSerialization = EllipticCurvePublicKey + + +class SECT571R1(EllipticCurve): + name = "sect571r1" + key_size = 570 + + +class SECT409R1(EllipticCurve): + name = "sect409r1" + key_size = 409 + + +class SECT283R1(EllipticCurve): + name = "sect283r1" + key_size = 283 + + +class SECT233R1(EllipticCurve): + name = "sect233r1" + key_size = 233 + + +class SECT163R2(EllipticCurve): + name = "sect163r2" + key_size = 163 + + +class SECT571K1(EllipticCurve): + name = "sect571k1" + key_size = 571 + + +class SECT409K1(EllipticCurve): + name = "sect409k1" + key_size = 409 + + +class SECT283K1(EllipticCurve): + name = "sect283k1" + key_size = 283 + + +class SECT233K1(EllipticCurve): + name = "sect233k1" + key_size = 233 + + +class SECT163K1(EllipticCurve): + name = "sect163k1" + key_size = 163 + + +class SECP521R1(EllipticCurve): + name = "secp521r1" + key_size = 521 + + +class SECP384R1(EllipticCurve): + name = "secp384r1" + key_size = 384 + + +class SECP256R1(EllipticCurve): + name = "secp256r1" + key_size = 256 + + +class SECP256K1(EllipticCurve): + name = "secp256k1" + key_size = 256 + + +class SECP224R1(EllipticCurve): + name = "secp224r1" + key_size = 224 + + +class SECP192R1(EllipticCurve): + name = "secp192r1" + key_size = 192 + + +class BrainpoolP256R1(EllipticCurve): + name = "brainpoolP256r1" + key_size = 256 + + +class BrainpoolP384R1(EllipticCurve): + name = "brainpoolP384r1" + key_size = 384 + + +class BrainpoolP512R1(EllipticCurve): + name = "brainpoolP512r1" + key_size = 512 + + +_CURVE_TYPES: typing.Dict[str, typing.Type[EllipticCurve]] = { + "prime192v1": SECP192R1, + "prime256v1": SECP256R1, + "secp192r1": SECP192R1, + "secp224r1": SECP224R1, + "secp256r1": SECP256R1, + "secp384r1": SECP384R1, + "secp521r1": SECP521R1, + "secp256k1": SECP256K1, + "sect163k1": SECT163K1, + "sect233k1": SECT233K1, + "sect283k1": SECT283K1, + "sect409k1": SECT409K1, + "sect571k1": SECT571K1, + "sect163r2": SECT163R2, + "sect233r1": SECT233R1, + "sect283r1": SECT283R1, + "sect409r1": SECT409R1, + "sect571r1": SECT571R1, + "brainpoolP256r1": BrainpoolP256R1, + "brainpoolP384r1": BrainpoolP384R1, + "brainpoolP512r1": BrainpoolP512R1, +} + + +class ECDSA(EllipticCurveSignatureAlgorithm): + def __init__( + self, + algorithm: typing.Union[asym_utils.Prehashed, hashes.HashAlgorithm], + ): + self._algorithm = algorithm + + @property + def algorithm( + self, + ) -> typing.Union[asym_utils.Prehashed, hashes.HashAlgorithm]: + return self._algorithm + + +def generate_private_key( + curve: EllipticCurve, backend: typing.Any = None +) -> EllipticCurvePrivateKey: + from cryptography.hazmat.backends.openssl.backend import backend as ossl + + return ossl.generate_elliptic_curve_private_key(curve) + + +def derive_private_key( + private_value: int, + curve: EllipticCurve, + backend: typing.Any = None, +) -> EllipticCurvePrivateKey: + from cryptography.hazmat.backends.openssl.backend import backend as ossl + + if not isinstance(private_value, int): + raise TypeError("private_value must be an integer type.") + + if private_value <= 0: + raise ValueError("private_value must be a positive integer.") + + if not isinstance(curve, EllipticCurve): + raise TypeError("curve must provide the EllipticCurve interface.") + + return ossl.derive_elliptic_curve_private_key(private_value, curve) + + +class EllipticCurvePublicNumbers: + def __init__(self, x: int, y: int, curve: EllipticCurve): + if not isinstance(x, int) or not isinstance(y, int): + raise TypeError("x and y must be integers.") + + if not isinstance(curve, EllipticCurve): + raise TypeError("curve must provide the EllipticCurve interface.") + + self._y = y + self._x = x + self._curve = curve + + def public_key(self, backend: typing.Any = None) -> EllipticCurvePublicKey: + from cryptography.hazmat.backends.openssl.backend import ( + backend as ossl, + ) + + return ossl.load_elliptic_curve_public_numbers(self) + + @property + def curve(self) -> EllipticCurve: + return self._curve + + @property + def x(self) -> int: + return self._x + + @property + def y(self) -> int: + return self._y + + def __eq__(self, other: object) -> bool: + if not isinstance(other, EllipticCurvePublicNumbers): + return NotImplemented + + return ( + self.x == other.x + and self.y == other.y + and self.curve.name == other.curve.name + and self.curve.key_size == other.curve.key_size + ) + + def __hash__(self) -> int: + return hash((self.x, self.y, self.curve.name, self.curve.key_size)) + + def __repr__(self) -> str: + return ( + "".format(self) + ) + + +class EllipticCurvePrivateNumbers: + def __init__( + self, private_value: int, public_numbers: EllipticCurvePublicNumbers + ): + if not isinstance(private_value, int): + raise TypeError("private_value must be an integer.") + + if not isinstance(public_numbers, EllipticCurvePublicNumbers): + raise TypeError( + "public_numbers must be an EllipticCurvePublicNumbers " + "instance." + ) + + self._private_value = private_value + self._public_numbers = public_numbers + + def private_key( + self, backend: typing.Any = None + ) -> EllipticCurvePrivateKey: + from cryptography.hazmat.backends.openssl.backend import ( + backend as ossl, + ) + + return ossl.load_elliptic_curve_private_numbers(self) + + @property + def private_value(self) -> int: + return self._private_value + + @property + def public_numbers(self) -> EllipticCurvePublicNumbers: + return self._public_numbers + + def __eq__(self, other: object) -> bool: + if not isinstance(other, EllipticCurvePrivateNumbers): + return NotImplemented + + return ( + self.private_value == other.private_value + and self.public_numbers == other.public_numbers + ) + + def __hash__(self) -> int: + return hash((self.private_value, self.public_numbers)) + + +class ECDH: + pass + + +_OID_TO_CURVE = { + EllipticCurveOID.SECP192R1: SECP192R1, + EllipticCurveOID.SECP224R1: SECP224R1, + EllipticCurveOID.SECP256K1: SECP256K1, + EllipticCurveOID.SECP256R1: SECP256R1, + EllipticCurveOID.SECP384R1: SECP384R1, + EllipticCurveOID.SECP521R1: SECP521R1, + EllipticCurveOID.BRAINPOOLP256R1: BrainpoolP256R1, + EllipticCurveOID.BRAINPOOLP384R1: BrainpoolP384R1, + EllipticCurveOID.BRAINPOOLP512R1: BrainpoolP512R1, + EllipticCurveOID.SECT163K1: SECT163K1, + EllipticCurveOID.SECT163R2: SECT163R2, + EllipticCurveOID.SECT233K1: SECT233K1, + EllipticCurveOID.SECT233R1: SECT233R1, + EllipticCurveOID.SECT283K1: SECT283K1, + EllipticCurveOID.SECT283R1: SECT283R1, + EllipticCurveOID.SECT409K1: SECT409K1, + EllipticCurveOID.SECT409R1: SECT409R1, + EllipticCurveOID.SECT571K1: SECT571K1, + EllipticCurveOID.SECT571R1: SECT571R1, +} + + +def get_curve_for_oid(oid: ObjectIdentifier) -> typing.Type[EllipticCurve]: + try: + return _OID_TO_CURVE[oid] + except KeyError: + raise LookupError( + "The provided object identifier has no matching elliptic " + "curve class" + ) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/ed25519.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/ed25519.py new file mode 100644 index 0000000000000000000000000000000000000000..f26e54d24ec50e9dd42abb5dbae75525535a441b --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/ed25519.py @@ -0,0 +1,118 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc + +from cryptography.exceptions import UnsupportedAlgorithm, _Reasons +from cryptography.hazmat.bindings._rust import openssl as rust_openssl +from cryptography.hazmat.primitives import _serialization + + +class Ed25519PublicKey(metaclass=abc.ABCMeta): + @classmethod + def from_public_bytes(cls, data: bytes) -> Ed25519PublicKey: + from cryptography.hazmat.backends.openssl.backend import backend + + if not backend.ed25519_supported(): + raise UnsupportedAlgorithm( + "ed25519 is not supported by this version of OpenSSL.", + _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, + ) + + return backend.ed25519_load_public_bytes(data) + + @abc.abstractmethod + def public_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PublicFormat, + ) -> bytes: + """ + The serialized bytes of the public key. + """ + + @abc.abstractmethod + def public_bytes_raw(self) -> bytes: + """ + The raw bytes of the public key. + Equivalent to public_bytes(Raw, Raw). + """ + + @abc.abstractmethod + def verify(self, signature: bytes, data: bytes) -> None: + """ + Verify the signature. + """ + + @abc.abstractmethod + def __eq__(self, other: object) -> bool: + """ + Checks equality. + """ + + +if hasattr(rust_openssl, "ed25519"): + Ed25519PublicKey.register(rust_openssl.ed25519.Ed25519PublicKey) + + +class Ed25519PrivateKey(metaclass=abc.ABCMeta): + @classmethod + def generate(cls) -> Ed25519PrivateKey: + from cryptography.hazmat.backends.openssl.backend import backend + + if not backend.ed25519_supported(): + raise UnsupportedAlgorithm( + "ed25519 is not supported by this version of OpenSSL.", + _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, + ) + + return backend.ed25519_generate_key() + + @classmethod + def from_private_bytes(cls, data: bytes) -> Ed25519PrivateKey: + from cryptography.hazmat.backends.openssl.backend import backend + + if not backend.ed25519_supported(): + raise UnsupportedAlgorithm( + "ed25519 is not supported by this version of OpenSSL.", + _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, + ) + + return backend.ed25519_load_private_bytes(data) + + @abc.abstractmethod + def public_key(self) -> Ed25519PublicKey: + """ + The Ed25519PublicKey derived from the private key. + """ + + @abc.abstractmethod + def private_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PrivateFormat, + encryption_algorithm: _serialization.KeySerializationEncryption, + ) -> bytes: + """ + The serialized bytes of the private key. + """ + + @abc.abstractmethod + def private_bytes_raw(self) -> bytes: + """ + The raw bytes of the private key. + Equivalent to private_bytes(Raw, Raw, NoEncryption()). + """ + + @abc.abstractmethod + def sign(self, data: bytes) -> bytes: + """ + Signs the data. + """ + + +if hasattr(rust_openssl, "x25519"): + Ed25519PrivateKey.register(rust_openssl.ed25519.Ed25519PrivateKey) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/ed448.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/ed448.py new file mode 100644 index 0000000000000000000000000000000000000000..a9a34b251b01178d6211111ee81c036ad908dc97 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/ed448.py @@ -0,0 +1,117 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc + +from cryptography.exceptions import UnsupportedAlgorithm, _Reasons +from cryptography.hazmat.bindings._rust import openssl as rust_openssl +from cryptography.hazmat.primitives import _serialization + + +class Ed448PublicKey(metaclass=abc.ABCMeta): + @classmethod + def from_public_bytes(cls, data: bytes) -> Ed448PublicKey: + from cryptography.hazmat.backends.openssl.backend import backend + + if not backend.ed448_supported(): + raise UnsupportedAlgorithm( + "ed448 is not supported by this version of OpenSSL.", + _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, + ) + + return backend.ed448_load_public_bytes(data) + + @abc.abstractmethod + def public_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PublicFormat, + ) -> bytes: + """ + The serialized bytes of the public key. + """ + + @abc.abstractmethod + def public_bytes_raw(self) -> bytes: + """ + The raw bytes of the public key. + Equivalent to public_bytes(Raw, Raw). + """ + + @abc.abstractmethod + def verify(self, signature: bytes, data: bytes) -> None: + """ + Verify the signature. + """ + + @abc.abstractmethod + def __eq__(self, other: object) -> bool: + """ + Checks equality. + """ + + +if hasattr(rust_openssl, "ed448"): + Ed448PublicKey.register(rust_openssl.ed448.Ed448PublicKey) + + +class Ed448PrivateKey(metaclass=abc.ABCMeta): + @classmethod + def generate(cls) -> Ed448PrivateKey: + from cryptography.hazmat.backends.openssl.backend import backend + + if not backend.ed448_supported(): + raise UnsupportedAlgorithm( + "ed448 is not supported by this version of OpenSSL.", + _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, + ) + return backend.ed448_generate_key() + + @classmethod + def from_private_bytes(cls, data: bytes) -> Ed448PrivateKey: + from cryptography.hazmat.backends.openssl.backend import backend + + if not backend.ed448_supported(): + raise UnsupportedAlgorithm( + "ed448 is not supported by this version of OpenSSL.", + _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, + ) + + return backend.ed448_load_private_bytes(data) + + @abc.abstractmethod + def public_key(self) -> Ed448PublicKey: + """ + The Ed448PublicKey derived from the private key. + """ + + @abc.abstractmethod + def sign(self, data: bytes) -> bytes: + """ + Signs the data. + """ + + @abc.abstractmethod + def private_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PrivateFormat, + encryption_algorithm: _serialization.KeySerializationEncryption, + ) -> bytes: + """ + The serialized bytes of the private key. + """ + + @abc.abstractmethod + def private_bytes_raw(self) -> bytes: + """ + The raw bytes of the private key. + Equivalent to private_bytes(Raw, Raw, NoEncryption()). + """ + + +if hasattr(rust_openssl, "x448"): + Ed448PrivateKey.register(rust_openssl.ed448.Ed448PrivateKey) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/padding.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/padding.py new file mode 100644 index 0000000000000000000000000000000000000000..7198808effd0d68a7cac9b338814ac1fb2e30234 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/padding.py @@ -0,0 +1,102 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc +import typing + +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives._asymmetric import ( + AsymmetricPadding as AsymmetricPadding, +) +from cryptography.hazmat.primitives.asymmetric import rsa + + +class PKCS1v15(AsymmetricPadding): + name = "EMSA-PKCS1-v1_5" + + +class _MaxLength: + "Sentinel value for `MAX_LENGTH`." + + +class _Auto: + "Sentinel value for `AUTO`." + + +class _DigestLength: + "Sentinel value for `DIGEST_LENGTH`." + + +class PSS(AsymmetricPadding): + MAX_LENGTH = _MaxLength() + AUTO = _Auto() + DIGEST_LENGTH = _DigestLength() + name = "EMSA-PSS" + _salt_length: typing.Union[int, _MaxLength, _Auto, _DigestLength] + + def __init__( + self, + mgf: MGF, + salt_length: typing.Union[int, _MaxLength, _Auto, _DigestLength], + ) -> None: + self._mgf = mgf + + if not isinstance( + salt_length, (int, _MaxLength, _Auto, _DigestLength) + ): + raise TypeError( + "salt_length must be an integer, MAX_LENGTH, " + "DIGEST_LENGTH, or AUTO" + ) + + if isinstance(salt_length, int) and salt_length < 0: + raise ValueError("salt_length must be zero or greater.") + + self._salt_length = salt_length + + +class OAEP(AsymmetricPadding): + name = "EME-OAEP" + + def __init__( + self, + mgf: MGF, + algorithm: hashes.HashAlgorithm, + label: typing.Optional[bytes], + ): + if not isinstance(algorithm, hashes.HashAlgorithm): + raise TypeError("Expected instance of hashes.HashAlgorithm.") + + self._mgf = mgf + self._algorithm = algorithm + self._label = label + + +class MGF(metaclass=abc.ABCMeta): + _algorithm: hashes.HashAlgorithm + + +class MGF1(MGF): + MAX_LENGTH = _MaxLength() + + def __init__(self, algorithm: hashes.HashAlgorithm): + if not isinstance(algorithm, hashes.HashAlgorithm): + raise TypeError("Expected instance of hashes.HashAlgorithm.") + + self._algorithm = algorithm + + +def calculate_max_pss_salt_length( + key: typing.Union[rsa.RSAPrivateKey, rsa.RSAPublicKey], + hash_algorithm: hashes.HashAlgorithm, +) -> int: + if not isinstance(key, (rsa.RSAPrivateKey, rsa.RSAPublicKey)): + raise TypeError("key must be an RSA public or private key") + # bit length - 1 per RFC 3447 + emlen = (key.key_size + 6) // 8 + salt_length = emlen - hash_algorithm.digest_size - 2 + assert salt_length >= 0 + return salt_length diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/rsa.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/rsa.py new file mode 100644 index 0000000000000000000000000000000000000000..b740f01f7c4cb67da3d5af4019e0b56d458b2658 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/rsa.py @@ -0,0 +1,439 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc +import typing +from math import gcd + +from cryptography.hazmat.primitives import _serialization, hashes +from cryptography.hazmat.primitives._asymmetric import AsymmetricPadding +from cryptography.hazmat.primitives.asymmetric import utils as asym_utils + + +class RSAPrivateKey(metaclass=abc.ABCMeta): + @abc.abstractmethod + def decrypt(self, ciphertext: bytes, padding: AsymmetricPadding) -> bytes: + """ + Decrypts the provided ciphertext. + """ + + @property + @abc.abstractmethod + def key_size(self) -> int: + """ + The bit length of the public modulus. + """ + + @abc.abstractmethod + def public_key(self) -> RSAPublicKey: + """ + The RSAPublicKey associated with this private key. + """ + + @abc.abstractmethod + def sign( + self, + data: bytes, + padding: AsymmetricPadding, + algorithm: typing.Union[asym_utils.Prehashed, hashes.HashAlgorithm], + ) -> bytes: + """ + Signs the data. + """ + + @abc.abstractmethod + def private_numbers(self) -> RSAPrivateNumbers: + """ + Returns an RSAPrivateNumbers. + """ + + @abc.abstractmethod + def private_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PrivateFormat, + encryption_algorithm: _serialization.KeySerializationEncryption, + ) -> bytes: + """ + Returns the key serialized as bytes. + """ + + +RSAPrivateKeyWithSerialization = RSAPrivateKey + + +class RSAPublicKey(metaclass=abc.ABCMeta): + @abc.abstractmethod + def encrypt(self, plaintext: bytes, padding: AsymmetricPadding) -> bytes: + """ + Encrypts the given plaintext. + """ + + @property + @abc.abstractmethod + def key_size(self) -> int: + """ + The bit length of the public modulus. + """ + + @abc.abstractmethod + def public_numbers(self) -> RSAPublicNumbers: + """ + Returns an RSAPublicNumbers + """ + + @abc.abstractmethod + def public_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PublicFormat, + ) -> bytes: + """ + Returns the key serialized as bytes. + """ + + @abc.abstractmethod + def verify( + self, + signature: bytes, + data: bytes, + padding: AsymmetricPadding, + algorithm: typing.Union[asym_utils.Prehashed, hashes.HashAlgorithm], + ) -> None: + """ + Verifies the signature of the data. + """ + + @abc.abstractmethod + def recover_data_from_signature( + self, + signature: bytes, + padding: AsymmetricPadding, + algorithm: typing.Optional[hashes.HashAlgorithm], + ) -> bytes: + """ + Recovers the original data from the signature. + """ + + @abc.abstractmethod + def __eq__(self, other: object) -> bool: + """ + Checks equality. + """ + + +RSAPublicKeyWithSerialization = RSAPublicKey + + +def generate_private_key( + public_exponent: int, + key_size: int, + backend: typing.Any = None, +) -> RSAPrivateKey: + from cryptography.hazmat.backends.openssl.backend import backend as ossl + + _verify_rsa_parameters(public_exponent, key_size) + return ossl.generate_rsa_private_key(public_exponent, key_size) + + +def _verify_rsa_parameters(public_exponent: int, key_size: int) -> None: + if public_exponent not in (3, 65537): + raise ValueError( + "public_exponent must be either 3 (for legacy compatibility) or " + "65537. Almost everyone should choose 65537 here!" + ) + + if key_size < 512: + raise ValueError("key_size must be at least 512-bits.") + + +def _check_private_key_components( + p: int, + q: int, + private_exponent: int, + dmp1: int, + dmq1: int, + iqmp: int, + public_exponent: int, + modulus: int, +) -> None: + if modulus < 3: + raise ValueError("modulus must be >= 3.") + + if p >= modulus: + raise ValueError("p must be < modulus.") + + if q >= modulus: + raise ValueError("q must be < modulus.") + + if dmp1 >= modulus: + raise ValueError("dmp1 must be < modulus.") + + if dmq1 >= modulus: + raise ValueError("dmq1 must be < modulus.") + + if iqmp >= modulus: + raise ValueError("iqmp must be < modulus.") + + if private_exponent >= modulus: + raise ValueError("private_exponent must be < modulus.") + + if public_exponent < 3 or public_exponent >= modulus: + raise ValueError("public_exponent must be >= 3 and < modulus.") + + if public_exponent & 1 == 0: + raise ValueError("public_exponent must be odd.") + + if dmp1 & 1 == 0: + raise ValueError("dmp1 must be odd.") + + if dmq1 & 1 == 0: + raise ValueError("dmq1 must be odd.") + + if p * q != modulus: + raise ValueError("p*q must equal modulus.") + + +def _check_public_key_components(e: int, n: int) -> None: + if n < 3: + raise ValueError("n must be >= 3.") + + if e < 3 or e >= n: + raise ValueError("e must be >= 3 and < n.") + + if e & 1 == 0: + raise ValueError("e must be odd.") + + +def _modinv(e: int, m: int) -> int: + """ + Modular Multiplicative Inverse. Returns x such that: (x*e) mod m == 1 + """ + x1, x2 = 1, 0 + a, b = e, m + while b > 0: + q, r = divmod(a, b) + xn = x1 - q * x2 + a, b, x1, x2 = b, r, x2, xn + return x1 % m + + +def rsa_crt_iqmp(p: int, q: int) -> int: + """ + Compute the CRT (q ** -1) % p value from RSA primes p and q. + """ + return _modinv(q, p) + + +def rsa_crt_dmp1(private_exponent: int, p: int) -> int: + """ + Compute the CRT private_exponent % (p - 1) value from the RSA + private_exponent (d) and p. + """ + return private_exponent % (p - 1) + + +def rsa_crt_dmq1(private_exponent: int, q: int) -> int: + """ + Compute the CRT private_exponent % (q - 1) value from the RSA + private_exponent (d) and q. + """ + return private_exponent % (q - 1) + + +# Controls the number of iterations rsa_recover_prime_factors will perform +# to obtain the prime factors. Each iteration increments by 2 so the actual +# maximum attempts is half this number. +_MAX_RECOVERY_ATTEMPTS = 1000 + + +def rsa_recover_prime_factors( + n: int, e: int, d: int +) -> typing.Tuple[int, int]: + """ + Compute factors p and q from the private exponent d. We assume that n has + no more than two factors. This function is adapted from code in PyCrypto. + """ + # See 8.2.2(i) in Handbook of Applied Cryptography. + ktot = d * e - 1 + # The quantity d*e-1 is a multiple of phi(n), even, + # and can be represented as t*2^s. + t = ktot + while t % 2 == 0: + t = t // 2 + # Cycle through all multiplicative inverses in Zn. + # The algorithm is non-deterministic, but there is a 50% chance + # any candidate a leads to successful factoring. + # See "Digitalized Signatures and Public Key Functions as Intractable + # as Factorization", M. Rabin, 1979 + spotted = False + a = 2 + while not spotted and a < _MAX_RECOVERY_ATTEMPTS: + k = t + # Cycle through all values a^{t*2^i}=a^k + while k < ktot: + cand = pow(a, k, n) + # Check if a^k is a non-trivial root of unity (mod n) + if cand != 1 and cand != (n - 1) and pow(cand, 2, n) == 1: + # We have found a number such that (cand-1)(cand+1)=0 (mod n). + # Either of the terms divides n. + p = gcd(cand + 1, n) + spotted = True + break + k *= 2 + # This value was not any good... let's try another! + a += 2 + if not spotted: + raise ValueError("Unable to compute factors p and q from exponent d.") + # Found ! + q, r = divmod(n, p) + assert r == 0 + p, q = sorted((p, q), reverse=True) + return (p, q) + + +class RSAPrivateNumbers: + def __init__( + self, + p: int, + q: int, + d: int, + dmp1: int, + dmq1: int, + iqmp: int, + public_numbers: RSAPublicNumbers, + ): + if ( + not isinstance(p, int) + or not isinstance(q, int) + or not isinstance(d, int) + or not isinstance(dmp1, int) + or not isinstance(dmq1, int) + or not isinstance(iqmp, int) + ): + raise TypeError( + "RSAPrivateNumbers p, q, d, dmp1, dmq1, iqmp arguments must" + " all be an integers." + ) + + if not isinstance(public_numbers, RSAPublicNumbers): + raise TypeError( + "RSAPrivateNumbers public_numbers must be an RSAPublicNumbers" + " instance." + ) + + self._p = p + self._q = q + self._d = d + self._dmp1 = dmp1 + self._dmq1 = dmq1 + self._iqmp = iqmp + self._public_numbers = public_numbers + + @property + def p(self) -> int: + return self._p + + @property + def q(self) -> int: + return self._q + + @property + def d(self) -> int: + return self._d + + @property + def dmp1(self) -> int: + return self._dmp1 + + @property + def dmq1(self) -> int: + return self._dmq1 + + @property + def iqmp(self) -> int: + return self._iqmp + + @property + def public_numbers(self) -> RSAPublicNumbers: + return self._public_numbers + + def private_key( + self, + backend: typing.Any = None, + *, + unsafe_skip_rsa_key_validation: bool = False, + ) -> RSAPrivateKey: + from cryptography.hazmat.backends.openssl.backend import ( + backend as ossl, + ) + + return ossl.load_rsa_private_numbers( + self, unsafe_skip_rsa_key_validation + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, RSAPrivateNumbers): + return NotImplemented + + return ( + self.p == other.p + and self.q == other.q + and self.d == other.d + and self.dmp1 == other.dmp1 + and self.dmq1 == other.dmq1 + and self.iqmp == other.iqmp + and self.public_numbers == other.public_numbers + ) + + def __hash__(self) -> int: + return hash( + ( + self.p, + self.q, + self.d, + self.dmp1, + self.dmq1, + self.iqmp, + self.public_numbers, + ) + ) + + +class RSAPublicNumbers: + def __init__(self, e: int, n: int): + if not isinstance(e, int) or not isinstance(n, int): + raise TypeError("RSAPublicNumbers arguments must be integers.") + + self._e = e + self._n = n + + @property + def e(self) -> int: + return self._e + + @property + def n(self) -> int: + return self._n + + def public_key(self, backend: typing.Any = None) -> RSAPublicKey: + from cryptography.hazmat.backends.openssl.backend import ( + backend as ossl, + ) + + return ossl.load_rsa_public_numbers(self) + + def __repr__(self) -> str: + return "".format(self) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, RSAPublicNumbers): + return NotImplemented + + return self.e == other.e and self.n == other.n + + def __hash__(self) -> int: + return hash((self.e, self.n)) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/types.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/types.py new file mode 100644 index 0000000000000000000000000000000000000000..1fe4eaf51d850c30ef7764d1c0bbf17533b8ad38 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/types.py @@ -0,0 +1,111 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import typing + +from cryptography import utils +from cryptography.hazmat.primitives.asymmetric import ( + dh, + dsa, + ec, + ed448, + ed25519, + rsa, + x448, + x25519, +) + +# Every asymmetric key type +PublicKeyTypes = typing.Union[ + dh.DHPublicKey, + dsa.DSAPublicKey, + rsa.RSAPublicKey, + ec.EllipticCurvePublicKey, + ed25519.Ed25519PublicKey, + ed448.Ed448PublicKey, + x25519.X25519PublicKey, + x448.X448PublicKey, +] +PUBLIC_KEY_TYPES = PublicKeyTypes +utils.deprecated( + PUBLIC_KEY_TYPES, + __name__, + "Use PublicKeyTypes instead", + utils.DeprecatedIn40, + name="PUBLIC_KEY_TYPES", +) +# Every asymmetric key type +PrivateKeyTypes = typing.Union[ + dh.DHPrivateKey, + ed25519.Ed25519PrivateKey, + ed448.Ed448PrivateKey, + rsa.RSAPrivateKey, + dsa.DSAPrivateKey, + ec.EllipticCurvePrivateKey, + x25519.X25519PrivateKey, + x448.X448PrivateKey, +] +PRIVATE_KEY_TYPES = PrivateKeyTypes +utils.deprecated( + PRIVATE_KEY_TYPES, + __name__, + "Use PrivateKeyTypes instead", + utils.DeprecatedIn40, + name="PRIVATE_KEY_TYPES", +) +# Just the key types we allow to be used for x509 signing. This mirrors +# the certificate public key types +CertificateIssuerPrivateKeyTypes = typing.Union[ + ed25519.Ed25519PrivateKey, + ed448.Ed448PrivateKey, + rsa.RSAPrivateKey, + dsa.DSAPrivateKey, + ec.EllipticCurvePrivateKey, +] +CERTIFICATE_PRIVATE_KEY_TYPES = CertificateIssuerPrivateKeyTypes +utils.deprecated( + CERTIFICATE_PRIVATE_KEY_TYPES, + __name__, + "Use CertificateIssuerPrivateKeyTypes instead", + utils.DeprecatedIn40, + name="CERTIFICATE_PRIVATE_KEY_TYPES", +) +# Just the key types we allow to be used for x509 signing. This mirrors +# the certificate private key types +CertificateIssuerPublicKeyTypes = typing.Union[ + dsa.DSAPublicKey, + rsa.RSAPublicKey, + ec.EllipticCurvePublicKey, + ed25519.Ed25519PublicKey, + ed448.Ed448PublicKey, +] +CERTIFICATE_ISSUER_PUBLIC_KEY_TYPES = CertificateIssuerPublicKeyTypes +utils.deprecated( + CERTIFICATE_ISSUER_PUBLIC_KEY_TYPES, + __name__, + "Use CertificateIssuerPublicKeyTypes instead", + utils.DeprecatedIn40, + name="CERTIFICATE_ISSUER_PUBLIC_KEY_TYPES", +) +# This type removes DHPublicKey. x448/x25519 can be a public key +# but cannot be used in signing so they are allowed here. +CertificatePublicKeyTypes = typing.Union[ + dsa.DSAPublicKey, + rsa.RSAPublicKey, + ec.EllipticCurvePublicKey, + ed25519.Ed25519PublicKey, + ed448.Ed448PublicKey, + x25519.X25519PublicKey, + x448.X448PublicKey, +] +CERTIFICATE_PUBLIC_KEY_TYPES = CertificatePublicKeyTypes +utils.deprecated( + CERTIFICATE_PUBLIC_KEY_TYPES, + __name__, + "Use CertificatePublicKeyTypes instead", + utils.DeprecatedIn40, + name="CERTIFICATE_PUBLIC_KEY_TYPES", +) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/utils.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..826b9567b47bc704902eb959fd21376c8969f695 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/utils.py @@ -0,0 +1,24 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography.hazmat.bindings._rust import asn1 +from cryptography.hazmat.primitives import hashes + +decode_dss_signature = asn1.decode_dss_signature +encode_dss_signature = asn1.encode_dss_signature + + +class Prehashed: + def __init__(self, algorithm: hashes.HashAlgorithm): + if not isinstance(algorithm, hashes.HashAlgorithm): + raise TypeError("Expected instance of HashAlgorithm.") + + self._algorithm = algorithm + self._digest_size = algorithm.digest_size + + @property + def digest_size(self) -> int: + return self._digest_size diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/x25519.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/x25519.py new file mode 100644 index 0000000000000000000000000000000000000000..699054c9689ba0da21cd4397602d7139acceb238 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/x25519.py @@ -0,0 +1,113 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc + +from cryptography.exceptions import UnsupportedAlgorithm, _Reasons +from cryptography.hazmat.bindings._rust import openssl as rust_openssl +from cryptography.hazmat.primitives import _serialization + + +class X25519PublicKey(metaclass=abc.ABCMeta): + @classmethod + def from_public_bytes(cls, data: bytes) -> X25519PublicKey: + from cryptography.hazmat.backends.openssl.backend import backend + + if not backend.x25519_supported(): + raise UnsupportedAlgorithm( + "X25519 is not supported by this version of OpenSSL.", + _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM, + ) + + return backend.x25519_load_public_bytes(data) + + @abc.abstractmethod + def public_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PublicFormat, + ) -> bytes: + """ + The serialized bytes of the public key. + """ + + @abc.abstractmethod + def public_bytes_raw(self) -> bytes: + """ + The raw bytes of the public key. + Equivalent to public_bytes(Raw, Raw). + """ + + @abc.abstractmethod + def __eq__(self, other: object) -> bool: + """ + Checks equality. + """ + + +# For LibreSSL +if hasattr(rust_openssl, "x25519"): + X25519PublicKey.register(rust_openssl.x25519.X25519PublicKey) + + +class X25519PrivateKey(metaclass=abc.ABCMeta): + @classmethod + def generate(cls) -> X25519PrivateKey: + from cryptography.hazmat.backends.openssl.backend import backend + + if not backend.x25519_supported(): + raise UnsupportedAlgorithm( + "X25519 is not supported by this version of OpenSSL.", + _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM, + ) + return backend.x25519_generate_key() + + @classmethod + def from_private_bytes(cls, data: bytes) -> X25519PrivateKey: + from cryptography.hazmat.backends.openssl.backend import backend + + if not backend.x25519_supported(): + raise UnsupportedAlgorithm( + "X25519 is not supported by this version of OpenSSL.", + _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM, + ) + + return backend.x25519_load_private_bytes(data) + + @abc.abstractmethod + def public_key(self) -> X25519PublicKey: + """ + Returns the public key assosciated with this private key + """ + + @abc.abstractmethod + def private_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PrivateFormat, + encryption_algorithm: _serialization.KeySerializationEncryption, + ) -> bytes: + """ + The serialized bytes of the private key. + """ + + @abc.abstractmethod + def private_bytes_raw(self) -> bytes: + """ + The raw bytes of the private key. + Equivalent to private_bytes(Raw, Raw, NoEncryption()). + """ + + @abc.abstractmethod + def exchange(self, peer_public_key: X25519PublicKey) -> bytes: + """ + Performs a key exchange operation using the provided peer's public key. + """ + + +# For LibreSSL +if hasattr(rust_openssl, "x25519"): + X25519PrivateKey.register(rust_openssl.x25519.X25519PrivateKey) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/x448.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/x448.py new file mode 100644 index 0000000000000000000000000000000000000000..abf7848550b8b42fea24155e614d4228fcf2b1e1 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/asymmetric/x448.py @@ -0,0 +1,111 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc + +from cryptography.exceptions import UnsupportedAlgorithm, _Reasons +from cryptography.hazmat.bindings._rust import openssl as rust_openssl +from cryptography.hazmat.primitives import _serialization + + +class X448PublicKey(metaclass=abc.ABCMeta): + @classmethod + def from_public_bytes(cls, data: bytes) -> X448PublicKey: + from cryptography.hazmat.backends.openssl.backend import backend + + if not backend.x448_supported(): + raise UnsupportedAlgorithm( + "X448 is not supported by this version of OpenSSL.", + _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM, + ) + + return backend.x448_load_public_bytes(data) + + @abc.abstractmethod + def public_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PublicFormat, + ) -> bytes: + """ + The serialized bytes of the public key. + """ + + @abc.abstractmethod + def public_bytes_raw(self) -> bytes: + """ + The raw bytes of the public key. + Equivalent to public_bytes(Raw, Raw). + """ + + @abc.abstractmethod + def __eq__(self, other: object) -> bool: + """ + Checks equality. + """ + + +if hasattr(rust_openssl, "x448"): + X448PublicKey.register(rust_openssl.x448.X448PublicKey) + + +class X448PrivateKey(metaclass=abc.ABCMeta): + @classmethod + def generate(cls) -> X448PrivateKey: + from cryptography.hazmat.backends.openssl.backend import backend + + if not backend.x448_supported(): + raise UnsupportedAlgorithm( + "X448 is not supported by this version of OpenSSL.", + _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM, + ) + return backend.x448_generate_key() + + @classmethod + def from_private_bytes(cls, data: bytes) -> X448PrivateKey: + from cryptography.hazmat.backends.openssl.backend import backend + + if not backend.x448_supported(): + raise UnsupportedAlgorithm( + "X448 is not supported by this version of OpenSSL.", + _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM, + ) + + return backend.x448_load_private_bytes(data) + + @abc.abstractmethod + def public_key(self) -> X448PublicKey: + """ + Returns the public key associated with this private key + """ + + @abc.abstractmethod + def private_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PrivateFormat, + encryption_algorithm: _serialization.KeySerializationEncryption, + ) -> bytes: + """ + The serialized bytes of the private key. + """ + + @abc.abstractmethod + def private_bytes_raw(self) -> bytes: + """ + The raw bytes of the private key. + Equivalent to private_bytes(Raw, Raw, NoEncryption()). + """ + + @abc.abstractmethod + def exchange(self, peer_public_key: X448PublicKey) -> bytes: + """ + Performs a key exchange operation using the provided peer's public key. + """ + + +if hasattr(rust_openssl, "x448"): + X448PrivateKey.register(rust_openssl.x448.X448PrivateKey) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/ciphers/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/ciphers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cc88fbf2c4c30c6c11564ff7ecbfdeb0ca6d5170 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/ciphers/__init__.py @@ -0,0 +1,27 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography.hazmat.primitives._cipheralgorithm import ( + BlockCipherAlgorithm, + CipherAlgorithm, +) +from cryptography.hazmat.primitives.ciphers.base import ( + AEADCipherContext, + AEADDecryptionContext, + AEADEncryptionContext, + Cipher, + CipherContext, +) + +__all__ = [ + "Cipher", + "CipherAlgorithm", + "BlockCipherAlgorithm", + "CipherContext", + "AEADCipherContext", + "AEADDecryptionContext", + "AEADEncryptionContext", +] diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/ciphers/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/ciphers/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6dd43a60b47edd95a067139c5b7652f91f8f8c4f Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/ciphers/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/ciphers/__pycache__/aead.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/ciphers/__pycache__/aead.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6b6ad68c1b9beee6eef56ac16ef650efc4ec9602 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/ciphers/__pycache__/aead.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/ciphers/__pycache__/algorithms.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/ciphers/__pycache__/algorithms.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e5a0a55d8b71ae14a420338db3603875659eb474 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/ciphers/__pycache__/algorithms.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/ciphers/__pycache__/base.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/ciphers/__pycache__/base.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..71b4db7f95817d61d4ef7a331d5b13e5a1923623 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/ciphers/__pycache__/base.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/ciphers/__pycache__/modes.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/ciphers/__pycache__/modes.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b98fe4f36ddfc3cc46d996ec857bedc5c376fdb Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/ciphers/__pycache__/modes.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/ciphers/aead.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/ciphers/aead.py new file mode 100644 index 0000000000000000000000000000000000000000..957b2d221b62741490044fe114e8c0bc4c90e693 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/ciphers/aead.py @@ -0,0 +1,378 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import os +import typing + +from cryptography import exceptions, utils +from cryptography.hazmat.backends.openssl import aead +from cryptography.hazmat.backends.openssl.backend import backend +from cryptography.hazmat.bindings._rust import FixedPool + + +class ChaCha20Poly1305: + _MAX_SIZE = 2**31 - 1 + + def __init__(self, key: bytes): + if not backend.aead_cipher_supported(self): + raise exceptions.UnsupportedAlgorithm( + "ChaCha20Poly1305 is not supported by this version of OpenSSL", + exceptions._Reasons.UNSUPPORTED_CIPHER, + ) + utils._check_byteslike("key", key) + + if len(key) != 32: + raise ValueError("ChaCha20Poly1305 key must be 32 bytes.") + + self._key = key + self._pool = FixedPool(self._create_fn) + + @classmethod + def generate_key(cls) -> bytes: + return os.urandom(32) + + def _create_fn(self): + return aead._aead_create_ctx(backend, self, self._key) + + def encrypt( + self, + nonce: bytes, + data: bytes, + associated_data: typing.Optional[bytes], + ) -> bytes: + if associated_data is None: + associated_data = b"" + + if len(data) > self._MAX_SIZE or len(associated_data) > self._MAX_SIZE: + # This is OverflowError to match what cffi would raise + raise OverflowError( + "Data or associated data too long. Max 2**31 - 1 bytes" + ) + + self._check_params(nonce, data, associated_data) + with self._pool.acquire() as ctx: + return aead._encrypt( + backend, self, nonce, data, [associated_data], 16, ctx + ) + + def decrypt( + self, + nonce: bytes, + data: bytes, + associated_data: typing.Optional[bytes], + ) -> bytes: + if associated_data is None: + associated_data = b"" + + self._check_params(nonce, data, associated_data) + with self._pool.acquire() as ctx: + return aead._decrypt( + backend, self, nonce, data, [associated_data], 16, ctx + ) + + def _check_params( + self, + nonce: bytes, + data: bytes, + associated_data: bytes, + ) -> None: + utils._check_byteslike("nonce", nonce) + utils._check_byteslike("data", data) + utils._check_byteslike("associated_data", associated_data) + if len(nonce) != 12: + raise ValueError("Nonce must be 12 bytes") + + +class AESCCM: + _MAX_SIZE = 2**31 - 1 + + def __init__(self, key: bytes, tag_length: int = 16): + utils._check_byteslike("key", key) + if len(key) not in (16, 24, 32): + raise ValueError("AESCCM key must be 128, 192, or 256 bits.") + + self._key = key + if not isinstance(tag_length, int): + raise TypeError("tag_length must be an integer") + + if tag_length not in (4, 6, 8, 10, 12, 14, 16): + raise ValueError("Invalid tag_length") + + self._tag_length = tag_length + + if not backend.aead_cipher_supported(self): + raise exceptions.UnsupportedAlgorithm( + "AESCCM is not supported by this version of OpenSSL", + exceptions._Reasons.UNSUPPORTED_CIPHER, + ) + + @classmethod + def generate_key(cls, bit_length: int) -> bytes: + if not isinstance(bit_length, int): + raise TypeError("bit_length must be an integer") + + if bit_length not in (128, 192, 256): + raise ValueError("bit_length must be 128, 192, or 256") + + return os.urandom(bit_length // 8) + + def encrypt( + self, + nonce: bytes, + data: bytes, + associated_data: typing.Optional[bytes], + ) -> bytes: + if associated_data is None: + associated_data = b"" + + if len(data) > self._MAX_SIZE or len(associated_data) > self._MAX_SIZE: + # This is OverflowError to match what cffi would raise + raise OverflowError( + "Data or associated data too long. Max 2**31 - 1 bytes" + ) + + self._check_params(nonce, data, associated_data) + self._validate_lengths(nonce, len(data)) + return aead._encrypt( + backend, self, nonce, data, [associated_data], self._tag_length + ) + + def decrypt( + self, + nonce: bytes, + data: bytes, + associated_data: typing.Optional[bytes], + ) -> bytes: + if associated_data is None: + associated_data = b"" + + self._check_params(nonce, data, associated_data) + return aead._decrypt( + backend, self, nonce, data, [associated_data], self._tag_length + ) + + def _validate_lengths(self, nonce: bytes, data_len: int) -> None: + # For information about computing this, see + # https://tools.ietf.org/html/rfc3610#section-2.1 + l_val = 15 - len(nonce) + if 2 ** (8 * l_val) < data_len: + raise ValueError("Data too long for nonce") + + def _check_params( + self, nonce: bytes, data: bytes, associated_data: bytes + ) -> None: + utils._check_byteslike("nonce", nonce) + utils._check_byteslike("data", data) + utils._check_byteslike("associated_data", associated_data) + if not 7 <= len(nonce) <= 13: + raise ValueError("Nonce must be between 7 and 13 bytes") + + +class AESGCM: + _MAX_SIZE = 2**31 - 1 + + def __init__(self, key: bytes): + utils._check_byteslike("key", key) + if len(key) not in (16, 24, 32): + raise ValueError("AESGCM key must be 128, 192, or 256 bits.") + + self._key = key + + @classmethod + def generate_key(cls, bit_length: int) -> bytes: + if not isinstance(bit_length, int): + raise TypeError("bit_length must be an integer") + + if bit_length not in (128, 192, 256): + raise ValueError("bit_length must be 128, 192, or 256") + + return os.urandom(bit_length // 8) + + def encrypt( + self, + nonce: bytes, + data: bytes, + associated_data: typing.Optional[bytes], + ) -> bytes: + if associated_data is None: + associated_data = b"" + + if len(data) > self._MAX_SIZE or len(associated_data) > self._MAX_SIZE: + # This is OverflowError to match what cffi would raise + raise OverflowError( + "Data or associated data too long. Max 2**31 - 1 bytes" + ) + + self._check_params(nonce, data, associated_data) + return aead._encrypt(backend, self, nonce, data, [associated_data], 16) + + def decrypt( + self, + nonce: bytes, + data: bytes, + associated_data: typing.Optional[bytes], + ) -> bytes: + if associated_data is None: + associated_data = b"" + + self._check_params(nonce, data, associated_data) + return aead._decrypt(backend, self, nonce, data, [associated_data], 16) + + def _check_params( + self, + nonce: bytes, + data: bytes, + associated_data: bytes, + ) -> None: + utils._check_byteslike("nonce", nonce) + utils._check_byteslike("data", data) + utils._check_byteslike("associated_data", associated_data) + if len(nonce) < 8 or len(nonce) > 128: + raise ValueError("Nonce must be between 8 and 128 bytes") + + +class AESOCB3: + _MAX_SIZE = 2**31 - 1 + + def __init__(self, key: bytes): + utils._check_byteslike("key", key) + if len(key) not in (16, 24, 32): + raise ValueError("AESOCB3 key must be 128, 192, or 256 bits.") + + self._key = key + + if not backend.aead_cipher_supported(self): + raise exceptions.UnsupportedAlgorithm( + "OCB3 is not supported by this version of OpenSSL", + exceptions._Reasons.UNSUPPORTED_CIPHER, + ) + + @classmethod + def generate_key(cls, bit_length: int) -> bytes: + if not isinstance(bit_length, int): + raise TypeError("bit_length must be an integer") + + if bit_length not in (128, 192, 256): + raise ValueError("bit_length must be 128, 192, or 256") + + return os.urandom(bit_length // 8) + + def encrypt( + self, + nonce: bytes, + data: bytes, + associated_data: typing.Optional[bytes], + ) -> bytes: + if associated_data is None: + associated_data = b"" + + if len(data) > self._MAX_SIZE or len(associated_data) > self._MAX_SIZE: + # This is OverflowError to match what cffi would raise + raise OverflowError( + "Data or associated data too long. Max 2**31 - 1 bytes" + ) + + self._check_params(nonce, data, associated_data) + return aead._encrypt(backend, self, nonce, data, [associated_data], 16) + + def decrypt( + self, + nonce: bytes, + data: bytes, + associated_data: typing.Optional[bytes], + ) -> bytes: + if associated_data is None: + associated_data = b"" + + self._check_params(nonce, data, associated_data) + return aead._decrypt(backend, self, nonce, data, [associated_data], 16) + + def _check_params( + self, + nonce: bytes, + data: bytes, + associated_data: bytes, + ) -> None: + utils._check_byteslike("nonce", nonce) + utils._check_byteslike("data", data) + utils._check_byteslike("associated_data", associated_data) + if len(nonce) < 12 or len(nonce) > 15: + raise ValueError("Nonce must be between 12 and 15 bytes") + + +class AESSIV: + _MAX_SIZE = 2**31 - 1 + + def __init__(self, key: bytes): + utils._check_byteslike("key", key) + if len(key) not in (32, 48, 64): + raise ValueError("AESSIV key must be 256, 384, or 512 bits.") + + self._key = key + + if not backend.aead_cipher_supported(self): + raise exceptions.UnsupportedAlgorithm( + "AES-SIV is not supported by this version of OpenSSL", + exceptions._Reasons.UNSUPPORTED_CIPHER, + ) + + @classmethod + def generate_key(cls, bit_length: int) -> bytes: + if not isinstance(bit_length, int): + raise TypeError("bit_length must be an integer") + + if bit_length not in (256, 384, 512): + raise ValueError("bit_length must be 256, 384, or 512") + + return os.urandom(bit_length // 8) + + def encrypt( + self, + data: bytes, + associated_data: typing.Optional[typing.List[bytes]], + ) -> bytes: + if associated_data is None: + associated_data = [] + + self._check_params(data, associated_data) + + if len(data) > self._MAX_SIZE or any( + len(ad) > self._MAX_SIZE for ad in associated_data + ): + # This is OverflowError to match what cffi would raise + raise OverflowError( + "Data or associated data too long. Max 2**31 - 1 bytes" + ) + + return aead._encrypt(backend, self, b"", data, associated_data, 16) + + def decrypt( + self, + data: bytes, + associated_data: typing.Optional[typing.List[bytes]], + ) -> bytes: + if associated_data is None: + associated_data = [] + + self._check_params(data, associated_data) + + return aead._decrypt(backend, self, b"", data, associated_data, 16) + + def _check_params( + self, + data: bytes, + associated_data: typing.List[bytes], + ) -> None: + utils._check_byteslike("data", data) + if len(data) == 0: + raise ValueError("data must not be zero length") + + if not isinstance(associated_data, list): + raise TypeError( + "associated_data must be a list of bytes-like objects or None" + ) + for x in associated_data: + utils._check_byteslike("associated_data elements", x) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/ciphers/algorithms.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/ciphers/algorithms.py new file mode 100644 index 0000000000000000000000000000000000000000..4bfc5d840d67411183d3f56854dc42cde8c066ff --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/ciphers/algorithms.py @@ -0,0 +1,228 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography import utils +from cryptography.hazmat.primitives.ciphers import ( + BlockCipherAlgorithm, + CipherAlgorithm, +) + + +def _verify_key_size(algorithm: CipherAlgorithm, key: bytes) -> bytes: + # Verify that the key is instance of bytes + utils._check_byteslike("key", key) + + # Verify that the key size matches the expected key size + if len(key) * 8 not in algorithm.key_sizes: + raise ValueError( + "Invalid key size ({}) for {}.".format( + len(key) * 8, algorithm.name + ) + ) + return key + + +class AES(BlockCipherAlgorithm): + name = "AES" + block_size = 128 + # 512 added to support AES-256-XTS, which uses 512-bit keys + key_sizes = frozenset([128, 192, 256, 512]) + + def __init__(self, key: bytes): + self.key = _verify_key_size(self, key) + + @property + def key_size(self) -> int: + return len(self.key) * 8 + + +class AES128(BlockCipherAlgorithm): + name = "AES" + block_size = 128 + key_sizes = frozenset([128]) + key_size = 128 + + def __init__(self, key: bytes): + self.key = _verify_key_size(self, key) + + +class AES256(BlockCipherAlgorithm): + name = "AES" + block_size = 128 + key_sizes = frozenset([256]) + key_size = 256 + + def __init__(self, key: bytes): + self.key = _verify_key_size(self, key) + + +class Camellia(BlockCipherAlgorithm): + name = "camellia" + block_size = 128 + key_sizes = frozenset([128, 192, 256]) + + def __init__(self, key: bytes): + self.key = _verify_key_size(self, key) + + @property + def key_size(self) -> int: + return len(self.key) * 8 + + +class TripleDES(BlockCipherAlgorithm): + name = "3DES" + block_size = 64 + key_sizes = frozenset([64, 128, 192]) + + def __init__(self, key: bytes): + if len(key) == 8: + key += key + key + elif len(key) == 16: + key += key[:8] + self.key = _verify_key_size(self, key) + + @property + def key_size(self) -> int: + return len(self.key) * 8 + + +class Blowfish(BlockCipherAlgorithm): + name = "Blowfish" + block_size = 64 + key_sizes = frozenset(range(32, 449, 8)) + + def __init__(self, key: bytes): + self.key = _verify_key_size(self, key) + + @property + def key_size(self) -> int: + return len(self.key) * 8 + + +_BlowfishInternal = Blowfish +utils.deprecated( + Blowfish, + __name__, + "Blowfish has been deprecated", + utils.DeprecatedIn37, + name="Blowfish", +) + + +class CAST5(BlockCipherAlgorithm): + name = "CAST5" + block_size = 64 + key_sizes = frozenset(range(40, 129, 8)) + + def __init__(self, key: bytes): + self.key = _verify_key_size(self, key) + + @property + def key_size(self) -> int: + return len(self.key) * 8 + + +_CAST5Internal = CAST5 +utils.deprecated( + CAST5, + __name__, + "CAST5 has been deprecated", + utils.DeprecatedIn37, + name="CAST5", +) + + +class ARC4(CipherAlgorithm): + name = "RC4" + key_sizes = frozenset([40, 56, 64, 80, 128, 160, 192, 256]) + + def __init__(self, key: bytes): + self.key = _verify_key_size(self, key) + + @property + def key_size(self) -> int: + return len(self.key) * 8 + + +class IDEA(BlockCipherAlgorithm): + name = "IDEA" + block_size = 64 + key_sizes = frozenset([128]) + + def __init__(self, key: bytes): + self.key = _verify_key_size(self, key) + + @property + def key_size(self) -> int: + return len(self.key) * 8 + + +_IDEAInternal = IDEA +utils.deprecated( + IDEA, + __name__, + "IDEA has been deprecated", + utils.DeprecatedIn37, + name="IDEA", +) + + +class SEED(BlockCipherAlgorithm): + name = "SEED" + block_size = 128 + key_sizes = frozenset([128]) + + def __init__(self, key: bytes): + self.key = _verify_key_size(self, key) + + @property + def key_size(self) -> int: + return len(self.key) * 8 + + +_SEEDInternal = SEED +utils.deprecated( + SEED, + __name__, + "SEED has been deprecated", + utils.DeprecatedIn37, + name="SEED", +) + + +class ChaCha20(CipherAlgorithm): + name = "ChaCha20" + key_sizes = frozenset([256]) + + def __init__(self, key: bytes, nonce: bytes): + self.key = _verify_key_size(self, key) + utils._check_byteslike("nonce", nonce) + + if len(nonce) != 16: + raise ValueError("nonce must be 128-bits (16 bytes)") + + self._nonce = nonce + + @property + def nonce(self) -> bytes: + return self._nonce + + @property + def key_size(self) -> int: + return len(self.key) * 8 + + +class SM4(BlockCipherAlgorithm): + name = "SM4" + block_size = 128 + key_sizes = frozenset([128]) + + def __init__(self, key: bytes): + self.key = _verify_key_size(self, key) + + @property + def key_size(self) -> int: + return len(self.key) * 8 diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/ciphers/base.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/ciphers/base.py new file mode 100644 index 0000000000000000000000000000000000000000..38a2ebbe081e72ee8ed70f9fb01423b220c93c1e --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/ciphers/base.py @@ -0,0 +1,269 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc +import typing + +from cryptography.exceptions import ( + AlreadyFinalized, + AlreadyUpdated, + NotYetFinalized, +) +from cryptography.hazmat.primitives._cipheralgorithm import CipherAlgorithm +from cryptography.hazmat.primitives.ciphers import modes + +if typing.TYPE_CHECKING: + from cryptography.hazmat.backends.openssl.ciphers import ( + _CipherContext as _BackendCipherContext, + ) + + +class CipherContext(metaclass=abc.ABCMeta): + @abc.abstractmethod + def update(self, data: bytes) -> bytes: + """ + Processes the provided bytes through the cipher and returns the results + as bytes. + """ + + @abc.abstractmethod + def update_into(self, data: bytes, buf: bytes) -> int: + """ + Processes the provided bytes and writes the resulting data into the + provided buffer. Returns the number of bytes written. + """ + + @abc.abstractmethod + def finalize(self) -> bytes: + """ + Returns the results of processing the final block as bytes. + """ + + +class AEADCipherContext(CipherContext, metaclass=abc.ABCMeta): + @abc.abstractmethod + def authenticate_additional_data(self, data: bytes) -> None: + """ + Authenticates the provided bytes. + """ + + +class AEADDecryptionContext(AEADCipherContext, metaclass=abc.ABCMeta): + @abc.abstractmethod + def finalize_with_tag(self, tag: bytes) -> bytes: + """ + Returns the results of processing the final block as bytes and allows + delayed passing of the authentication tag. + """ + + +class AEADEncryptionContext(AEADCipherContext, metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def tag(self) -> bytes: + """ + Returns tag bytes. This is only available after encryption is + finalized. + """ + + +Mode = typing.TypeVar( + "Mode", bound=typing.Optional[modes.Mode], covariant=True +) + + +class Cipher(typing.Generic[Mode]): + def __init__( + self, + algorithm: CipherAlgorithm, + mode: Mode, + backend: typing.Any = None, + ) -> None: + if not isinstance(algorithm, CipherAlgorithm): + raise TypeError("Expected interface of CipherAlgorithm.") + + if mode is not None: + # mypy needs this assert to narrow the type from our generic + # type. Maybe it won't some time in the future. + assert isinstance(mode, modes.Mode) + mode.validate_for_algorithm(algorithm) + + self.algorithm = algorithm + self.mode = mode + + @typing.overload + def encryptor( + self: Cipher[modes.ModeWithAuthenticationTag], + ) -> AEADEncryptionContext: + ... + + @typing.overload + def encryptor( + self: _CIPHER_TYPE, + ) -> CipherContext: + ... + + def encryptor(self): + if isinstance(self.mode, modes.ModeWithAuthenticationTag): + if self.mode.tag is not None: + raise ValueError( + "Authentication tag must be None when encrypting." + ) + from cryptography.hazmat.backends.openssl.backend import backend + + ctx = backend.create_symmetric_encryption_ctx( + self.algorithm, self.mode + ) + return self._wrap_ctx(ctx, encrypt=True) + + @typing.overload + def decryptor( + self: Cipher[modes.ModeWithAuthenticationTag], + ) -> AEADDecryptionContext: + ... + + @typing.overload + def decryptor( + self: _CIPHER_TYPE, + ) -> CipherContext: + ... + + def decryptor(self): + from cryptography.hazmat.backends.openssl.backend import backend + + ctx = backend.create_symmetric_decryption_ctx( + self.algorithm, self.mode + ) + return self._wrap_ctx(ctx, encrypt=False) + + def _wrap_ctx( + self, ctx: _BackendCipherContext, encrypt: bool + ) -> typing.Union[ + AEADEncryptionContext, AEADDecryptionContext, CipherContext + ]: + if isinstance(self.mode, modes.ModeWithAuthenticationTag): + if encrypt: + return _AEADEncryptionContext(ctx) + else: + return _AEADDecryptionContext(ctx) + else: + return _CipherContext(ctx) + + +_CIPHER_TYPE = Cipher[ + typing.Union[ + modes.ModeWithNonce, + modes.ModeWithTweak, + None, + modes.ECB, + modes.ModeWithInitializationVector, + ] +] + + +class _CipherContext(CipherContext): + _ctx: typing.Optional[_BackendCipherContext] + + def __init__(self, ctx: _BackendCipherContext) -> None: + self._ctx = ctx + + def update(self, data: bytes) -> bytes: + if self._ctx is None: + raise AlreadyFinalized("Context was already finalized.") + return self._ctx.update(data) + + def update_into(self, data: bytes, buf: bytes) -> int: + if self._ctx is None: + raise AlreadyFinalized("Context was already finalized.") + return self._ctx.update_into(data, buf) + + def finalize(self) -> bytes: + if self._ctx is None: + raise AlreadyFinalized("Context was already finalized.") + data = self._ctx.finalize() + self._ctx = None + return data + + +class _AEADCipherContext(AEADCipherContext): + _ctx: typing.Optional[_BackendCipherContext] + _tag: typing.Optional[bytes] + + def __init__(self, ctx: _BackendCipherContext) -> None: + self._ctx = ctx + self._bytes_processed = 0 + self._aad_bytes_processed = 0 + self._tag = None + self._updated = False + + def _check_limit(self, data_size: int) -> None: + if self._ctx is None: + raise AlreadyFinalized("Context was already finalized.") + self._updated = True + self._bytes_processed += data_size + if self._bytes_processed > self._ctx._mode._MAX_ENCRYPTED_BYTES: + raise ValueError( + "{} has a maximum encrypted byte limit of {}".format( + self._ctx._mode.name, self._ctx._mode._MAX_ENCRYPTED_BYTES + ) + ) + + def update(self, data: bytes) -> bytes: + self._check_limit(len(data)) + # mypy needs this assert even though _check_limit already checked + assert self._ctx is not None + return self._ctx.update(data) + + def update_into(self, data: bytes, buf: bytes) -> int: + self._check_limit(len(data)) + # mypy needs this assert even though _check_limit already checked + assert self._ctx is not None + return self._ctx.update_into(data, buf) + + def finalize(self) -> bytes: + if self._ctx is None: + raise AlreadyFinalized("Context was already finalized.") + data = self._ctx.finalize() + self._tag = self._ctx.tag + self._ctx = None + return data + + def authenticate_additional_data(self, data: bytes) -> None: + if self._ctx is None: + raise AlreadyFinalized("Context was already finalized.") + if self._updated: + raise AlreadyUpdated("Update has been called on this context.") + + self._aad_bytes_processed += len(data) + if self._aad_bytes_processed > self._ctx._mode._MAX_AAD_BYTES: + raise ValueError( + "{} has a maximum AAD byte limit of {}".format( + self._ctx._mode.name, self._ctx._mode._MAX_AAD_BYTES + ) + ) + + self._ctx.authenticate_additional_data(data) + + +class _AEADDecryptionContext(_AEADCipherContext, AEADDecryptionContext): + def finalize_with_tag(self, tag: bytes) -> bytes: + if self._ctx is None: + raise AlreadyFinalized("Context was already finalized.") + data = self._ctx.finalize_with_tag(tag) + self._tag = self._ctx.tag + self._ctx = None + return data + + +class _AEADEncryptionContext(_AEADCipherContext, AEADEncryptionContext): + @property + def tag(self) -> bytes: + if self._ctx is not None: + raise NotYetFinalized( + "You must finalize encryption before " "getting the tag." + ) + assert self._tag is not None + return self._tag diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/ciphers/modes.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/ciphers/modes.py new file mode 100644 index 0000000000000000000000000000000000000000..d8ea1888d67b00603cc1ba5c7ad50f7d2ed0847e --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/ciphers/modes.py @@ -0,0 +1,274 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc +import typing + +from cryptography import utils +from cryptography.exceptions import UnsupportedAlgorithm, _Reasons +from cryptography.hazmat.primitives._cipheralgorithm import ( + BlockCipherAlgorithm, + CipherAlgorithm, +) +from cryptography.hazmat.primitives.ciphers import algorithms + + +class Mode(metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def name(self) -> str: + """ + A string naming this mode (e.g. "ECB", "CBC"). + """ + + @abc.abstractmethod + def validate_for_algorithm(self, algorithm: CipherAlgorithm) -> None: + """ + Checks that all the necessary invariants of this (mode, algorithm) + combination are met. + """ + + +class ModeWithInitializationVector(Mode, metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def initialization_vector(self) -> bytes: + """ + The value of the initialization vector for this mode as bytes. + """ + + +class ModeWithTweak(Mode, metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def tweak(self) -> bytes: + """ + The value of the tweak for this mode as bytes. + """ + + +class ModeWithNonce(Mode, metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def nonce(self) -> bytes: + """ + The value of the nonce for this mode as bytes. + """ + + +class ModeWithAuthenticationTag(Mode, metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def tag(self) -> typing.Optional[bytes]: + """ + The value of the tag supplied to the constructor of this mode. + """ + + +def _check_aes_key_length(self: Mode, algorithm: CipherAlgorithm) -> None: + if algorithm.key_size > 256 and algorithm.name == "AES": + raise ValueError( + "Only 128, 192, and 256 bit keys are allowed for this AES mode" + ) + + +def _check_iv_length( + self: ModeWithInitializationVector, algorithm: BlockCipherAlgorithm +) -> None: + if len(self.initialization_vector) * 8 != algorithm.block_size: + raise ValueError( + "Invalid IV size ({}) for {}.".format( + len(self.initialization_vector), self.name + ) + ) + + +def _check_nonce_length( + nonce: bytes, name: str, algorithm: CipherAlgorithm +) -> None: + if not isinstance(algorithm, BlockCipherAlgorithm): + raise UnsupportedAlgorithm( + f"{name} requires a block cipher algorithm", + _Reasons.UNSUPPORTED_CIPHER, + ) + if len(nonce) * 8 != algorithm.block_size: + raise ValueError(f"Invalid nonce size ({len(nonce)}) for {name}.") + + +def _check_iv_and_key_length( + self: ModeWithInitializationVector, algorithm: CipherAlgorithm +) -> None: + if not isinstance(algorithm, BlockCipherAlgorithm): + raise UnsupportedAlgorithm( + f"{self} requires a block cipher algorithm", + _Reasons.UNSUPPORTED_CIPHER, + ) + _check_aes_key_length(self, algorithm) + _check_iv_length(self, algorithm) + + +class CBC(ModeWithInitializationVector): + name = "CBC" + + def __init__(self, initialization_vector: bytes): + utils._check_byteslike("initialization_vector", initialization_vector) + self._initialization_vector = initialization_vector + + @property + def initialization_vector(self) -> bytes: + return self._initialization_vector + + validate_for_algorithm = _check_iv_and_key_length + + +class XTS(ModeWithTweak): + name = "XTS" + + def __init__(self, tweak: bytes): + utils._check_byteslike("tweak", tweak) + + if len(tweak) != 16: + raise ValueError("tweak must be 128-bits (16 bytes)") + + self._tweak = tweak + + @property + def tweak(self) -> bytes: + return self._tweak + + def validate_for_algorithm(self, algorithm: CipherAlgorithm) -> None: + if isinstance(algorithm, (algorithms.AES128, algorithms.AES256)): + raise TypeError( + "The AES128 and AES256 classes do not support XTS, please use " + "the standard AES class instead." + ) + + if algorithm.key_size not in (256, 512): + raise ValueError( + "The XTS specification requires a 256-bit key for AES-128-XTS" + " and 512-bit key for AES-256-XTS" + ) + + +class ECB(Mode): + name = "ECB" + + validate_for_algorithm = _check_aes_key_length + + +class OFB(ModeWithInitializationVector): + name = "OFB" + + def __init__(self, initialization_vector: bytes): + utils._check_byteslike("initialization_vector", initialization_vector) + self._initialization_vector = initialization_vector + + @property + def initialization_vector(self) -> bytes: + return self._initialization_vector + + validate_for_algorithm = _check_iv_and_key_length + + +class CFB(ModeWithInitializationVector): + name = "CFB" + + def __init__(self, initialization_vector: bytes): + utils._check_byteslike("initialization_vector", initialization_vector) + self._initialization_vector = initialization_vector + + @property + def initialization_vector(self) -> bytes: + return self._initialization_vector + + validate_for_algorithm = _check_iv_and_key_length + + +class CFB8(ModeWithInitializationVector): + name = "CFB8" + + def __init__(self, initialization_vector: bytes): + utils._check_byteslike("initialization_vector", initialization_vector) + self._initialization_vector = initialization_vector + + @property + def initialization_vector(self) -> bytes: + return self._initialization_vector + + validate_for_algorithm = _check_iv_and_key_length + + +class CTR(ModeWithNonce): + name = "CTR" + + def __init__(self, nonce: bytes): + utils._check_byteslike("nonce", nonce) + self._nonce = nonce + + @property + def nonce(self) -> bytes: + return self._nonce + + def validate_for_algorithm(self, algorithm: CipherAlgorithm) -> None: + _check_aes_key_length(self, algorithm) + _check_nonce_length(self.nonce, self.name, algorithm) + + +class GCM(ModeWithInitializationVector, ModeWithAuthenticationTag): + name = "GCM" + _MAX_ENCRYPTED_BYTES = (2**39 - 256) // 8 + _MAX_AAD_BYTES = (2**64) // 8 + + def __init__( + self, + initialization_vector: bytes, + tag: typing.Optional[bytes] = None, + min_tag_length: int = 16, + ): + # OpenSSL 3.0.0 constrains GCM IVs to [64, 1024] bits inclusive + # This is a sane limit anyway so we'll enforce it here. + utils._check_byteslike("initialization_vector", initialization_vector) + if len(initialization_vector) < 8 or len(initialization_vector) > 128: + raise ValueError( + "initialization_vector must be between 8 and 128 bytes (64 " + "and 1024 bits)." + ) + self._initialization_vector = initialization_vector + if tag is not None: + utils._check_bytes("tag", tag) + if min_tag_length < 4: + raise ValueError("min_tag_length must be >= 4") + if len(tag) < min_tag_length: + raise ValueError( + "Authentication tag must be {} bytes or longer.".format( + min_tag_length + ) + ) + self._tag = tag + self._min_tag_length = min_tag_length + + @property + def tag(self) -> typing.Optional[bytes]: + return self._tag + + @property + def initialization_vector(self) -> bytes: + return self._initialization_vector + + def validate_for_algorithm(self, algorithm: CipherAlgorithm) -> None: + _check_aes_key_length(self, algorithm) + if not isinstance(algorithm, BlockCipherAlgorithm): + raise UnsupportedAlgorithm( + "GCM requires a block cipher algorithm", + _Reasons.UNSUPPORTED_CIPHER, + ) + block_size_bytes = algorithm.block_size // 8 + if self._tag is not None and len(self._tag) > block_size_bytes: + raise ValueError( + "Authentication tag cannot be more than {} bytes.".format( + block_size_bytes + ) + ) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/cmac.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/cmac.py new file mode 100644 index 0000000000000000000000000000000000000000..8aa1d791acdd09aefe1391a73dec960428b6892d --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/cmac.py @@ -0,0 +1,65 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import typing + +from cryptography import utils +from cryptography.exceptions import AlreadyFinalized +from cryptography.hazmat.primitives import ciphers + +if typing.TYPE_CHECKING: + from cryptography.hazmat.backends.openssl.cmac import _CMACContext + + +class CMAC: + _ctx: typing.Optional[_CMACContext] + _algorithm: ciphers.BlockCipherAlgorithm + + def __init__( + self, + algorithm: ciphers.BlockCipherAlgorithm, + backend: typing.Any = None, + ctx: typing.Optional[_CMACContext] = None, + ) -> None: + if not isinstance(algorithm, ciphers.BlockCipherAlgorithm): + raise TypeError("Expected instance of BlockCipherAlgorithm.") + self._algorithm = algorithm + + if ctx is None: + from cryptography.hazmat.backends.openssl.backend import ( + backend as ossl, + ) + + self._ctx = ossl.create_cmac_ctx(self._algorithm) + else: + self._ctx = ctx + + def update(self, data: bytes) -> None: + if self._ctx is None: + raise AlreadyFinalized("Context was already finalized.") + + utils._check_bytes("data", data) + self._ctx.update(data) + + def finalize(self) -> bytes: + if self._ctx is None: + raise AlreadyFinalized("Context was already finalized.") + digest = self._ctx.finalize() + self._ctx = None + return digest + + def verify(self, signature: bytes) -> None: + utils._check_bytes("signature", signature) + if self._ctx is None: + raise AlreadyFinalized("Context was already finalized.") + + ctx, self._ctx = self._ctx, None + ctx.verify(signature) + + def copy(self) -> CMAC: + if self._ctx is None: + raise AlreadyFinalized("Context was already finalized.") + return CMAC(self._algorithm, ctx=self._ctx.copy()) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/constant_time.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/constant_time.py new file mode 100644 index 0000000000000000000000000000000000000000..3975c7147eb92b56685423aa1c5810adcf253a23 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/constant_time.py @@ -0,0 +1,14 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import hmac + + +def bytes_eq(a: bytes, b: bytes) -> bool: + if not isinstance(a, bytes) or not isinstance(b, bytes): + raise TypeError("a and b must be bytes.") + + return hmac.compare_digest(a, b) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/hashes.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/hashes.py new file mode 100644 index 0000000000000000000000000000000000000000..b6a7ff140e682d187161985cb74b3bdbab6a28ab --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/hashes.py @@ -0,0 +1,243 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc +import typing + +from cryptography.hazmat.bindings._rust import openssl as rust_openssl + +__all__ = [ + "HashAlgorithm", + "HashContext", + "Hash", + "ExtendableOutputFunction", + "SHA1", + "SHA512_224", + "SHA512_256", + "SHA224", + "SHA256", + "SHA384", + "SHA512", + "SHA3_224", + "SHA3_256", + "SHA3_384", + "SHA3_512", + "SHAKE128", + "SHAKE256", + "MD5", + "BLAKE2b", + "BLAKE2s", + "SM3", +] + + +class HashAlgorithm(metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def name(self) -> str: + """ + A string naming this algorithm (e.g. "sha256", "md5"). + """ + + @property + @abc.abstractmethod + def digest_size(self) -> int: + """ + The size of the resulting digest in bytes. + """ + + @property + @abc.abstractmethod + def block_size(self) -> typing.Optional[int]: + """ + The internal block size of the hash function, or None if the hash + function does not use blocks internally (e.g. SHA3). + """ + + +class HashContext(metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def algorithm(self) -> HashAlgorithm: + """ + A HashAlgorithm that will be used by this context. + """ + + @abc.abstractmethod + def update(self, data: bytes) -> None: + """ + Processes the provided bytes through the hash. + """ + + @abc.abstractmethod + def finalize(self) -> bytes: + """ + Finalizes the hash context and returns the hash digest as bytes. + """ + + @abc.abstractmethod + def copy(self) -> HashContext: + """ + Return a HashContext that is a copy of the current context. + """ + + +Hash = rust_openssl.hashes.Hash +HashContext.register(Hash) + + +class ExtendableOutputFunction(metaclass=abc.ABCMeta): + """ + An interface for extendable output functions. + """ + + +class SHA1(HashAlgorithm): + name = "sha1" + digest_size = 20 + block_size = 64 + + +class SHA512_224(HashAlgorithm): # noqa: N801 + name = "sha512-224" + digest_size = 28 + block_size = 128 + + +class SHA512_256(HashAlgorithm): # noqa: N801 + name = "sha512-256" + digest_size = 32 + block_size = 128 + + +class SHA224(HashAlgorithm): + name = "sha224" + digest_size = 28 + block_size = 64 + + +class SHA256(HashAlgorithm): + name = "sha256" + digest_size = 32 + block_size = 64 + + +class SHA384(HashAlgorithm): + name = "sha384" + digest_size = 48 + block_size = 128 + + +class SHA512(HashAlgorithm): + name = "sha512" + digest_size = 64 + block_size = 128 + + +class SHA3_224(HashAlgorithm): # noqa: N801 + name = "sha3-224" + digest_size = 28 + block_size = None + + +class SHA3_256(HashAlgorithm): # noqa: N801 + name = "sha3-256" + digest_size = 32 + block_size = None + + +class SHA3_384(HashAlgorithm): # noqa: N801 + name = "sha3-384" + digest_size = 48 + block_size = None + + +class SHA3_512(HashAlgorithm): # noqa: N801 + name = "sha3-512" + digest_size = 64 + block_size = None + + +class SHAKE128(HashAlgorithm, ExtendableOutputFunction): + name = "shake128" + block_size = None + + def __init__(self, digest_size: int): + if not isinstance(digest_size, int): + raise TypeError("digest_size must be an integer") + + if digest_size < 1: + raise ValueError("digest_size must be a positive integer") + + self._digest_size = digest_size + + @property + def digest_size(self) -> int: + return self._digest_size + + +class SHAKE256(HashAlgorithm, ExtendableOutputFunction): + name = "shake256" + block_size = None + + def __init__(self, digest_size: int): + if not isinstance(digest_size, int): + raise TypeError("digest_size must be an integer") + + if digest_size < 1: + raise ValueError("digest_size must be a positive integer") + + self._digest_size = digest_size + + @property + def digest_size(self) -> int: + return self._digest_size + + +class MD5(HashAlgorithm): + name = "md5" + digest_size = 16 + block_size = 64 + + +class BLAKE2b(HashAlgorithm): + name = "blake2b" + _max_digest_size = 64 + _min_digest_size = 1 + block_size = 128 + + def __init__(self, digest_size: int): + if digest_size != 64: + raise ValueError("Digest size must be 64") + + self._digest_size = digest_size + + @property + def digest_size(self) -> int: + return self._digest_size + + +class BLAKE2s(HashAlgorithm): + name = "blake2s" + block_size = 64 + _max_digest_size = 32 + _min_digest_size = 1 + + def __init__(self, digest_size: int): + if digest_size != 32: + raise ValueError("Digest size must be 32") + + self._digest_size = digest_size + + @property + def digest_size(self) -> int: + return self._digest_size + + +class SM3(HashAlgorithm): + name = "sm3" + digest_size = 32 + block_size = 64 diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/hmac.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/hmac.py new file mode 100644 index 0000000000000000000000000000000000000000..a9442d59ab474ac680ff7253f2ca0e67d0e93c1a --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/hmac.py @@ -0,0 +1,13 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography.hazmat.bindings._rust import openssl as rust_openssl +from cryptography.hazmat.primitives import hashes + +__all__ = ["HMAC"] + +HMAC = rust_openssl.hmac.HMAC +hashes.HashContext.register(HMAC) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/kdf/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/kdf/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..79bb459f01ec288d67b4f7c20fd5af436fcab4a5 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/kdf/__init__.py @@ -0,0 +1,23 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc + + +class KeyDerivationFunction(metaclass=abc.ABCMeta): + @abc.abstractmethod + def derive(self, key_material: bytes) -> bytes: + """ + Deterministically generates and returns a new key based on the existing + key material. + """ + + @abc.abstractmethod + def verify(self, key_material: bytes, expected_key: bytes) -> None: + """ + Checks whether the key generated by the key material matches the + expected derived key. Raises an exception if they do not match. + """ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..408f2093724fd97e6aa1b00a57453d1078845361 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/concatkdf.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/concatkdf.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..12fc319ba0dc9728d93c28b0e7af8257ffaa3512 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/concatkdf.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/hkdf.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/hkdf.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e541884e72749824cf7198d7c740f4989486ddd3 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/hkdf.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/kbkdf.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/kbkdf.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5758c0e87046bb6e6a8da128a02d348cf92a49d3 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/kbkdf.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/pbkdf2.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/pbkdf2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9db6ed52428e6d2cecfa44180c4d5727c70ba2c0 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/pbkdf2.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/scrypt.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/scrypt.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..70eb063cd49378f227bbcff4bace2b138ed8065b Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/scrypt.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/x963kdf.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/x963kdf.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b2fce189a3e4bc1e9f4d43d0d333524981cf7b66 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/x963kdf.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/kdf/concatkdf.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/kdf/concatkdf.py new file mode 100644 index 0000000000000000000000000000000000000000..d5ea58a94522b2222c6a555b696b74c8e50e4cf1 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/kdf/concatkdf.py @@ -0,0 +1,124 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import typing + +from cryptography import utils +from cryptography.exceptions import AlreadyFinalized, InvalidKey +from cryptography.hazmat.primitives import constant_time, hashes, hmac +from cryptography.hazmat.primitives.kdf import KeyDerivationFunction + + +def _int_to_u32be(n: int) -> bytes: + return n.to_bytes(length=4, byteorder="big") + + +def _common_args_checks( + algorithm: hashes.HashAlgorithm, + length: int, + otherinfo: typing.Optional[bytes], +) -> None: + max_length = algorithm.digest_size * (2**32 - 1) + if length > max_length: + raise ValueError(f"Cannot derive keys larger than {max_length} bits.") + if otherinfo is not None: + utils._check_bytes("otherinfo", otherinfo) + + +def _concatkdf_derive( + key_material: bytes, + length: int, + auxfn: typing.Callable[[], hashes.HashContext], + otherinfo: bytes, +) -> bytes: + utils._check_byteslike("key_material", key_material) + output = [b""] + outlen = 0 + counter = 1 + + while length > outlen: + h = auxfn() + h.update(_int_to_u32be(counter)) + h.update(key_material) + h.update(otherinfo) + output.append(h.finalize()) + outlen += len(output[-1]) + counter += 1 + + return b"".join(output)[:length] + + +class ConcatKDFHash(KeyDerivationFunction): + def __init__( + self, + algorithm: hashes.HashAlgorithm, + length: int, + otherinfo: typing.Optional[bytes], + backend: typing.Any = None, + ): + _common_args_checks(algorithm, length, otherinfo) + self._algorithm = algorithm + self._length = length + self._otherinfo: bytes = otherinfo if otherinfo is not None else b"" + + self._used = False + + def _hash(self) -> hashes.Hash: + return hashes.Hash(self._algorithm) + + def derive(self, key_material: bytes) -> bytes: + if self._used: + raise AlreadyFinalized + self._used = True + return _concatkdf_derive( + key_material, self._length, self._hash, self._otherinfo + ) + + def verify(self, key_material: bytes, expected_key: bytes) -> None: + if not constant_time.bytes_eq(self.derive(key_material), expected_key): + raise InvalidKey + + +class ConcatKDFHMAC(KeyDerivationFunction): + def __init__( + self, + algorithm: hashes.HashAlgorithm, + length: int, + salt: typing.Optional[bytes], + otherinfo: typing.Optional[bytes], + backend: typing.Any = None, + ): + _common_args_checks(algorithm, length, otherinfo) + self._algorithm = algorithm + self._length = length + self._otherinfo: bytes = otherinfo if otherinfo is not None else b"" + + if algorithm.block_size is None: + raise TypeError(f"{algorithm.name} is unsupported for ConcatKDF") + + if salt is None: + salt = b"\x00" * algorithm.block_size + else: + utils._check_bytes("salt", salt) + + self._salt = salt + + self._used = False + + def _hmac(self) -> hmac.HMAC: + return hmac.HMAC(self._salt, self._algorithm) + + def derive(self, key_material: bytes) -> bytes: + if self._used: + raise AlreadyFinalized + self._used = True + return _concatkdf_derive( + key_material, self._length, self._hmac, self._otherinfo + ) + + def verify(self, key_material: bytes, expected_key: bytes) -> None: + if not constant_time.bytes_eq(self.derive(key_material), expected_key): + raise InvalidKey diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/kdf/hkdf.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/kdf/hkdf.py new file mode 100644 index 0000000000000000000000000000000000000000..d4768944363174e6aa0949b3fbb64eede3313a6f --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/kdf/hkdf.py @@ -0,0 +1,101 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import typing + +from cryptography import utils +from cryptography.exceptions import AlreadyFinalized, InvalidKey +from cryptography.hazmat.primitives import constant_time, hashes, hmac +from cryptography.hazmat.primitives.kdf import KeyDerivationFunction + + +class HKDF(KeyDerivationFunction): + def __init__( + self, + algorithm: hashes.HashAlgorithm, + length: int, + salt: typing.Optional[bytes], + info: typing.Optional[bytes], + backend: typing.Any = None, + ): + self._algorithm = algorithm + + if salt is None: + salt = b"\x00" * self._algorithm.digest_size + else: + utils._check_bytes("salt", salt) + + self._salt = salt + + self._hkdf_expand = HKDFExpand(self._algorithm, length, info) + + def _extract(self, key_material: bytes) -> bytes: + h = hmac.HMAC(self._salt, self._algorithm) + h.update(key_material) + return h.finalize() + + def derive(self, key_material: bytes) -> bytes: + utils._check_byteslike("key_material", key_material) + return self._hkdf_expand.derive(self._extract(key_material)) + + def verify(self, key_material: bytes, expected_key: bytes) -> None: + if not constant_time.bytes_eq(self.derive(key_material), expected_key): + raise InvalidKey + + +class HKDFExpand(KeyDerivationFunction): + def __init__( + self, + algorithm: hashes.HashAlgorithm, + length: int, + info: typing.Optional[bytes], + backend: typing.Any = None, + ): + self._algorithm = algorithm + + max_length = 255 * algorithm.digest_size + + if length > max_length: + raise ValueError( + f"Cannot derive keys larger than {max_length} octets." + ) + + self._length = length + + if info is None: + info = b"" + else: + utils._check_bytes("info", info) + + self._info = info + + self._used = False + + def _expand(self, key_material: bytes) -> bytes: + output = [b""] + counter = 1 + + while self._algorithm.digest_size * (len(output) - 1) < self._length: + h = hmac.HMAC(key_material, self._algorithm) + h.update(output[-1]) + h.update(self._info) + h.update(bytes([counter])) + output.append(h.finalize()) + counter += 1 + + return b"".join(output)[: self._length] + + def derive(self, key_material: bytes) -> bytes: + utils._check_byteslike("key_material", key_material) + if self._used: + raise AlreadyFinalized + + self._used = True + return self._expand(key_material) + + def verify(self, key_material: bytes, expected_key: bytes) -> None: + if not constant_time.bytes_eq(self.derive(key_material), expected_key): + raise InvalidKey diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/kdf/kbkdf.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/kdf/kbkdf.py new file mode 100644 index 0000000000000000000000000000000000000000..967763828f3f35ff9a39629f94e89dafdfc734f9 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/kdf/kbkdf.py @@ -0,0 +1,299 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import typing + +from cryptography import utils +from cryptography.exceptions import ( + AlreadyFinalized, + InvalidKey, + UnsupportedAlgorithm, + _Reasons, +) +from cryptography.hazmat.primitives import ( + ciphers, + cmac, + constant_time, + hashes, + hmac, +) +from cryptography.hazmat.primitives.kdf import KeyDerivationFunction + + +class Mode(utils.Enum): + CounterMode = "ctr" + + +class CounterLocation(utils.Enum): + BeforeFixed = "before_fixed" + AfterFixed = "after_fixed" + MiddleFixed = "middle_fixed" + + +class _KBKDFDeriver: + def __init__( + self, + prf: typing.Callable, + mode: Mode, + length: int, + rlen: int, + llen: typing.Optional[int], + location: CounterLocation, + break_location: typing.Optional[int], + label: typing.Optional[bytes], + context: typing.Optional[bytes], + fixed: typing.Optional[bytes], + ): + assert callable(prf) + + if not isinstance(mode, Mode): + raise TypeError("mode must be of type Mode") + + if not isinstance(location, CounterLocation): + raise TypeError("location must be of type CounterLocation") + + if break_location is None and location is CounterLocation.MiddleFixed: + raise ValueError("Please specify a break_location") + + if ( + break_location is not None + and location != CounterLocation.MiddleFixed + ): + raise ValueError( + "break_location is ignored when location is not" + " CounterLocation.MiddleFixed" + ) + + if break_location is not None and not isinstance(break_location, int): + raise TypeError("break_location must be an integer") + + if break_location is not None and break_location < 0: + raise ValueError("break_location must be a positive integer") + + if (label or context) and fixed: + raise ValueError( + "When supplying fixed data, " "label and context are ignored." + ) + + if rlen is None or not self._valid_byte_length(rlen): + raise ValueError("rlen must be between 1 and 4") + + if llen is None and fixed is None: + raise ValueError("Please specify an llen") + + if llen is not None and not isinstance(llen, int): + raise TypeError("llen must be an integer") + + if label is None: + label = b"" + + if context is None: + context = b"" + + utils._check_bytes("label", label) + utils._check_bytes("context", context) + self._prf = prf + self._mode = mode + self._length = length + self._rlen = rlen + self._llen = llen + self._location = location + self._break_location = break_location + self._label = label + self._context = context + self._used = False + self._fixed_data = fixed + + @staticmethod + def _valid_byte_length(value: int) -> bool: + if not isinstance(value, int): + raise TypeError("value must be of type int") + + value_bin = utils.int_to_bytes(1, value) + if not 1 <= len(value_bin) <= 4: + return False + return True + + def derive(self, key_material: bytes, prf_output_size: int) -> bytes: + if self._used: + raise AlreadyFinalized + + utils._check_byteslike("key_material", key_material) + self._used = True + + # inverse floor division (equivalent to ceiling) + rounds = -(-self._length // prf_output_size) + + output = [b""] + + # For counter mode, the number of iterations shall not be + # larger than 2^r-1, where r <= 32 is the binary length of the counter + # This ensures that the counter values used as an input to the + # PRF will not repeat during a particular call to the KDF function. + r_bin = utils.int_to_bytes(1, self._rlen) + if rounds > pow(2, len(r_bin) * 8) - 1: + raise ValueError("There are too many iterations.") + + fixed = self._generate_fixed_input() + + if self._location == CounterLocation.BeforeFixed: + data_before_ctr = b"" + data_after_ctr = fixed + elif self._location == CounterLocation.AfterFixed: + data_before_ctr = fixed + data_after_ctr = b"" + else: + if isinstance( + self._break_location, int + ) and self._break_location > len(fixed): + raise ValueError("break_location offset > len(fixed)") + data_before_ctr = fixed[: self._break_location] + data_after_ctr = fixed[self._break_location :] + + for i in range(1, rounds + 1): + h = self._prf(key_material) + + counter = utils.int_to_bytes(i, self._rlen) + input_data = data_before_ctr + counter + data_after_ctr + + h.update(input_data) + + output.append(h.finalize()) + + return b"".join(output)[: self._length] + + def _generate_fixed_input(self) -> bytes: + if self._fixed_data and isinstance(self._fixed_data, bytes): + return self._fixed_data + + l_val = utils.int_to_bytes(self._length * 8, self._llen) + + return b"".join([self._label, b"\x00", self._context, l_val]) + + +class KBKDFHMAC(KeyDerivationFunction): + def __init__( + self, + algorithm: hashes.HashAlgorithm, + mode: Mode, + length: int, + rlen: int, + llen: typing.Optional[int], + location: CounterLocation, + label: typing.Optional[bytes], + context: typing.Optional[bytes], + fixed: typing.Optional[bytes], + backend: typing.Any = None, + *, + break_location: typing.Optional[int] = None, + ): + if not isinstance(algorithm, hashes.HashAlgorithm): + raise UnsupportedAlgorithm( + "Algorithm supplied is not a supported hash algorithm.", + _Reasons.UNSUPPORTED_HASH, + ) + + from cryptography.hazmat.backends.openssl.backend import ( + backend as ossl, + ) + + if not ossl.hmac_supported(algorithm): + raise UnsupportedAlgorithm( + "Algorithm supplied is not a supported hmac algorithm.", + _Reasons.UNSUPPORTED_HASH, + ) + + self._algorithm = algorithm + + self._deriver = _KBKDFDeriver( + self._prf, + mode, + length, + rlen, + llen, + location, + break_location, + label, + context, + fixed, + ) + + def _prf(self, key_material: bytes) -> hmac.HMAC: + return hmac.HMAC(key_material, self._algorithm) + + def derive(self, key_material: bytes) -> bytes: + return self._deriver.derive(key_material, self._algorithm.digest_size) + + def verify(self, key_material: bytes, expected_key: bytes) -> None: + if not constant_time.bytes_eq(self.derive(key_material), expected_key): + raise InvalidKey + + +class KBKDFCMAC(KeyDerivationFunction): + def __init__( + self, + algorithm, + mode: Mode, + length: int, + rlen: int, + llen: typing.Optional[int], + location: CounterLocation, + label: typing.Optional[bytes], + context: typing.Optional[bytes], + fixed: typing.Optional[bytes], + backend: typing.Any = None, + *, + break_location: typing.Optional[int] = None, + ): + if not issubclass( + algorithm, ciphers.BlockCipherAlgorithm + ) or not issubclass(algorithm, ciphers.CipherAlgorithm): + raise UnsupportedAlgorithm( + "Algorithm supplied is not a supported cipher algorithm.", + _Reasons.UNSUPPORTED_CIPHER, + ) + + self._algorithm = algorithm + self._cipher: typing.Optional[ciphers.BlockCipherAlgorithm] = None + + self._deriver = _KBKDFDeriver( + self._prf, + mode, + length, + rlen, + llen, + location, + break_location, + label, + context, + fixed, + ) + + def _prf(self, _: bytes) -> cmac.CMAC: + assert self._cipher is not None + + return cmac.CMAC(self._cipher) + + def derive(self, key_material: bytes) -> bytes: + self._cipher = self._algorithm(key_material) + + assert self._cipher is not None + + from cryptography.hazmat.backends.openssl.backend import ( + backend as ossl, + ) + + if not ossl.cmac_algorithm_supported(self._cipher): + raise UnsupportedAlgorithm( + "Algorithm supplied is not a supported cipher algorithm.", + _Reasons.UNSUPPORTED_CIPHER, + ) + + return self._deriver.derive(key_material, self._cipher.block_size // 8) + + def verify(self, key_material: bytes, expected_key: bytes) -> None: + if not constant_time.bytes_eq(self.derive(key_material), expected_key): + raise InvalidKey diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/kdf/pbkdf2.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/kdf/pbkdf2.py new file mode 100644 index 0000000000000000000000000000000000000000..623e1ca7f9eb6a2dfd6c397e9f051314669b997b --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/kdf/pbkdf2.py @@ -0,0 +1,64 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import typing + +from cryptography import utils +from cryptography.exceptions import ( + AlreadyFinalized, + InvalidKey, + UnsupportedAlgorithm, + _Reasons, +) +from cryptography.hazmat.bindings._rust import openssl as rust_openssl +from cryptography.hazmat.primitives import constant_time, hashes +from cryptography.hazmat.primitives.kdf import KeyDerivationFunction + + +class PBKDF2HMAC(KeyDerivationFunction): + def __init__( + self, + algorithm: hashes.HashAlgorithm, + length: int, + salt: bytes, + iterations: int, + backend: typing.Any = None, + ): + from cryptography.hazmat.backends.openssl.backend import ( + backend as ossl, + ) + + if not ossl.pbkdf2_hmac_supported(algorithm): + raise UnsupportedAlgorithm( + "{} is not supported for PBKDF2 by this backend.".format( + algorithm.name + ), + _Reasons.UNSUPPORTED_HASH, + ) + self._used = False + self._algorithm = algorithm + self._length = length + utils._check_bytes("salt", salt) + self._salt = salt + self._iterations = iterations + + def derive(self, key_material: bytes) -> bytes: + if self._used: + raise AlreadyFinalized("PBKDF2 instances can only be used once.") + self._used = True + + return rust_openssl.kdf.derive_pbkdf2_hmac( + key_material, + self._algorithm, + self._salt, + self._iterations, + self._length, + ) + + def verify(self, key_material: bytes, expected_key: bytes) -> None: + derived_key = self.derive(key_material) + if not constant_time.bytes_eq(derived_key, expected_key): + raise InvalidKey("Keys do not match.") diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/kdf/scrypt.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/kdf/scrypt.py new file mode 100644 index 0000000000000000000000000000000000000000..05a4f675b6ababd6701cd96850fdf89a28f9d2fd --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/kdf/scrypt.py @@ -0,0 +1,80 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import sys +import typing + +from cryptography import utils +from cryptography.exceptions import ( + AlreadyFinalized, + InvalidKey, + UnsupportedAlgorithm, +) +from cryptography.hazmat.bindings._rust import openssl as rust_openssl +from cryptography.hazmat.primitives import constant_time +from cryptography.hazmat.primitives.kdf import KeyDerivationFunction + +# This is used by the scrypt tests to skip tests that require more memory +# than the MEM_LIMIT +_MEM_LIMIT = sys.maxsize // 2 + + +class Scrypt(KeyDerivationFunction): + def __init__( + self, + salt: bytes, + length: int, + n: int, + r: int, + p: int, + backend: typing.Any = None, + ): + from cryptography.hazmat.backends.openssl.backend import ( + backend as ossl, + ) + + if not ossl.scrypt_supported(): + raise UnsupportedAlgorithm( + "This version of OpenSSL does not support scrypt" + ) + self._length = length + utils._check_bytes("salt", salt) + if n < 2 or (n & (n - 1)) != 0: + raise ValueError("n must be greater than 1 and be a power of 2.") + + if r < 1: + raise ValueError("r must be greater than or equal to 1.") + + if p < 1: + raise ValueError("p must be greater than or equal to 1.") + + self._used = False + self._salt = salt + self._n = n + self._r = r + self._p = p + + def derive(self, key_material: bytes) -> bytes: + if self._used: + raise AlreadyFinalized("Scrypt instances can only be used once.") + self._used = True + + utils._check_byteslike("key_material", key_material) + + return rust_openssl.kdf.derive_scrypt( + key_material, + self._salt, + self._n, + self._r, + self._p, + _MEM_LIMIT, + self._length, + ) + + def verify(self, key_material: bytes, expected_key: bytes) -> None: + derived_key = self.derive(key_material) + if not constant_time.bytes_eq(derived_key, expected_key): + raise InvalidKey("Keys do not match.") diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/kdf/x963kdf.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/kdf/x963kdf.py new file mode 100644 index 0000000000000000000000000000000000000000..17acc5174bb09c6056569f9198e253275dfc40bf --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/kdf/x963kdf.py @@ -0,0 +1,61 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import typing + +from cryptography import utils +from cryptography.exceptions import AlreadyFinalized, InvalidKey +from cryptography.hazmat.primitives import constant_time, hashes +from cryptography.hazmat.primitives.kdf import KeyDerivationFunction + + +def _int_to_u32be(n: int) -> bytes: + return n.to_bytes(length=4, byteorder="big") + + +class X963KDF(KeyDerivationFunction): + def __init__( + self, + algorithm: hashes.HashAlgorithm, + length: int, + sharedinfo: typing.Optional[bytes], + backend: typing.Any = None, + ): + max_len = algorithm.digest_size * (2**32 - 1) + if length > max_len: + raise ValueError(f"Cannot derive keys larger than {max_len} bits.") + if sharedinfo is not None: + utils._check_bytes("sharedinfo", sharedinfo) + + self._algorithm = algorithm + self._length = length + self._sharedinfo = sharedinfo + self._used = False + + def derive(self, key_material: bytes) -> bytes: + if self._used: + raise AlreadyFinalized + self._used = True + utils._check_byteslike("key_material", key_material) + output = [b""] + outlen = 0 + counter = 1 + + while self._length > outlen: + h = hashes.Hash(self._algorithm) + h.update(key_material) + h.update(_int_to_u32be(counter)) + if self._sharedinfo is not None: + h.update(self._sharedinfo) + output.append(h.finalize()) + outlen += len(output[-1]) + counter += 1 + + return b"".join(output)[: self._length] + + def verify(self, key_material: bytes, expected_key: bytes) -> None: + if not constant_time.bytes_eq(self.derive(key_material), expected_key): + raise InvalidKey diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/keywrap.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/keywrap.py new file mode 100644 index 0000000000000000000000000000000000000000..59b0326c2a86fafad73fa34b893aa2c76c194617 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/keywrap.py @@ -0,0 +1,177 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import typing + +from cryptography.hazmat.primitives.ciphers import Cipher +from cryptography.hazmat.primitives.ciphers.algorithms import AES +from cryptography.hazmat.primitives.ciphers.modes import ECB +from cryptography.hazmat.primitives.constant_time import bytes_eq + + +def _wrap_core( + wrapping_key: bytes, + a: bytes, + r: typing.List[bytes], +) -> bytes: + # RFC 3394 Key Wrap - 2.2.1 (index method) + encryptor = Cipher(AES(wrapping_key), ECB()).encryptor() + n = len(r) + for j in range(6): + for i in range(n): + # every encryption operation is a discrete 16 byte chunk (because + # AES has a 128-bit block size) and since we're using ECB it is + # safe to reuse the encryptor for the entire operation + b = encryptor.update(a + r[i]) + a = ( + int.from_bytes(b[:8], byteorder="big") ^ ((n * j) + i + 1) + ).to_bytes(length=8, byteorder="big") + r[i] = b[-8:] + + assert encryptor.finalize() == b"" + + return a + b"".join(r) + + +def aes_key_wrap( + wrapping_key: bytes, + key_to_wrap: bytes, + backend: typing.Any = None, +) -> bytes: + if len(wrapping_key) not in [16, 24, 32]: + raise ValueError("The wrapping key must be a valid AES key length") + + if len(key_to_wrap) < 16: + raise ValueError("The key to wrap must be at least 16 bytes") + + if len(key_to_wrap) % 8 != 0: + raise ValueError("The key to wrap must be a multiple of 8 bytes") + + a = b"\xa6\xa6\xa6\xa6\xa6\xa6\xa6\xa6" + r = [key_to_wrap[i : i + 8] for i in range(0, len(key_to_wrap), 8)] + return _wrap_core(wrapping_key, a, r) + + +def _unwrap_core( + wrapping_key: bytes, + a: bytes, + r: typing.List[bytes], +) -> typing.Tuple[bytes, typing.List[bytes]]: + # Implement RFC 3394 Key Unwrap - 2.2.2 (index method) + decryptor = Cipher(AES(wrapping_key), ECB()).decryptor() + n = len(r) + for j in reversed(range(6)): + for i in reversed(range(n)): + atr = ( + int.from_bytes(a, byteorder="big") ^ ((n * j) + i + 1) + ).to_bytes(length=8, byteorder="big") + r[i] + # every decryption operation is a discrete 16 byte chunk so + # it is safe to reuse the decryptor for the entire operation + b = decryptor.update(atr) + a = b[:8] + r[i] = b[-8:] + + assert decryptor.finalize() == b"" + return a, r + + +def aes_key_wrap_with_padding( + wrapping_key: bytes, + key_to_wrap: bytes, + backend: typing.Any = None, +) -> bytes: + if len(wrapping_key) not in [16, 24, 32]: + raise ValueError("The wrapping key must be a valid AES key length") + + aiv = b"\xA6\x59\x59\xA6" + len(key_to_wrap).to_bytes( + length=4, byteorder="big" + ) + # pad the key to wrap if necessary + pad = (8 - (len(key_to_wrap) % 8)) % 8 + key_to_wrap = key_to_wrap + b"\x00" * pad + if len(key_to_wrap) == 8: + # RFC 5649 - 4.1 - exactly 8 octets after padding + encryptor = Cipher(AES(wrapping_key), ECB()).encryptor() + b = encryptor.update(aiv + key_to_wrap) + assert encryptor.finalize() == b"" + return b + else: + r = [key_to_wrap[i : i + 8] for i in range(0, len(key_to_wrap), 8)] + return _wrap_core(wrapping_key, aiv, r) + + +def aes_key_unwrap_with_padding( + wrapping_key: bytes, + wrapped_key: bytes, + backend: typing.Any = None, +) -> bytes: + if len(wrapped_key) < 16: + raise InvalidUnwrap("Must be at least 16 bytes") + + if len(wrapping_key) not in [16, 24, 32]: + raise ValueError("The wrapping key must be a valid AES key length") + + if len(wrapped_key) == 16: + # RFC 5649 - 4.2 - exactly two 64-bit blocks + decryptor = Cipher(AES(wrapping_key), ECB()).decryptor() + out = decryptor.update(wrapped_key) + assert decryptor.finalize() == b"" + a = out[:8] + data = out[8:] + n = 1 + else: + r = [wrapped_key[i : i + 8] for i in range(0, len(wrapped_key), 8)] + encrypted_aiv = r.pop(0) + n = len(r) + a, r = _unwrap_core(wrapping_key, encrypted_aiv, r) + data = b"".join(r) + + # 1) Check that MSB(32,A) = A65959A6. + # 2) Check that 8*(n-1) < LSB(32,A) <= 8*n. If so, let + # MLI = LSB(32,A). + # 3) Let b = (8*n)-MLI, and then check that the rightmost b octets of + # the output data are zero. + mli = int.from_bytes(a[4:], byteorder="big") + b = (8 * n) - mli + if ( + not bytes_eq(a[:4], b"\xa6\x59\x59\xa6") + or not 8 * (n - 1) < mli <= 8 * n + or (b != 0 and not bytes_eq(data[-b:], b"\x00" * b)) + ): + raise InvalidUnwrap() + + if b == 0: + return data + else: + return data[:-b] + + +def aes_key_unwrap( + wrapping_key: bytes, + wrapped_key: bytes, + backend: typing.Any = None, +) -> bytes: + if len(wrapped_key) < 24: + raise InvalidUnwrap("Must be at least 24 bytes") + + if len(wrapped_key) % 8 != 0: + raise InvalidUnwrap("The wrapped key must be a multiple of 8 bytes") + + if len(wrapping_key) not in [16, 24, 32]: + raise ValueError("The wrapping key must be a valid AES key length") + + aiv = b"\xa6\xa6\xa6\xa6\xa6\xa6\xa6\xa6" + r = [wrapped_key[i : i + 8] for i in range(0, len(wrapped_key), 8)] + a = r.pop(0) + a, r = _unwrap_core(wrapping_key, a, r) + if not bytes_eq(a, aiv): + raise InvalidUnwrap() + + return b"".join(r) + + +class InvalidUnwrap(Exception): + pass diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/padding.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/padding.py new file mode 100644 index 0000000000000000000000000000000000000000..fde3094b00ae4f118d81a2b15c18acb80702cdba --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/padding.py @@ -0,0 +1,225 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc +import typing + +from cryptography import utils +from cryptography.exceptions import AlreadyFinalized +from cryptography.hazmat.bindings._rust import ( + check_ansix923_padding, + check_pkcs7_padding, +) + + +class PaddingContext(metaclass=abc.ABCMeta): + @abc.abstractmethod + def update(self, data: bytes) -> bytes: + """ + Pads the provided bytes and returns any available data as bytes. + """ + + @abc.abstractmethod + def finalize(self) -> bytes: + """ + Finalize the padding, returns bytes. + """ + + +def _byte_padding_check(block_size: int) -> None: + if not (0 <= block_size <= 2040): + raise ValueError("block_size must be in range(0, 2041).") + + if block_size % 8 != 0: + raise ValueError("block_size must be a multiple of 8.") + + +def _byte_padding_update( + buffer_: typing.Optional[bytes], data: bytes, block_size: int +) -> typing.Tuple[bytes, bytes]: + if buffer_ is None: + raise AlreadyFinalized("Context was already finalized.") + + utils._check_byteslike("data", data) + + buffer_ += bytes(data) + + finished_blocks = len(buffer_) // (block_size // 8) + + result = buffer_[: finished_blocks * (block_size // 8)] + buffer_ = buffer_[finished_blocks * (block_size // 8) :] + + return buffer_, result + + +def _byte_padding_pad( + buffer_: typing.Optional[bytes], + block_size: int, + paddingfn: typing.Callable[[int], bytes], +) -> bytes: + if buffer_ is None: + raise AlreadyFinalized("Context was already finalized.") + + pad_size = block_size // 8 - len(buffer_) + return buffer_ + paddingfn(pad_size) + + +def _byte_unpadding_update( + buffer_: typing.Optional[bytes], data: bytes, block_size: int +) -> typing.Tuple[bytes, bytes]: + if buffer_ is None: + raise AlreadyFinalized("Context was already finalized.") + + utils._check_byteslike("data", data) + + buffer_ += bytes(data) + + finished_blocks = max(len(buffer_) // (block_size // 8) - 1, 0) + + result = buffer_[: finished_blocks * (block_size // 8)] + buffer_ = buffer_[finished_blocks * (block_size // 8) :] + + return buffer_, result + + +def _byte_unpadding_check( + buffer_: typing.Optional[bytes], + block_size: int, + checkfn: typing.Callable[[bytes], int], +) -> bytes: + if buffer_ is None: + raise AlreadyFinalized("Context was already finalized.") + + if len(buffer_) != block_size // 8: + raise ValueError("Invalid padding bytes.") + + valid = checkfn(buffer_) + + if not valid: + raise ValueError("Invalid padding bytes.") + + pad_size = buffer_[-1] + return buffer_[:-pad_size] + + +class PKCS7: + def __init__(self, block_size: int): + _byte_padding_check(block_size) + self.block_size = block_size + + def padder(self) -> PaddingContext: + return _PKCS7PaddingContext(self.block_size) + + def unpadder(self) -> PaddingContext: + return _PKCS7UnpaddingContext(self.block_size) + + +class _PKCS7PaddingContext(PaddingContext): + _buffer: typing.Optional[bytes] + + def __init__(self, block_size: int): + self.block_size = block_size + # TODO: more copies than necessary, we should use zero-buffer (#193) + self._buffer = b"" + + def update(self, data: bytes) -> bytes: + self._buffer, result = _byte_padding_update( + self._buffer, data, self.block_size + ) + return result + + def _padding(self, size: int) -> bytes: + return bytes([size]) * size + + def finalize(self) -> bytes: + result = _byte_padding_pad( + self._buffer, self.block_size, self._padding + ) + self._buffer = None + return result + + +class _PKCS7UnpaddingContext(PaddingContext): + _buffer: typing.Optional[bytes] + + def __init__(self, block_size: int): + self.block_size = block_size + # TODO: more copies than necessary, we should use zero-buffer (#193) + self._buffer = b"" + + def update(self, data: bytes) -> bytes: + self._buffer, result = _byte_unpadding_update( + self._buffer, data, self.block_size + ) + return result + + def finalize(self) -> bytes: + result = _byte_unpadding_check( + self._buffer, self.block_size, check_pkcs7_padding + ) + self._buffer = None + return result + + +class ANSIX923: + def __init__(self, block_size: int): + _byte_padding_check(block_size) + self.block_size = block_size + + def padder(self) -> PaddingContext: + return _ANSIX923PaddingContext(self.block_size) + + def unpadder(self) -> PaddingContext: + return _ANSIX923UnpaddingContext(self.block_size) + + +class _ANSIX923PaddingContext(PaddingContext): + _buffer: typing.Optional[bytes] + + def __init__(self, block_size: int): + self.block_size = block_size + # TODO: more copies than necessary, we should use zero-buffer (#193) + self._buffer = b"" + + def update(self, data: bytes) -> bytes: + self._buffer, result = _byte_padding_update( + self._buffer, data, self.block_size + ) + return result + + def _padding(self, size: int) -> bytes: + return bytes([0]) * (size - 1) + bytes([size]) + + def finalize(self) -> bytes: + result = _byte_padding_pad( + self._buffer, self.block_size, self._padding + ) + self._buffer = None + return result + + +class _ANSIX923UnpaddingContext(PaddingContext): + _buffer: typing.Optional[bytes] + + def __init__(self, block_size: int): + self.block_size = block_size + # TODO: more copies than necessary, we should use zero-buffer (#193) + self._buffer = b"" + + def update(self, data: bytes) -> bytes: + self._buffer, result = _byte_unpadding_update( + self._buffer, data, self.block_size + ) + return result + + def finalize(self) -> bytes: + result = _byte_unpadding_check( + self._buffer, + self.block_size, + check_ansix923_padding, + ) + self._buffer = None + return result diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/poly1305.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/poly1305.py new file mode 100644 index 0000000000000000000000000000000000000000..7f5a77a576fd258a9a634ae3c3365fc3f7d4702a --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/poly1305.py @@ -0,0 +1,11 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography.hazmat.bindings._rust import openssl as rust_openssl + +__all__ = ["Poly1305"] + +Poly1305 = rust_openssl.poly1305.Poly1305 diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/serialization/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/serialization/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b6c9a5cdc5206997f12d2818e6c751a423e187ea --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/serialization/__init__.py @@ -0,0 +1,63 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography.hazmat.primitives._serialization import ( + BestAvailableEncryption, + Encoding, + KeySerializationEncryption, + NoEncryption, + ParameterFormat, + PrivateFormat, + PublicFormat, + _KeySerializationEncryption, +) +from cryptography.hazmat.primitives.serialization.base import ( + load_der_parameters, + load_der_private_key, + load_der_public_key, + load_pem_parameters, + load_pem_private_key, + load_pem_public_key, +) +from cryptography.hazmat.primitives.serialization.ssh import ( + SSHCertificate, + SSHCertificateBuilder, + SSHCertificateType, + SSHCertPrivateKeyTypes, + SSHCertPublicKeyTypes, + SSHPrivateKeyTypes, + SSHPublicKeyTypes, + load_ssh_private_key, + load_ssh_public_identity, + load_ssh_public_key, +) + +__all__ = [ + "load_der_parameters", + "load_der_private_key", + "load_der_public_key", + "load_pem_parameters", + "load_pem_private_key", + "load_pem_public_key", + "load_ssh_private_key", + "load_ssh_public_identity", + "load_ssh_public_key", + "Encoding", + "PrivateFormat", + "PublicFormat", + "ParameterFormat", + "KeySerializationEncryption", + "BestAvailableEncryption", + "NoEncryption", + "_KeySerializationEncryption", + "SSHCertificateBuilder", + "SSHCertificate", + "SSHCertificateType", + "SSHCertPublicKeyTypes", + "SSHCertPrivateKeyTypes", + "SSHPrivateKeyTypes", + "SSHPublicKeyTypes", +] diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/serialization/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/serialization/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..feceb4e0d1f000c9a7a0e4c41fcefad5184d6f09 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/serialization/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/serialization/__pycache__/base.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/serialization/__pycache__/base.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e0635e6e1037eb8f336f0f4ccc29f84c840aec7b Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/serialization/__pycache__/base.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/serialization/__pycache__/pkcs12.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/serialization/__pycache__/pkcs12.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d3ad48714471843bd16864076600bc5b84d05d56 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/serialization/__pycache__/pkcs12.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/serialization/__pycache__/pkcs7.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/serialization/__pycache__/pkcs7.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f16d3ddd66e16a69fbf9aa3a41bdee19cbf6c4e3 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/serialization/__pycache__/pkcs7.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/serialization/__pycache__/ssh.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/serialization/__pycache__/ssh.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c8ddfafc076010f06001294c79f17d0526dd2886 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/serialization/__pycache__/ssh.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/serialization/base.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/serialization/base.py new file mode 100644 index 0000000000000000000000000000000000000000..18a96ccfd5cd8a2fe04c6778bc9ed82f8b0e6e7e --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/serialization/base.py @@ -0,0 +1,73 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import typing + +from cryptography.hazmat.primitives.asymmetric import dh +from cryptography.hazmat.primitives.asymmetric.types import ( + PrivateKeyTypes, + PublicKeyTypes, +) + + +def load_pem_private_key( + data: bytes, + password: typing.Optional[bytes], + backend: typing.Any = None, + *, + unsafe_skip_rsa_key_validation: bool = False, +) -> PrivateKeyTypes: + from cryptography.hazmat.backends.openssl.backend import backend as ossl + + return ossl.load_pem_private_key( + data, password, unsafe_skip_rsa_key_validation + ) + + +def load_pem_public_key( + data: bytes, backend: typing.Any = None +) -> PublicKeyTypes: + from cryptography.hazmat.backends.openssl.backend import backend as ossl + + return ossl.load_pem_public_key(data) + + +def load_pem_parameters( + data: bytes, backend: typing.Any = None +) -> dh.DHParameters: + from cryptography.hazmat.backends.openssl.backend import backend as ossl + + return ossl.load_pem_parameters(data) + + +def load_der_private_key( + data: bytes, + password: typing.Optional[bytes], + backend: typing.Any = None, + *, + unsafe_skip_rsa_key_validation: bool = False, +) -> PrivateKeyTypes: + from cryptography.hazmat.backends.openssl.backend import backend as ossl + + return ossl.load_der_private_key( + data, password, unsafe_skip_rsa_key_validation + ) + + +def load_der_public_key( + data: bytes, backend: typing.Any = None +) -> PublicKeyTypes: + from cryptography.hazmat.backends.openssl.backend import backend as ossl + + return ossl.load_der_public_key(data) + + +def load_der_parameters( + data: bytes, backend: typing.Any = None +) -> dh.DHParameters: + from cryptography.hazmat.backends.openssl.backend import backend as ossl + + return ossl.load_der_parameters(data) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/serialization/pkcs12.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/serialization/pkcs12.py new file mode 100644 index 0000000000000000000000000000000000000000..27133a3fa851901070783134f475b5060a5c2eab --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/serialization/pkcs12.py @@ -0,0 +1,229 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import typing + +from cryptography import x509 +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives._serialization import PBES as PBES +from cryptography.hazmat.primitives.asymmetric import ( + dsa, + ec, + ed448, + ed25519, + rsa, +) +from cryptography.hazmat.primitives.asymmetric.types import PrivateKeyTypes + +__all__ = [ + "PBES", + "PKCS12PrivateKeyTypes", + "PKCS12Certificate", + "PKCS12KeyAndCertificates", + "load_key_and_certificates", + "load_pkcs12", + "serialize_key_and_certificates", +] + +PKCS12PrivateKeyTypes = typing.Union[ + rsa.RSAPrivateKey, + dsa.DSAPrivateKey, + ec.EllipticCurvePrivateKey, + ed25519.Ed25519PrivateKey, + ed448.Ed448PrivateKey, +] + + +class PKCS12Certificate: + def __init__( + self, + cert: x509.Certificate, + friendly_name: typing.Optional[bytes], + ): + if not isinstance(cert, x509.Certificate): + raise TypeError("Expecting x509.Certificate object") + if friendly_name is not None and not isinstance(friendly_name, bytes): + raise TypeError("friendly_name must be bytes or None") + self._cert = cert + self._friendly_name = friendly_name + + @property + def friendly_name(self) -> typing.Optional[bytes]: + return self._friendly_name + + @property + def certificate(self) -> x509.Certificate: + return self._cert + + def __eq__(self, other: object) -> bool: + if not isinstance(other, PKCS12Certificate): + return NotImplemented + + return ( + self.certificate == other.certificate + and self.friendly_name == other.friendly_name + ) + + def __hash__(self) -> int: + return hash((self.certificate, self.friendly_name)) + + def __repr__(self) -> str: + return "".format( + self.certificate, self.friendly_name + ) + + +class PKCS12KeyAndCertificates: + def __init__( + self, + key: typing.Optional[PrivateKeyTypes], + cert: typing.Optional[PKCS12Certificate], + additional_certs: typing.List[PKCS12Certificate], + ): + if key is not None and not isinstance( + key, + ( + rsa.RSAPrivateKey, + dsa.DSAPrivateKey, + ec.EllipticCurvePrivateKey, + ed25519.Ed25519PrivateKey, + ed448.Ed448PrivateKey, + ), + ): + raise TypeError( + "Key must be RSA, DSA, EllipticCurve, ED25519, or ED448" + " private key, or None." + ) + if cert is not None and not isinstance(cert, PKCS12Certificate): + raise TypeError("cert must be a PKCS12Certificate object or None") + if not all( + isinstance(add_cert, PKCS12Certificate) + for add_cert in additional_certs + ): + raise TypeError( + "all values in additional_certs must be PKCS12Certificate" + " objects" + ) + self._key = key + self._cert = cert + self._additional_certs = additional_certs + + @property + def key(self) -> typing.Optional[PrivateKeyTypes]: + return self._key + + @property + def cert(self) -> typing.Optional[PKCS12Certificate]: + return self._cert + + @property + def additional_certs(self) -> typing.List[PKCS12Certificate]: + return self._additional_certs + + def __eq__(self, other: object) -> bool: + if not isinstance(other, PKCS12KeyAndCertificates): + return NotImplemented + + return ( + self.key == other.key + and self.cert == other.cert + and self.additional_certs == other.additional_certs + ) + + def __hash__(self) -> int: + return hash((self.key, self.cert, tuple(self.additional_certs))) + + def __repr__(self) -> str: + fmt = ( + "" + ) + return fmt.format(self.key, self.cert, self.additional_certs) + + +def load_key_and_certificates( + data: bytes, + password: typing.Optional[bytes], + backend: typing.Any = None, +) -> typing.Tuple[ + typing.Optional[PrivateKeyTypes], + typing.Optional[x509.Certificate], + typing.List[x509.Certificate], +]: + from cryptography.hazmat.backends.openssl.backend import backend as ossl + + return ossl.load_key_and_certificates_from_pkcs12(data, password) + + +def load_pkcs12( + data: bytes, + password: typing.Optional[bytes], + backend: typing.Any = None, +) -> PKCS12KeyAndCertificates: + from cryptography.hazmat.backends.openssl.backend import backend as ossl + + return ossl.load_pkcs12(data, password) + + +_PKCS12CATypes = typing.Union[ + x509.Certificate, + PKCS12Certificate, +] + + +def serialize_key_and_certificates( + name: typing.Optional[bytes], + key: typing.Optional[PKCS12PrivateKeyTypes], + cert: typing.Optional[x509.Certificate], + cas: typing.Optional[typing.Iterable[_PKCS12CATypes]], + encryption_algorithm: serialization.KeySerializationEncryption, +) -> bytes: + if key is not None and not isinstance( + key, + ( + rsa.RSAPrivateKey, + dsa.DSAPrivateKey, + ec.EllipticCurvePrivateKey, + ed25519.Ed25519PrivateKey, + ed448.Ed448PrivateKey, + ), + ): + raise TypeError( + "Key must be RSA, DSA, EllipticCurve, ED25519, or ED448" + " private key, or None." + ) + if cert is not None and not isinstance(cert, x509.Certificate): + raise TypeError("cert must be a certificate or None") + + if cas is not None: + cas = list(cas) + if not all( + isinstance( + val, + ( + x509.Certificate, + PKCS12Certificate, + ), + ) + for val in cas + ): + raise TypeError("all values in cas must be certificates") + + if not isinstance( + encryption_algorithm, serialization.KeySerializationEncryption + ): + raise TypeError( + "Key encryption algorithm must be a " + "KeySerializationEncryption instance" + ) + + if key is None and cert is None and not cas: + raise ValueError("You must supply at least one of key, cert, or cas") + + from cryptography.hazmat.backends.openssl.backend import backend + + return backend.serialize_key_and_certificates_to_pkcs12( + name, key, cert, cas, encryption_algorithm + ) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/serialization/pkcs7.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/serialization/pkcs7.py new file mode 100644 index 0000000000000000000000000000000000000000..9998bcaa1131db00cf432f24fb1731b65ae697cd --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/serialization/pkcs7.py @@ -0,0 +1,235 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import email.base64mime +import email.generator +import email.message +import email.policy +import io +import typing + +from cryptography import utils, x509 +from cryptography.hazmat.bindings._rust import pkcs7 as rust_pkcs7 +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import ec, rsa +from cryptography.utils import _check_byteslike + + +def load_pem_pkcs7_certificates(data: bytes) -> typing.List[x509.Certificate]: + from cryptography.hazmat.backends.openssl.backend import backend + + return backend.load_pem_pkcs7_certificates(data) + + +def load_der_pkcs7_certificates(data: bytes) -> typing.List[x509.Certificate]: + from cryptography.hazmat.backends.openssl.backend import backend + + return backend.load_der_pkcs7_certificates(data) + + +def serialize_certificates( + certs: typing.List[x509.Certificate], + encoding: serialization.Encoding, +) -> bytes: + return rust_pkcs7.serialize_certificates(certs, encoding) + + +PKCS7HashTypes = typing.Union[ + hashes.SHA224, + hashes.SHA256, + hashes.SHA384, + hashes.SHA512, +] + +PKCS7PrivateKeyTypes = typing.Union[ + rsa.RSAPrivateKey, ec.EllipticCurvePrivateKey +] + + +class PKCS7Options(utils.Enum): + Text = "Add text/plain MIME type" + Binary = "Don't translate input data into canonical MIME format" + DetachedSignature = "Don't embed data in the PKCS7 structure" + NoCapabilities = "Don't embed SMIME capabilities" + NoAttributes = "Don't embed authenticatedAttributes" + NoCerts = "Don't embed signer certificate" + + +class PKCS7SignatureBuilder: + def __init__( + self, + data: typing.Optional[bytes] = None, + signers: typing.List[ + typing.Tuple[ + x509.Certificate, + PKCS7PrivateKeyTypes, + PKCS7HashTypes, + ] + ] = [], + additional_certs: typing.List[x509.Certificate] = [], + ): + self._data = data + self._signers = signers + self._additional_certs = additional_certs + + def set_data(self, data: bytes) -> PKCS7SignatureBuilder: + _check_byteslike("data", data) + if self._data is not None: + raise ValueError("data may only be set once") + + return PKCS7SignatureBuilder(data, self._signers) + + def add_signer( + self, + certificate: x509.Certificate, + private_key: PKCS7PrivateKeyTypes, + hash_algorithm: PKCS7HashTypes, + ) -> PKCS7SignatureBuilder: + if not isinstance( + hash_algorithm, + ( + hashes.SHA224, + hashes.SHA256, + hashes.SHA384, + hashes.SHA512, + ), + ): + raise TypeError( + "hash_algorithm must be one of hashes.SHA224, " + "SHA256, SHA384, or SHA512" + ) + if not isinstance(certificate, x509.Certificate): + raise TypeError("certificate must be a x509.Certificate") + + if not isinstance( + private_key, (rsa.RSAPrivateKey, ec.EllipticCurvePrivateKey) + ): + raise TypeError("Only RSA & EC keys are supported at this time.") + + return PKCS7SignatureBuilder( + self._data, + self._signers + [(certificate, private_key, hash_algorithm)], + ) + + def add_certificate( + self, certificate: x509.Certificate + ) -> PKCS7SignatureBuilder: + if not isinstance(certificate, x509.Certificate): + raise TypeError("certificate must be a x509.Certificate") + + return PKCS7SignatureBuilder( + self._data, self._signers, self._additional_certs + [certificate] + ) + + def sign( + self, + encoding: serialization.Encoding, + options: typing.Iterable[PKCS7Options], + backend: typing.Any = None, + ) -> bytes: + if len(self._signers) == 0: + raise ValueError("Must have at least one signer") + if self._data is None: + raise ValueError("You must add data to sign") + options = list(options) + if not all(isinstance(x, PKCS7Options) for x in options): + raise ValueError("options must be from the PKCS7Options enum") + if encoding not in ( + serialization.Encoding.PEM, + serialization.Encoding.DER, + serialization.Encoding.SMIME, + ): + raise ValueError( + "Must be PEM, DER, or SMIME from the Encoding enum" + ) + + # Text is a meaningless option unless it is accompanied by + # DetachedSignature + if ( + PKCS7Options.Text in options + and PKCS7Options.DetachedSignature not in options + ): + raise ValueError( + "When passing the Text option you must also pass " + "DetachedSignature" + ) + + if PKCS7Options.Text in options and encoding in ( + serialization.Encoding.DER, + serialization.Encoding.PEM, + ): + raise ValueError( + "The Text option is only available for SMIME serialization" + ) + + # No attributes implies no capabilities so we'll error if you try to + # pass both. + if ( + PKCS7Options.NoAttributes in options + and PKCS7Options.NoCapabilities in options + ): + raise ValueError( + "NoAttributes is a superset of NoCapabilities. Do not pass " + "both values." + ) + + return rust_pkcs7.sign_and_serialize(self, encoding, options) + + +def _smime_encode( + data: bytes, signature: bytes, micalg: str, text_mode: bool +) -> bytes: + # This function works pretty hard to replicate what OpenSSL does + # precisely. For good and for ill. + + m = email.message.Message() + m.add_header("MIME-Version", "1.0") + m.add_header( + "Content-Type", + "multipart/signed", + protocol="application/x-pkcs7-signature", + micalg=micalg, + ) + + m.preamble = "This is an S/MIME signed message\n" + + msg_part = OpenSSLMimePart() + msg_part.set_payload(data) + if text_mode: + msg_part.add_header("Content-Type", "text/plain") + m.attach(msg_part) + + sig_part = email.message.MIMEPart() + sig_part.add_header( + "Content-Type", "application/x-pkcs7-signature", name="smime.p7s" + ) + sig_part.add_header("Content-Transfer-Encoding", "base64") + sig_part.add_header( + "Content-Disposition", "attachment", filename="smime.p7s" + ) + sig_part.set_payload( + email.base64mime.body_encode(signature, maxlinelen=65) + ) + del sig_part["MIME-Version"] + m.attach(sig_part) + + fp = io.BytesIO() + g = email.generator.BytesGenerator( + fp, + maxheaderlen=0, + mangle_from_=False, + policy=m.policy.clone(linesep="\r\n"), + ) + g.flatten(m) + return fp.getvalue() + + +class OpenSSLMimePart(email.message.MIMEPart): + # A MIMEPart subclass that replicates OpenSSL's behavior of not including + # a newline if there are no headers. + def _write_headers(self, generator) -> None: + if list(self.raw_items()): + generator._write_headers(self) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/serialization/ssh.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/serialization/ssh.py new file mode 100644 index 0000000000000000000000000000000000000000..35e53c102875a6ded5298a59afcd04c8386a0794 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/serialization/ssh.py @@ -0,0 +1,1534 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import binascii +import enum +import os +import re +import typing +import warnings +from base64 import encodebytes as _base64_encode +from dataclasses import dataclass + +from cryptography import utils +from cryptography.exceptions import UnsupportedAlgorithm +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives.asymmetric import ( + dsa, + ec, + ed25519, + padding, + rsa, +) +from cryptography.hazmat.primitives.asymmetric import utils as asym_utils +from cryptography.hazmat.primitives.ciphers import ( + AEADDecryptionContext, + Cipher, + algorithms, + modes, +) +from cryptography.hazmat.primitives.serialization import ( + Encoding, + KeySerializationEncryption, + NoEncryption, + PrivateFormat, + PublicFormat, + _KeySerializationEncryption, +) + +try: + from bcrypt import kdf as _bcrypt_kdf + + _bcrypt_supported = True +except ImportError: + _bcrypt_supported = False + + def _bcrypt_kdf( + password: bytes, + salt: bytes, + desired_key_bytes: int, + rounds: int, + ignore_few_rounds: bool = False, + ) -> bytes: + raise UnsupportedAlgorithm("Need bcrypt module") + + +_SSH_ED25519 = b"ssh-ed25519" +_SSH_RSA = b"ssh-rsa" +_SSH_DSA = b"ssh-dss" +_ECDSA_NISTP256 = b"ecdsa-sha2-nistp256" +_ECDSA_NISTP384 = b"ecdsa-sha2-nistp384" +_ECDSA_NISTP521 = b"ecdsa-sha2-nistp521" +_CERT_SUFFIX = b"-cert-v01@openssh.com" + +# These are not key types, only algorithms, so they cannot appear +# as a public key type +_SSH_RSA_SHA256 = b"rsa-sha2-256" +_SSH_RSA_SHA512 = b"rsa-sha2-512" + +_SSH_PUBKEY_RC = re.compile(rb"\A(\S+)[ \t]+(\S+)") +_SK_MAGIC = b"openssh-key-v1\0" +_SK_START = b"-----BEGIN OPENSSH PRIVATE KEY-----" +_SK_END = b"-----END OPENSSH PRIVATE KEY-----" +_BCRYPT = b"bcrypt" +_NONE = b"none" +_DEFAULT_CIPHER = b"aes256-ctr" +_DEFAULT_ROUNDS = 16 + +# re is only way to work on bytes-like data +_PEM_RC = re.compile(_SK_START + b"(.*?)" + _SK_END, re.DOTALL) + +# padding for max blocksize +_PADDING = memoryview(bytearray(range(1, 1 + 16))) + + +@dataclass +class _SSHCipher: + alg: typing.Type[algorithms.AES] + key_len: int + mode: typing.Union[ + typing.Type[modes.CTR], + typing.Type[modes.CBC], + typing.Type[modes.GCM], + ] + block_len: int + iv_len: int + tag_len: typing.Optional[int] + is_aead: bool + + +# ciphers that are actually used in key wrapping +_SSH_CIPHERS: typing.Dict[bytes, _SSHCipher] = { + b"aes256-ctr": _SSHCipher( + alg=algorithms.AES, + key_len=32, + mode=modes.CTR, + block_len=16, + iv_len=16, + tag_len=None, + is_aead=False, + ), + b"aes256-cbc": _SSHCipher( + alg=algorithms.AES, + key_len=32, + mode=modes.CBC, + block_len=16, + iv_len=16, + tag_len=None, + is_aead=False, + ), + b"aes256-gcm@openssh.com": _SSHCipher( + alg=algorithms.AES, + key_len=32, + mode=modes.GCM, + block_len=16, + iv_len=12, + tag_len=16, + is_aead=True, + ), +} + +# map local curve name to key type +_ECDSA_KEY_TYPE = { + "secp256r1": _ECDSA_NISTP256, + "secp384r1": _ECDSA_NISTP384, + "secp521r1": _ECDSA_NISTP521, +} + + +def _get_ssh_key_type( + key: typing.Union[SSHPrivateKeyTypes, SSHPublicKeyTypes] +) -> bytes: + if isinstance(key, ec.EllipticCurvePrivateKey): + key_type = _ecdsa_key_type(key.public_key()) + elif isinstance(key, ec.EllipticCurvePublicKey): + key_type = _ecdsa_key_type(key) + elif isinstance(key, (rsa.RSAPrivateKey, rsa.RSAPublicKey)): + key_type = _SSH_RSA + elif isinstance(key, (dsa.DSAPrivateKey, dsa.DSAPublicKey)): + key_type = _SSH_DSA + elif isinstance( + key, (ed25519.Ed25519PrivateKey, ed25519.Ed25519PublicKey) + ): + key_type = _SSH_ED25519 + else: + raise ValueError("Unsupported key type") + + return key_type + + +def _ecdsa_key_type(public_key: ec.EllipticCurvePublicKey) -> bytes: + """Return SSH key_type and curve_name for private key.""" + curve = public_key.curve + if curve.name not in _ECDSA_KEY_TYPE: + raise ValueError( + f"Unsupported curve for ssh private key: {curve.name!r}" + ) + return _ECDSA_KEY_TYPE[curve.name] + + +def _ssh_pem_encode( + data: bytes, + prefix: bytes = _SK_START + b"\n", + suffix: bytes = _SK_END + b"\n", +) -> bytes: + return b"".join([prefix, _base64_encode(data), suffix]) + + +def _check_block_size(data: bytes, block_len: int) -> None: + """Require data to be full blocks""" + if not data or len(data) % block_len != 0: + raise ValueError("Corrupt data: missing padding") + + +def _check_empty(data: bytes) -> None: + """All data should have been parsed.""" + if data: + raise ValueError("Corrupt data: unparsed data") + + +def _init_cipher( + ciphername: bytes, + password: typing.Optional[bytes], + salt: bytes, + rounds: int, +) -> Cipher[typing.Union[modes.CBC, modes.CTR, modes.GCM]]: + """Generate key + iv and return cipher.""" + if not password: + raise ValueError("Key is password-protected.") + + ciph = _SSH_CIPHERS[ciphername] + seed = _bcrypt_kdf( + password, salt, ciph.key_len + ciph.iv_len, rounds, True + ) + return Cipher( + ciph.alg(seed[: ciph.key_len]), + ciph.mode(seed[ciph.key_len :]), + ) + + +def _get_u32(data: memoryview) -> typing.Tuple[int, memoryview]: + """Uint32""" + if len(data) < 4: + raise ValueError("Invalid data") + return int.from_bytes(data[:4], byteorder="big"), data[4:] + + +def _get_u64(data: memoryview) -> typing.Tuple[int, memoryview]: + """Uint64""" + if len(data) < 8: + raise ValueError("Invalid data") + return int.from_bytes(data[:8], byteorder="big"), data[8:] + + +def _get_sshstr(data: memoryview) -> typing.Tuple[memoryview, memoryview]: + """Bytes with u32 length prefix""" + n, data = _get_u32(data) + if n > len(data): + raise ValueError("Invalid data") + return data[:n], data[n:] + + +def _get_mpint(data: memoryview) -> typing.Tuple[int, memoryview]: + """Big integer.""" + val, data = _get_sshstr(data) + if val and val[0] > 0x7F: + raise ValueError("Invalid data") + return int.from_bytes(val, "big"), data + + +def _to_mpint(val: int) -> bytes: + """Storage format for signed bigint.""" + if val < 0: + raise ValueError("negative mpint not allowed") + if not val: + return b"" + nbytes = (val.bit_length() + 8) // 8 + return utils.int_to_bytes(val, nbytes) + + +class _FragList: + """Build recursive structure without data copy.""" + + flist: typing.List[bytes] + + def __init__( + self, init: typing.Optional[typing.List[bytes]] = None + ) -> None: + self.flist = [] + if init: + self.flist.extend(init) + + def put_raw(self, val: bytes) -> None: + """Add plain bytes""" + self.flist.append(val) + + def put_u32(self, val: int) -> None: + """Big-endian uint32""" + self.flist.append(val.to_bytes(length=4, byteorder="big")) + + def put_u64(self, val: int) -> None: + """Big-endian uint64""" + self.flist.append(val.to_bytes(length=8, byteorder="big")) + + def put_sshstr(self, val: typing.Union[bytes, _FragList]) -> None: + """Bytes prefixed with u32 length""" + if isinstance(val, (bytes, memoryview, bytearray)): + self.put_u32(len(val)) + self.flist.append(val) + else: + self.put_u32(val.size()) + self.flist.extend(val.flist) + + def put_mpint(self, val: int) -> None: + """Big-endian bigint prefixed with u32 length""" + self.put_sshstr(_to_mpint(val)) + + def size(self) -> int: + """Current number of bytes""" + return sum(map(len, self.flist)) + + def render(self, dstbuf: memoryview, pos: int = 0) -> int: + """Write into bytearray""" + for frag in self.flist: + flen = len(frag) + start, pos = pos, pos + flen + dstbuf[start:pos] = frag + return pos + + def tobytes(self) -> bytes: + """Return as bytes""" + buf = memoryview(bytearray(self.size())) + self.render(buf) + return buf.tobytes() + + +class _SSHFormatRSA: + """Format for RSA keys. + + Public: + mpint e, n + Private: + mpint n, e, d, iqmp, p, q + """ + + def get_public(self, data: memoryview): + """RSA public fields""" + e, data = _get_mpint(data) + n, data = _get_mpint(data) + return (e, n), data + + def load_public( + self, data: memoryview + ) -> typing.Tuple[rsa.RSAPublicKey, memoryview]: + """Make RSA public key from data.""" + (e, n), data = self.get_public(data) + public_numbers = rsa.RSAPublicNumbers(e, n) + public_key = public_numbers.public_key() + return public_key, data + + def load_private( + self, data: memoryview, pubfields + ) -> typing.Tuple[rsa.RSAPrivateKey, memoryview]: + """Make RSA private key from data.""" + n, data = _get_mpint(data) + e, data = _get_mpint(data) + d, data = _get_mpint(data) + iqmp, data = _get_mpint(data) + p, data = _get_mpint(data) + q, data = _get_mpint(data) + + if (e, n) != pubfields: + raise ValueError("Corrupt data: rsa field mismatch") + dmp1 = rsa.rsa_crt_dmp1(d, p) + dmq1 = rsa.rsa_crt_dmq1(d, q) + public_numbers = rsa.RSAPublicNumbers(e, n) + private_numbers = rsa.RSAPrivateNumbers( + p, q, d, dmp1, dmq1, iqmp, public_numbers + ) + private_key = private_numbers.private_key() + return private_key, data + + def encode_public( + self, public_key: rsa.RSAPublicKey, f_pub: _FragList + ) -> None: + """Write RSA public key""" + pubn = public_key.public_numbers() + f_pub.put_mpint(pubn.e) + f_pub.put_mpint(pubn.n) + + def encode_private( + self, private_key: rsa.RSAPrivateKey, f_priv: _FragList + ) -> None: + """Write RSA private key""" + private_numbers = private_key.private_numbers() + public_numbers = private_numbers.public_numbers + + f_priv.put_mpint(public_numbers.n) + f_priv.put_mpint(public_numbers.e) + + f_priv.put_mpint(private_numbers.d) + f_priv.put_mpint(private_numbers.iqmp) + f_priv.put_mpint(private_numbers.p) + f_priv.put_mpint(private_numbers.q) + + +class _SSHFormatDSA: + """Format for DSA keys. + + Public: + mpint p, q, g, y + Private: + mpint p, q, g, y, x + """ + + def get_public( + self, data: memoryview + ) -> typing.Tuple[typing.Tuple, memoryview]: + """DSA public fields""" + p, data = _get_mpint(data) + q, data = _get_mpint(data) + g, data = _get_mpint(data) + y, data = _get_mpint(data) + return (p, q, g, y), data + + def load_public( + self, data: memoryview + ) -> typing.Tuple[dsa.DSAPublicKey, memoryview]: + """Make DSA public key from data.""" + (p, q, g, y), data = self.get_public(data) + parameter_numbers = dsa.DSAParameterNumbers(p, q, g) + public_numbers = dsa.DSAPublicNumbers(y, parameter_numbers) + self._validate(public_numbers) + public_key = public_numbers.public_key() + return public_key, data + + def load_private( + self, data: memoryview, pubfields + ) -> typing.Tuple[dsa.DSAPrivateKey, memoryview]: + """Make DSA private key from data.""" + (p, q, g, y), data = self.get_public(data) + x, data = _get_mpint(data) + + if (p, q, g, y) != pubfields: + raise ValueError("Corrupt data: dsa field mismatch") + parameter_numbers = dsa.DSAParameterNumbers(p, q, g) + public_numbers = dsa.DSAPublicNumbers(y, parameter_numbers) + self._validate(public_numbers) + private_numbers = dsa.DSAPrivateNumbers(x, public_numbers) + private_key = private_numbers.private_key() + return private_key, data + + def encode_public( + self, public_key: dsa.DSAPublicKey, f_pub: _FragList + ) -> None: + """Write DSA public key""" + public_numbers = public_key.public_numbers() + parameter_numbers = public_numbers.parameter_numbers + self._validate(public_numbers) + + f_pub.put_mpint(parameter_numbers.p) + f_pub.put_mpint(parameter_numbers.q) + f_pub.put_mpint(parameter_numbers.g) + f_pub.put_mpint(public_numbers.y) + + def encode_private( + self, private_key: dsa.DSAPrivateKey, f_priv: _FragList + ) -> None: + """Write DSA private key""" + self.encode_public(private_key.public_key(), f_priv) + f_priv.put_mpint(private_key.private_numbers().x) + + def _validate(self, public_numbers: dsa.DSAPublicNumbers) -> None: + parameter_numbers = public_numbers.parameter_numbers + if parameter_numbers.p.bit_length() != 1024: + raise ValueError("SSH supports only 1024 bit DSA keys") + + +class _SSHFormatECDSA: + """Format for ECDSA keys. + + Public: + str curve + bytes point + Private: + str curve + bytes point + mpint secret + """ + + def __init__(self, ssh_curve_name: bytes, curve: ec.EllipticCurve): + self.ssh_curve_name = ssh_curve_name + self.curve = curve + + def get_public( + self, data: memoryview + ) -> typing.Tuple[typing.Tuple, memoryview]: + """ECDSA public fields""" + curve, data = _get_sshstr(data) + point, data = _get_sshstr(data) + if curve != self.ssh_curve_name: + raise ValueError("Curve name mismatch") + if point[0] != 4: + raise NotImplementedError("Need uncompressed point") + return (curve, point), data + + def load_public( + self, data: memoryview + ) -> typing.Tuple[ec.EllipticCurvePublicKey, memoryview]: + """Make ECDSA public key from data.""" + (curve_name, point), data = self.get_public(data) + public_key = ec.EllipticCurvePublicKey.from_encoded_point( + self.curve, point.tobytes() + ) + return public_key, data + + def load_private( + self, data: memoryview, pubfields + ) -> typing.Tuple[ec.EllipticCurvePrivateKey, memoryview]: + """Make ECDSA private key from data.""" + (curve_name, point), data = self.get_public(data) + secret, data = _get_mpint(data) + + if (curve_name, point) != pubfields: + raise ValueError("Corrupt data: ecdsa field mismatch") + private_key = ec.derive_private_key(secret, self.curve) + return private_key, data + + def encode_public( + self, public_key: ec.EllipticCurvePublicKey, f_pub: _FragList + ) -> None: + """Write ECDSA public key""" + point = public_key.public_bytes( + Encoding.X962, PublicFormat.UncompressedPoint + ) + f_pub.put_sshstr(self.ssh_curve_name) + f_pub.put_sshstr(point) + + def encode_private( + self, private_key: ec.EllipticCurvePrivateKey, f_priv: _FragList + ) -> None: + """Write ECDSA private key""" + public_key = private_key.public_key() + private_numbers = private_key.private_numbers() + + self.encode_public(public_key, f_priv) + f_priv.put_mpint(private_numbers.private_value) + + +class _SSHFormatEd25519: + """Format for Ed25519 keys. + + Public: + bytes point + Private: + bytes point + bytes secret_and_point + """ + + def get_public( + self, data: memoryview + ) -> typing.Tuple[typing.Tuple, memoryview]: + """Ed25519 public fields""" + point, data = _get_sshstr(data) + return (point,), data + + def load_public( + self, data: memoryview + ) -> typing.Tuple[ed25519.Ed25519PublicKey, memoryview]: + """Make Ed25519 public key from data.""" + (point,), data = self.get_public(data) + public_key = ed25519.Ed25519PublicKey.from_public_bytes( + point.tobytes() + ) + return public_key, data + + def load_private( + self, data: memoryview, pubfields + ) -> typing.Tuple[ed25519.Ed25519PrivateKey, memoryview]: + """Make Ed25519 private key from data.""" + (point,), data = self.get_public(data) + keypair, data = _get_sshstr(data) + + secret = keypair[:32] + point2 = keypair[32:] + if point != point2 or (point,) != pubfields: + raise ValueError("Corrupt data: ed25519 field mismatch") + private_key = ed25519.Ed25519PrivateKey.from_private_bytes(secret) + return private_key, data + + def encode_public( + self, public_key: ed25519.Ed25519PublicKey, f_pub: _FragList + ) -> None: + """Write Ed25519 public key""" + raw_public_key = public_key.public_bytes( + Encoding.Raw, PublicFormat.Raw + ) + f_pub.put_sshstr(raw_public_key) + + def encode_private( + self, private_key: ed25519.Ed25519PrivateKey, f_priv: _FragList + ) -> None: + """Write Ed25519 private key""" + public_key = private_key.public_key() + raw_private_key = private_key.private_bytes( + Encoding.Raw, PrivateFormat.Raw, NoEncryption() + ) + raw_public_key = public_key.public_bytes( + Encoding.Raw, PublicFormat.Raw + ) + f_keypair = _FragList([raw_private_key, raw_public_key]) + + self.encode_public(public_key, f_priv) + f_priv.put_sshstr(f_keypair) + + +_KEY_FORMATS = { + _SSH_RSA: _SSHFormatRSA(), + _SSH_DSA: _SSHFormatDSA(), + _SSH_ED25519: _SSHFormatEd25519(), + _ECDSA_NISTP256: _SSHFormatECDSA(b"nistp256", ec.SECP256R1()), + _ECDSA_NISTP384: _SSHFormatECDSA(b"nistp384", ec.SECP384R1()), + _ECDSA_NISTP521: _SSHFormatECDSA(b"nistp521", ec.SECP521R1()), +} + + +def _lookup_kformat(key_type: bytes): + """Return valid format or throw error""" + if not isinstance(key_type, bytes): + key_type = memoryview(key_type).tobytes() + if key_type in _KEY_FORMATS: + return _KEY_FORMATS[key_type] + raise UnsupportedAlgorithm(f"Unsupported key type: {key_type!r}") + + +SSHPrivateKeyTypes = typing.Union[ + ec.EllipticCurvePrivateKey, + rsa.RSAPrivateKey, + dsa.DSAPrivateKey, + ed25519.Ed25519PrivateKey, +] + + +def load_ssh_private_key( + data: bytes, + password: typing.Optional[bytes], + backend: typing.Any = None, +) -> SSHPrivateKeyTypes: + """Load private key from OpenSSH custom encoding.""" + utils._check_byteslike("data", data) + if password is not None: + utils._check_bytes("password", password) + + m = _PEM_RC.search(data) + if not m: + raise ValueError("Not OpenSSH private key format") + p1 = m.start(1) + p2 = m.end(1) + data = binascii.a2b_base64(memoryview(data)[p1:p2]) + if not data.startswith(_SK_MAGIC): + raise ValueError("Not OpenSSH private key format") + data = memoryview(data)[len(_SK_MAGIC) :] + + # parse header + ciphername, data = _get_sshstr(data) + kdfname, data = _get_sshstr(data) + kdfoptions, data = _get_sshstr(data) + nkeys, data = _get_u32(data) + if nkeys != 1: + raise ValueError("Only one key supported") + + # load public key data + pubdata, data = _get_sshstr(data) + pub_key_type, pubdata = _get_sshstr(pubdata) + kformat = _lookup_kformat(pub_key_type) + pubfields, pubdata = kformat.get_public(pubdata) + _check_empty(pubdata) + + if (ciphername, kdfname) != (_NONE, _NONE): + ciphername_bytes = ciphername.tobytes() + if ciphername_bytes not in _SSH_CIPHERS: + raise UnsupportedAlgorithm( + f"Unsupported cipher: {ciphername_bytes!r}" + ) + if kdfname != _BCRYPT: + raise UnsupportedAlgorithm(f"Unsupported KDF: {kdfname!r}") + blklen = _SSH_CIPHERS[ciphername_bytes].block_len + tag_len = _SSH_CIPHERS[ciphername_bytes].tag_len + # load secret data + edata, data = _get_sshstr(data) + # see https://bugzilla.mindrot.org/show_bug.cgi?id=3553 for + # information about how OpenSSH handles AEAD tags + if _SSH_CIPHERS[ciphername_bytes].is_aead: + tag = bytes(data) + if len(tag) != tag_len: + raise ValueError("Corrupt data: invalid tag length for cipher") + else: + _check_empty(data) + _check_block_size(edata, blklen) + salt, kbuf = _get_sshstr(kdfoptions) + rounds, kbuf = _get_u32(kbuf) + _check_empty(kbuf) + ciph = _init_cipher(ciphername_bytes, password, salt.tobytes(), rounds) + dec = ciph.decryptor() + edata = memoryview(dec.update(edata)) + if _SSH_CIPHERS[ciphername_bytes].is_aead: + assert isinstance(dec, AEADDecryptionContext) + _check_empty(dec.finalize_with_tag(tag)) + else: + # _check_block_size requires data to be a full block so there + # should be no output from finalize + _check_empty(dec.finalize()) + else: + # load secret data + edata, data = _get_sshstr(data) + _check_empty(data) + blklen = 8 + _check_block_size(edata, blklen) + ck1, edata = _get_u32(edata) + ck2, edata = _get_u32(edata) + if ck1 != ck2: + raise ValueError("Corrupt data: broken checksum") + + # load per-key struct + key_type, edata = _get_sshstr(edata) + if key_type != pub_key_type: + raise ValueError("Corrupt data: key type mismatch") + private_key, edata = kformat.load_private(edata, pubfields) + comment, edata = _get_sshstr(edata) + + # yes, SSH does padding check *after* all other parsing is done. + # need to follow as it writes zero-byte padding too. + if edata != _PADDING[: len(edata)]: + raise ValueError("Corrupt data: invalid padding") + + if isinstance(private_key, dsa.DSAPrivateKey): + warnings.warn( + "SSH DSA keys are deprecated and will be removed in a future " + "release.", + utils.DeprecatedIn40, + stacklevel=2, + ) + + return private_key + + +def _serialize_ssh_private_key( + private_key: SSHPrivateKeyTypes, + password: bytes, + encryption_algorithm: KeySerializationEncryption, +) -> bytes: + """Serialize private key with OpenSSH custom encoding.""" + utils._check_bytes("password", password) + if isinstance(private_key, dsa.DSAPrivateKey): + warnings.warn( + "SSH DSA key support is deprecated and will be " + "removed in a future release", + utils.DeprecatedIn40, + stacklevel=4, + ) + + key_type = _get_ssh_key_type(private_key) + kformat = _lookup_kformat(key_type) + + # setup parameters + f_kdfoptions = _FragList() + if password: + ciphername = _DEFAULT_CIPHER + blklen = _SSH_CIPHERS[ciphername].block_len + kdfname = _BCRYPT + rounds = _DEFAULT_ROUNDS + if ( + isinstance(encryption_algorithm, _KeySerializationEncryption) + and encryption_algorithm._kdf_rounds is not None + ): + rounds = encryption_algorithm._kdf_rounds + salt = os.urandom(16) + f_kdfoptions.put_sshstr(salt) + f_kdfoptions.put_u32(rounds) + ciph = _init_cipher(ciphername, password, salt, rounds) + else: + ciphername = kdfname = _NONE + blklen = 8 + ciph = None + nkeys = 1 + checkval = os.urandom(4) + comment = b"" + + # encode public and private parts together + f_public_key = _FragList() + f_public_key.put_sshstr(key_type) + kformat.encode_public(private_key.public_key(), f_public_key) + + f_secrets = _FragList([checkval, checkval]) + f_secrets.put_sshstr(key_type) + kformat.encode_private(private_key, f_secrets) + f_secrets.put_sshstr(comment) + f_secrets.put_raw(_PADDING[: blklen - (f_secrets.size() % blklen)]) + + # top-level structure + f_main = _FragList() + f_main.put_raw(_SK_MAGIC) + f_main.put_sshstr(ciphername) + f_main.put_sshstr(kdfname) + f_main.put_sshstr(f_kdfoptions) + f_main.put_u32(nkeys) + f_main.put_sshstr(f_public_key) + f_main.put_sshstr(f_secrets) + + # copy result info bytearray + slen = f_secrets.size() + mlen = f_main.size() + buf = memoryview(bytearray(mlen + blklen)) + f_main.render(buf) + ofs = mlen - slen + + # encrypt in-place + if ciph is not None: + ciph.encryptor().update_into(buf[ofs:mlen], buf[ofs:]) + + return _ssh_pem_encode(buf[:mlen]) + + +SSHPublicKeyTypes = typing.Union[ + ec.EllipticCurvePublicKey, + rsa.RSAPublicKey, + dsa.DSAPublicKey, + ed25519.Ed25519PublicKey, +] + +SSHCertPublicKeyTypes = typing.Union[ + ec.EllipticCurvePublicKey, + rsa.RSAPublicKey, + ed25519.Ed25519PublicKey, +] + + +class SSHCertificateType(enum.Enum): + USER = 1 + HOST = 2 + + +class SSHCertificate: + def __init__( + self, + _nonce: memoryview, + _public_key: SSHPublicKeyTypes, + _serial: int, + _cctype: int, + _key_id: memoryview, + _valid_principals: typing.List[bytes], + _valid_after: int, + _valid_before: int, + _critical_options: typing.Dict[bytes, bytes], + _extensions: typing.Dict[bytes, bytes], + _sig_type: memoryview, + _sig_key: memoryview, + _inner_sig_type: memoryview, + _signature: memoryview, + _tbs_cert_body: memoryview, + _cert_key_type: bytes, + _cert_body: memoryview, + ): + self._nonce = _nonce + self._public_key = _public_key + self._serial = _serial + try: + self._type = SSHCertificateType(_cctype) + except ValueError: + raise ValueError("Invalid certificate type") + self._key_id = _key_id + self._valid_principals = _valid_principals + self._valid_after = _valid_after + self._valid_before = _valid_before + self._critical_options = _critical_options + self._extensions = _extensions + self._sig_type = _sig_type + self._sig_key = _sig_key + self._inner_sig_type = _inner_sig_type + self._signature = _signature + self._cert_key_type = _cert_key_type + self._cert_body = _cert_body + self._tbs_cert_body = _tbs_cert_body + + @property + def nonce(self) -> bytes: + return bytes(self._nonce) + + def public_key(self) -> SSHCertPublicKeyTypes: + # make mypy happy until we remove DSA support entirely and + # the underlying union won't have a disallowed type + return typing.cast(SSHCertPublicKeyTypes, self._public_key) + + @property + def serial(self) -> int: + return self._serial + + @property + def type(self) -> SSHCertificateType: + return self._type + + @property + def key_id(self) -> bytes: + return bytes(self._key_id) + + @property + def valid_principals(self) -> typing.List[bytes]: + return self._valid_principals + + @property + def valid_before(self) -> int: + return self._valid_before + + @property + def valid_after(self) -> int: + return self._valid_after + + @property + def critical_options(self) -> typing.Dict[bytes, bytes]: + return self._critical_options + + @property + def extensions(self) -> typing.Dict[bytes, bytes]: + return self._extensions + + def signature_key(self) -> SSHCertPublicKeyTypes: + sigformat = _lookup_kformat(self._sig_type) + signature_key, sigkey_rest = sigformat.load_public(self._sig_key) + _check_empty(sigkey_rest) + return signature_key + + def public_bytes(self) -> bytes: + return ( + bytes(self._cert_key_type) + + b" " + + binascii.b2a_base64(bytes(self._cert_body), newline=False) + ) + + def verify_cert_signature(self) -> None: + signature_key = self.signature_key() + if isinstance(signature_key, ed25519.Ed25519PublicKey): + signature_key.verify( + bytes(self._signature), bytes(self._tbs_cert_body) + ) + elif isinstance(signature_key, ec.EllipticCurvePublicKey): + # The signature is encoded as a pair of big-endian integers + r, data = _get_mpint(self._signature) + s, data = _get_mpint(data) + _check_empty(data) + computed_sig = asym_utils.encode_dss_signature(r, s) + hash_alg = _get_ec_hash_alg(signature_key.curve) + signature_key.verify( + computed_sig, bytes(self._tbs_cert_body), ec.ECDSA(hash_alg) + ) + else: + assert isinstance(signature_key, rsa.RSAPublicKey) + if self._inner_sig_type == _SSH_RSA: + hash_alg = hashes.SHA1() + elif self._inner_sig_type == _SSH_RSA_SHA256: + hash_alg = hashes.SHA256() + else: + assert self._inner_sig_type == _SSH_RSA_SHA512 + hash_alg = hashes.SHA512() + signature_key.verify( + bytes(self._signature), + bytes(self._tbs_cert_body), + padding.PKCS1v15(), + hash_alg, + ) + + +def _get_ec_hash_alg(curve: ec.EllipticCurve) -> hashes.HashAlgorithm: + if isinstance(curve, ec.SECP256R1): + return hashes.SHA256() + elif isinstance(curve, ec.SECP384R1): + return hashes.SHA384() + else: + assert isinstance(curve, ec.SECP521R1) + return hashes.SHA512() + + +def _load_ssh_public_identity( + data: bytes, + _legacy_dsa_allowed=False, +) -> typing.Union[SSHCertificate, SSHPublicKeyTypes]: + utils._check_byteslike("data", data) + + m = _SSH_PUBKEY_RC.match(data) + if not m: + raise ValueError("Invalid line format") + key_type = orig_key_type = m.group(1) + key_body = m.group(2) + with_cert = False + if key_type.endswith(_CERT_SUFFIX): + with_cert = True + key_type = key_type[: -len(_CERT_SUFFIX)] + if key_type == _SSH_DSA and not _legacy_dsa_allowed: + raise UnsupportedAlgorithm( + "DSA keys aren't supported in SSH certificates" + ) + kformat = _lookup_kformat(key_type) + + try: + rest = memoryview(binascii.a2b_base64(key_body)) + except (TypeError, binascii.Error): + raise ValueError("Invalid format") + + if with_cert: + cert_body = rest + inner_key_type, rest = _get_sshstr(rest) + if inner_key_type != orig_key_type: + raise ValueError("Invalid key format") + if with_cert: + nonce, rest = _get_sshstr(rest) + public_key, rest = kformat.load_public(rest) + if with_cert: + serial, rest = _get_u64(rest) + cctype, rest = _get_u32(rest) + key_id, rest = _get_sshstr(rest) + principals, rest = _get_sshstr(rest) + valid_principals = [] + while principals: + principal, principals = _get_sshstr(principals) + valid_principals.append(bytes(principal)) + valid_after, rest = _get_u64(rest) + valid_before, rest = _get_u64(rest) + crit_options, rest = _get_sshstr(rest) + critical_options = _parse_exts_opts(crit_options) + exts, rest = _get_sshstr(rest) + extensions = _parse_exts_opts(exts) + # Get the reserved field, which is unused. + _, rest = _get_sshstr(rest) + sig_key_raw, rest = _get_sshstr(rest) + sig_type, sig_key = _get_sshstr(sig_key_raw) + if sig_type == _SSH_DSA and not _legacy_dsa_allowed: + raise UnsupportedAlgorithm( + "DSA signatures aren't supported in SSH certificates" + ) + # Get the entire cert body and subtract the signature + tbs_cert_body = cert_body[: -len(rest)] + signature_raw, rest = _get_sshstr(rest) + _check_empty(rest) + inner_sig_type, sig_rest = _get_sshstr(signature_raw) + # RSA certs can have multiple algorithm types + if ( + sig_type == _SSH_RSA + and inner_sig_type + not in [_SSH_RSA_SHA256, _SSH_RSA_SHA512, _SSH_RSA] + ) or (sig_type != _SSH_RSA and inner_sig_type != sig_type): + raise ValueError("Signature key type does not match") + signature, sig_rest = _get_sshstr(sig_rest) + _check_empty(sig_rest) + return SSHCertificate( + nonce, + public_key, + serial, + cctype, + key_id, + valid_principals, + valid_after, + valid_before, + critical_options, + extensions, + sig_type, + sig_key, + inner_sig_type, + signature, + tbs_cert_body, + orig_key_type, + cert_body, + ) + else: + _check_empty(rest) + return public_key + + +def load_ssh_public_identity( + data: bytes, +) -> typing.Union[SSHCertificate, SSHPublicKeyTypes]: + return _load_ssh_public_identity(data) + + +def _parse_exts_opts(exts_opts: memoryview) -> typing.Dict[bytes, bytes]: + result: typing.Dict[bytes, bytes] = {} + last_name = None + while exts_opts: + name, exts_opts = _get_sshstr(exts_opts) + bname: bytes = bytes(name) + if bname in result: + raise ValueError("Duplicate name") + if last_name is not None and bname < last_name: + raise ValueError("Fields not lexically sorted") + value, exts_opts = _get_sshstr(exts_opts) + if len(value) > 0: + try: + value, extra = _get_sshstr(value) + except ValueError: + warnings.warn( + "This certificate has an incorrect encoding for critical " + "options or extensions. This will be an exception in " + "cryptography 42", + utils.DeprecatedIn41, + stacklevel=4, + ) + else: + if len(extra) > 0: + raise ValueError("Unexpected extra data after value") + result[bname] = bytes(value) + last_name = bname + return result + + +def load_ssh_public_key( + data: bytes, backend: typing.Any = None +) -> SSHPublicKeyTypes: + cert_or_key = _load_ssh_public_identity(data, _legacy_dsa_allowed=True) + public_key: SSHPublicKeyTypes + if isinstance(cert_or_key, SSHCertificate): + public_key = cert_or_key.public_key() + else: + public_key = cert_or_key + + if isinstance(public_key, dsa.DSAPublicKey): + warnings.warn( + "SSH DSA keys are deprecated and will be removed in a future " + "release.", + utils.DeprecatedIn40, + stacklevel=2, + ) + return public_key + + +def serialize_ssh_public_key(public_key: SSHPublicKeyTypes) -> bytes: + """One-line public key format for OpenSSH""" + if isinstance(public_key, dsa.DSAPublicKey): + warnings.warn( + "SSH DSA key support is deprecated and will be " + "removed in a future release", + utils.DeprecatedIn40, + stacklevel=4, + ) + key_type = _get_ssh_key_type(public_key) + kformat = _lookup_kformat(key_type) + + f_pub = _FragList() + f_pub.put_sshstr(key_type) + kformat.encode_public(public_key, f_pub) + + pub = binascii.b2a_base64(f_pub.tobytes()).strip() + return b"".join([key_type, b" ", pub]) + + +SSHCertPrivateKeyTypes = typing.Union[ + ec.EllipticCurvePrivateKey, + rsa.RSAPrivateKey, + ed25519.Ed25519PrivateKey, +] + + +# This is an undocumented limit enforced in the openssh codebase for sshd and +# ssh-keygen, but it is undefined in the ssh certificates spec. +_SSHKEY_CERT_MAX_PRINCIPALS = 256 + + +class SSHCertificateBuilder: + def __init__( + self, + _public_key: typing.Optional[SSHCertPublicKeyTypes] = None, + _serial: typing.Optional[int] = None, + _type: typing.Optional[SSHCertificateType] = None, + _key_id: typing.Optional[bytes] = None, + _valid_principals: typing.List[bytes] = [], + _valid_for_all_principals: bool = False, + _valid_before: typing.Optional[int] = None, + _valid_after: typing.Optional[int] = None, + _critical_options: typing.List[typing.Tuple[bytes, bytes]] = [], + _extensions: typing.List[typing.Tuple[bytes, bytes]] = [], + ): + self._public_key = _public_key + self._serial = _serial + self._type = _type + self._key_id = _key_id + self._valid_principals = _valid_principals + self._valid_for_all_principals = _valid_for_all_principals + self._valid_before = _valid_before + self._valid_after = _valid_after + self._critical_options = _critical_options + self._extensions = _extensions + + def public_key( + self, public_key: SSHCertPublicKeyTypes + ) -> SSHCertificateBuilder: + if not isinstance( + public_key, + ( + ec.EllipticCurvePublicKey, + rsa.RSAPublicKey, + ed25519.Ed25519PublicKey, + ), + ): + raise TypeError("Unsupported key type") + if self._public_key is not None: + raise ValueError("public_key already set") + + return SSHCertificateBuilder( + _public_key=public_key, + _serial=self._serial, + _type=self._type, + _key_id=self._key_id, + _valid_principals=self._valid_principals, + _valid_for_all_principals=self._valid_for_all_principals, + _valid_before=self._valid_before, + _valid_after=self._valid_after, + _critical_options=self._critical_options, + _extensions=self._extensions, + ) + + def serial(self, serial: int) -> SSHCertificateBuilder: + if not isinstance(serial, int): + raise TypeError("serial must be an integer") + if not 0 <= serial < 2**64: + raise ValueError("serial must be between 0 and 2**64") + if self._serial is not None: + raise ValueError("serial already set") + + return SSHCertificateBuilder( + _public_key=self._public_key, + _serial=serial, + _type=self._type, + _key_id=self._key_id, + _valid_principals=self._valid_principals, + _valid_for_all_principals=self._valid_for_all_principals, + _valid_before=self._valid_before, + _valid_after=self._valid_after, + _critical_options=self._critical_options, + _extensions=self._extensions, + ) + + def type(self, type: SSHCertificateType) -> SSHCertificateBuilder: + if not isinstance(type, SSHCertificateType): + raise TypeError("type must be an SSHCertificateType") + if self._type is not None: + raise ValueError("type already set") + + return SSHCertificateBuilder( + _public_key=self._public_key, + _serial=self._serial, + _type=type, + _key_id=self._key_id, + _valid_principals=self._valid_principals, + _valid_for_all_principals=self._valid_for_all_principals, + _valid_before=self._valid_before, + _valid_after=self._valid_after, + _critical_options=self._critical_options, + _extensions=self._extensions, + ) + + def key_id(self, key_id: bytes) -> SSHCertificateBuilder: + if not isinstance(key_id, bytes): + raise TypeError("key_id must be bytes") + if self._key_id is not None: + raise ValueError("key_id already set") + + return SSHCertificateBuilder( + _public_key=self._public_key, + _serial=self._serial, + _type=self._type, + _key_id=key_id, + _valid_principals=self._valid_principals, + _valid_for_all_principals=self._valid_for_all_principals, + _valid_before=self._valid_before, + _valid_after=self._valid_after, + _critical_options=self._critical_options, + _extensions=self._extensions, + ) + + def valid_principals( + self, valid_principals: typing.List[bytes] + ) -> SSHCertificateBuilder: + if self._valid_for_all_principals: + raise ValueError( + "Principals can't be set because the cert is valid " + "for all principals" + ) + if ( + not all(isinstance(x, bytes) for x in valid_principals) + or not valid_principals + ): + raise TypeError( + "principals must be a list of bytes and can't be empty" + ) + if self._valid_principals: + raise ValueError("valid_principals already set") + + if len(valid_principals) > _SSHKEY_CERT_MAX_PRINCIPALS: + raise ValueError( + "Reached or exceeded the maximum number of valid_principals" + ) + + return SSHCertificateBuilder( + _public_key=self._public_key, + _serial=self._serial, + _type=self._type, + _key_id=self._key_id, + _valid_principals=valid_principals, + _valid_for_all_principals=self._valid_for_all_principals, + _valid_before=self._valid_before, + _valid_after=self._valid_after, + _critical_options=self._critical_options, + _extensions=self._extensions, + ) + + def valid_for_all_principals(self): + if self._valid_principals: + raise ValueError( + "valid_principals already set, can't set " + "valid_for_all_principals" + ) + if self._valid_for_all_principals: + raise ValueError("valid_for_all_principals already set") + + return SSHCertificateBuilder( + _public_key=self._public_key, + _serial=self._serial, + _type=self._type, + _key_id=self._key_id, + _valid_principals=self._valid_principals, + _valid_for_all_principals=True, + _valid_before=self._valid_before, + _valid_after=self._valid_after, + _critical_options=self._critical_options, + _extensions=self._extensions, + ) + + def valid_before( + self, valid_before: typing.Union[int, float] + ) -> SSHCertificateBuilder: + if not isinstance(valid_before, (int, float)): + raise TypeError("valid_before must be an int or float") + valid_before = int(valid_before) + if valid_before < 0 or valid_before >= 2**64: + raise ValueError("valid_before must [0, 2**64)") + if self._valid_before is not None: + raise ValueError("valid_before already set") + + return SSHCertificateBuilder( + _public_key=self._public_key, + _serial=self._serial, + _type=self._type, + _key_id=self._key_id, + _valid_principals=self._valid_principals, + _valid_for_all_principals=self._valid_for_all_principals, + _valid_before=valid_before, + _valid_after=self._valid_after, + _critical_options=self._critical_options, + _extensions=self._extensions, + ) + + def valid_after( + self, valid_after: typing.Union[int, float] + ) -> SSHCertificateBuilder: + if not isinstance(valid_after, (int, float)): + raise TypeError("valid_after must be an int or float") + valid_after = int(valid_after) + if valid_after < 0 or valid_after >= 2**64: + raise ValueError("valid_after must [0, 2**64)") + if self._valid_after is not None: + raise ValueError("valid_after already set") + + return SSHCertificateBuilder( + _public_key=self._public_key, + _serial=self._serial, + _type=self._type, + _key_id=self._key_id, + _valid_principals=self._valid_principals, + _valid_for_all_principals=self._valid_for_all_principals, + _valid_before=self._valid_before, + _valid_after=valid_after, + _critical_options=self._critical_options, + _extensions=self._extensions, + ) + + def add_critical_option( + self, name: bytes, value: bytes + ) -> SSHCertificateBuilder: + if not isinstance(name, bytes) or not isinstance(value, bytes): + raise TypeError("name and value must be bytes") + # This is O(n**2) + if name in [name for name, _ in self._critical_options]: + raise ValueError("Duplicate critical option name") + + return SSHCertificateBuilder( + _public_key=self._public_key, + _serial=self._serial, + _type=self._type, + _key_id=self._key_id, + _valid_principals=self._valid_principals, + _valid_for_all_principals=self._valid_for_all_principals, + _valid_before=self._valid_before, + _valid_after=self._valid_after, + _critical_options=self._critical_options + [(name, value)], + _extensions=self._extensions, + ) + + def add_extension( + self, name: bytes, value: bytes + ) -> SSHCertificateBuilder: + if not isinstance(name, bytes) or not isinstance(value, bytes): + raise TypeError("name and value must be bytes") + # This is O(n**2) + if name in [name for name, _ in self._extensions]: + raise ValueError("Duplicate extension name") + + return SSHCertificateBuilder( + _public_key=self._public_key, + _serial=self._serial, + _type=self._type, + _key_id=self._key_id, + _valid_principals=self._valid_principals, + _valid_for_all_principals=self._valid_for_all_principals, + _valid_before=self._valid_before, + _valid_after=self._valid_after, + _critical_options=self._critical_options, + _extensions=self._extensions + [(name, value)], + ) + + def sign(self, private_key: SSHCertPrivateKeyTypes) -> SSHCertificate: + if not isinstance( + private_key, + ( + ec.EllipticCurvePrivateKey, + rsa.RSAPrivateKey, + ed25519.Ed25519PrivateKey, + ), + ): + raise TypeError("Unsupported private key type") + + if self._public_key is None: + raise ValueError("public_key must be set") + + # Not required + serial = 0 if self._serial is None else self._serial + + if self._type is None: + raise ValueError("type must be set") + + # Not required + key_id = b"" if self._key_id is None else self._key_id + + # A zero length list is valid, but means the certificate + # is valid for any principal of the specified type. We require + # the user to explicitly set valid_for_all_principals to get + # that behavior. + if not self._valid_principals and not self._valid_for_all_principals: + raise ValueError( + "valid_principals must be set if valid_for_all_principals " + "is False" + ) + + if self._valid_before is None: + raise ValueError("valid_before must be set") + + if self._valid_after is None: + raise ValueError("valid_after must be set") + + if self._valid_after > self._valid_before: + raise ValueError("valid_after must be earlier than valid_before") + + # lexically sort our byte strings + self._critical_options.sort(key=lambda x: x[0]) + self._extensions.sort(key=lambda x: x[0]) + + key_type = _get_ssh_key_type(self._public_key) + cert_prefix = key_type + _CERT_SUFFIX + + # Marshal the bytes to be signed + nonce = os.urandom(32) + kformat = _lookup_kformat(key_type) + f = _FragList() + f.put_sshstr(cert_prefix) + f.put_sshstr(nonce) + kformat.encode_public(self._public_key, f) + f.put_u64(serial) + f.put_u32(self._type.value) + f.put_sshstr(key_id) + fprincipals = _FragList() + for p in self._valid_principals: + fprincipals.put_sshstr(p) + f.put_sshstr(fprincipals.tobytes()) + f.put_u64(self._valid_after) + f.put_u64(self._valid_before) + fcrit = _FragList() + for name, value in self._critical_options: + fcrit.put_sshstr(name) + if len(value) > 0: + foptval = _FragList() + foptval.put_sshstr(value) + fcrit.put_sshstr(foptval.tobytes()) + else: + fcrit.put_sshstr(value) + f.put_sshstr(fcrit.tobytes()) + fext = _FragList() + for name, value in self._extensions: + fext.put_sshstr(name) + if len(value) > 0: + fextval = _FragList() + fextval.put_sshstr(value) + fext.put_sshstr(fextval.tobytes()) + else: + fext.put_sshstr(value) + f.put_sshstr(fext.tobytes()) + f.put_sshstr(b"") # RESERVED FIELD + # encode CA public key + ca_type = _get_ssh_key_type(private_key) + caformat = _lookup_kformat(ca_type) + caf = _FragList() + caf.put_sshstr(ca_type) + caformat.encode_public(private_key.public_key(), caf) + f.put_sshstr(caf.tobytes()) + # Sigs according to the rules defined for the CA's public key + # (RFC4253 section 6.6 for ssh-rsa, RFC5656 for ECDSA, + # and RFC8032 for Ed25519). + if isinstance(private_key, ed25519.Ed25519PrivateKey): + signature = private_key.sign(f.tobytes()) + fsig = _FragList() + fsig.put_sshstr(ca_type) + fsig.put_sshstr(signature) + f.put_sshstr(fsig.tobytes()) + elif isinstance(private_key, ec.EllipticCurvePrivateKey): + hash_alg = _get_ec_hash_alg(private_key.curve) + signature = private_key.sign(f.tobytes(), ec.ECDSA(hash_alg)) + r, s = asym_utils.decode_dss_signature(signature) + fsig = _FragList() + fsig.put_sshstr(ca_type) + fsigblob = _FragList() + fsigblob.put_mpint(r) + fsigblob.put_mpint(s) + fsig.put_sshstr(fsigblob.tobytes()) + f.put_sshstr(fsig.tobytes()) + + else: + assert isinstance(private_key, rsa.RSAPrivateKey) + # Just like Golang, we're going to use SHA512 for RSA + # https://cs.opensource.google/go/x/crypto/+/refs/tags/ + # v0.4.0:ssh/certs.go;l=445 + # RFC 8332 defines SHA256 and 512 as options + fsig = _FragList() + fsig.put_sshstr(_SSH_RSA_SHA512) + signature = private_key.sign( + f.tobytes(), padding.PKCS1v15(), hashes.SHA512() + ) + fsig.put_sshstr(signature) + f.put_sshstr(fsig.tobytes()) + + cert_data = binascii.b2a_base64(f.tobytes()).strip() + # load_ssh_public_identity returns a union, but this is + # guaranteed to be an SSHCertificate, so we cast to make + # mypy happy. + return typing.cast( + SSHCertificate, + load_ssh_public_identity(b"".join([cert_prefix, b" ", cert_data])), + ) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/twofactor/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/twofactor/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c1af423004863e7db3e163f61a6baa4ddc157351 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/twofactor/__init__.py @@ -0,0 +1,9 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + + +class InvalidToken(Exception): + pass diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/twofactor/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/twofactor/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8fe6bc57beb911fc60cad28fe0257a4bd21711a3 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/twofactor/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/twofactor/__pycache__/hotp.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/twofactor/__pycache__/hotp.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7453dae5de993996d70d1d764d2a04d546eaee58 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/twofactor/__pycache__/hotp.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/twofactor/__pycache__/totp.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/twofactor/__pycache__/totp.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a24466023f72a46166d53330f7b3eb250f42c7e0 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/twofactor/__pycache__/totp.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/twofactor/hotp.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/twofactor/hotp.py new file mode 100644 index 0000000000000000000000000000000000000000..2067108a63d6ff2dd56687e1f477cbe28a2eee4e --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/twofactor/hotp.py @@ -0,0 +1,92 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import base64 +import typing +from urllib.parse import quote, urlencode + +from cryptography.hazmat.primitives import constant_time, hmac +from cryptography.hazmat.primitives.hashes import SHA1, SHA256, SHA512 +from cryptography.hazmat.primitives.twofactor import InvalidToken + +HOTPHashTypes = typing.Union[SHA1, SHA256, SHA512] + + +def _generate_uri( + hotp: HOTP, + type_name: str, + account_name: str, + issuer: typing.Optional[str], + extra_parameters: typing.List[typing.Tuple[str, int]], +) -> str: + parameters = [ + ("digits", hotp._length), + ("secret", base64.b32encode(hotp._key)), + ("algorithm", hotp._algorithm.name.upper()), + ] + + if issuer is not None: + parameters.append(("issuer", issuer)) + + parameters.extend(extra_parameters) + + label = ( + f"{quote(issuer)}:{quote(account_name)}" + if issuer + else quote(account_name) + ) + return f"otpauth://{type_name}/{label}?{urlencode(parameters)}" + + +class HOTP: + def __init__( + self, + key: bytes, + length: int, + algorithm: HOTPHashTypes, + backend: typing.Any = None, + enforce_key_length: bool = True, + ) -> None: + if len(key) < 16 and enforce_key_length is True: + raise ValueError("Key length has to be at least 128 bits.") + + if not isinstance(length, int): + raise TypeError("Length parameter must be an integer type.") + + if length < 6 or length > 8: + raise ValueError("Length of HOTP has to be between 6 and 8.") + + if not isinstance(algorithm, (SHA1, SHA256, SHA512)): + raise TypeError("Algorithm must be SHA1, SHA256 or SHA512.") + + self._key = key + self._length = length + self._algorithm = algorithm + + def generate(self, counter: int) -> bytes: + truncated_value = self._dynamic_truncate(counter) + hotp = truncated_value % (10**self._length) + return "{0:0{1}}".format(hotp, self._length).encode() + + def verify(self, hotp: bytes, counter: int) -> None: + if not constant_time.bytes_eq(self.generate(counter), hotp): + raise InvalidToken("Supplied HOTP value does not match.") + + def _dynamic_truncate(self, counter: int) -> int: + ctx = hmac.HMAC(self._key, self._algorithm) + ctx.update(counter.to_bytes(length=8, byteorder="big")) + hmac_value = ctx.finalize() + + offset = hmac_value[len(hmac_value) - 1] & 0b1111 + p = hmac_value[offset : offset + 4] + return int.from_bytes(p, byteorder="big") & 0x7FFFFFFF + + def get_provisioning_uri( + self, account_name: str, counter: int, issuer: typing.Optional[str] + ) -> str: + return _generate_uri( + self, "hotp", account_name, issuer, [("counter", int(counter))] + ) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/twofactor/totp.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/twofactor/totp.py new file mode 100644 index 0000000000000000000000000000000000000000..daddcea2f77e4b753f5618625336de31c2035980 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/hazmat/primitives/twofactor/totp.py @@ -0,0 +1,50 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import typing + +from cryptography.hazmat.primitives import constant_time +from cryptography.hazmat.primitives.twofactor import InvalidToken +from cryptography.hazmat.primitives.twofactor.hotp import ( + HOTP, + HOTPHashTypes, + _generate_uri, +) + + +class TOTP: + def __init__( + self, + key: bytes, + length: int, + algorithm: HOTPHashTypes, + time_step: int, + backend: typing.Any = None, + enforce_key_length: bool = True, + ): + self._time_step = time_step + self._hotp = HOTP( + key, length, algorithm, enforce_key_length=enforce_key_length + ) + + def generate(self, time: typing.Union[int, float]) -> bytes: + counter = int(time / self._time_step) + return self._hotp.generate(counter) + + def verify(self, totp: bytes, time: int) -> None: + if not constant_time.bytes_eq(self.generate(time), totp): + raise InvalidToken("Supplied TOTP value does not match.") + + def get_provisioning_uri( + self, account_name: str, issuer: typing.Optional[str] + ) -> str: + return _generate_uri( + self._hotp, + "totp", + account_name, + issuer, + [("period", int(self._time_step))], + ) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/x509/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/x509/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d77694a29906412c9fc5628a3ff1980db66578ba --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/x509/__init__.py @@ -0,0 +1,255 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography.x509 import certificate_transparency +from cryptography.x509.base import ( + Attribute, + AttributeNotFound, + Attributes, + Certificate, + CertificateBuilder, + CertificateRevocationList, + CertificateRevocationListBuilder, + CertificateSigningRequest, + CertificateSigningRequestBuilder, + InvalidVersion, + RevokedCertificate, + RevokedCertificateBuilder, + Version, + load_der_x509_certificate, + load_der_x509_crl, + load_der_x509_csr, + load_pem_x509_certificate, + load_pem_x509_certificates, + load_pem_x509_crl, + load_pem_x509_csr, + random_serial_number, +) +from cryptography.x509.extensions import ( + AccessDescription, + AuthorityInformationAccess, + AuthorityKeyIdentifier, + BasicConstraints, + CertificateIssuer, + CertificatePolicies, + CRLDistributionPoints, + CRLNumber, + CRLReason, + DeltaCRLIndicator, + DistributionPoint, + DuplicateExtension, + ExtendedKeyUsage, + Extension, + ExtensionNotFound, + Extensions, + ExtensionType, + FreshestCRL, + GeneralNames, + InhibitAnyPolicy, + InvalidityDate, + IssuerAlternativeName, + IssuingDistributionPoint, + KeyUsage, + MSCertificateTemplate, + NameConstraints, + NoticeReference, + OCSPAcceptableResponses, + OCSPNoCheck, + OCSPNonce, + PolicyConstraints, + PolicyInformation, + PrecertificateSignedCertificateTimestamps, + PrecertPoison, + ReasonFlags, + SignedCertificateTimestamps, + SubjectAlternativeName, + SubjectInformationAccess, + SubjectKeyIdentifier, + TLSFeature, + TLSFeatureType, + UnrecognizedExtension, + UserNotice, +) +from cryptography.x509.general_name import ( + DirectoryName, + DNSName, + GeneralName, + IPAddress, + OtherName, + RegisteredID, + RFC822Name, + UniformResourceIdentifier, + UnsupportedGeneralNameType, +) +from cryptography.x509.name import ( + Name, + NameAttribute, + RelativeDistinguishedName, +) +from cryptography.x509.oid import ( + AuthorityInformationAccessOID, + CertificatePoliciesOID, + CRLEntryExtensionOID, + ExtendedKeyUsageOID, + ExtensionOID, + NameOID, + ObjectIdentifier, + SignatureAlgorithmOID, +) + +OID_AUTHORITY_INFORMATION_ACCESS = ExtensionOID.AUTHORITY_INFORMATION_ACCESS +OID_AUTHORITY_KEY_IDENTIFIER = ExtensionOID.AUTHORITY_KEY_IDENTIFIER +OID_BASIC_CONSTRAINTS = ExtensionOID.BASIC_CONSTRAINTS +OID_CERTIFICATE_POLICIES = ExtensionOID.CERTIFICATE_POLICIES +OID_CRL_DISTRIBUTION_POINTS = ExtensionOID.CRL_DISTRIBUTION_POINTS +OID_EXTENDED_KEY_USAGE = ExtensionOID.EXTENDED_KEY_USAGE +OID_FRESHEST_CRL = ExtensionOID.FRESHEST_CRL +OID_INHIBIT_ANY_POLICY = ExtensionOID.INHIBIT_ANY_POLICY +OID_ISSUER_ALTERNATIVE_NAME = ExtensionOID.ISSUER_ALTERNATIVE_NAME +OID_KEY_USAGE = ExtensionOID.KEY_USAGE +OID_NAME_CONSTRAINTS = ExtensionOID.NAME_CONSTRAINTS +OID_OCSP_NO_CHECK = ExtensionOID.OCSP_NO_CHECK +OID_POLICY_CONSTRAINTS = ExtensionOID.POLICY_CONSTRAINTS +OID_POLICY_MAPPINGS = ExtensionOID.POLICY_MAPPINGS +OID_SUBJECT_ALTERNATIVE_NAME = ExtensionOID.SUBJECT_ALTERNATIVE_NAME +OID_SUBJECT_DIRECTORY_ATTRIBUTES = ExtensionOID.SUBJECT_DIRECTORY_ATTRIBUTES +OID_SUBJECT_INFORMATION_ACCESS = ExtensionOID.SUBJECT_INFORMATION_ACCESS +OID_SUBJECT_KEY_IDENTIFIER = ExtensionOID.SUBJECT_KEY_IDENTIFIER + +OID_DSA_WITH_SHA1 = SignatureAlgorithmOID.DSA_WITH_SHA1 +OID_DSA_WITH_SHA224 = SignatureAlgorithmOID.DSA_WITH_SHA224 +OID_DSA_WITH_SHA256 = SignatureAlgorithmOID.DSA_WITH_SHA256 +OID_ECDSA_WITH_SHA1 = SignatureAlgorithmOID.ECDSA_WITH_SHA1 +OID_ECDSA_WITH_SHA224 = SignatureAlgorithmOID.ECDSA_WITH_SHA224 +OID_ECDSA_WITH_SHA256 = SignatureAlgorithmOID.ECDSA_WITH_SHA256 +OID_ECDSA_WITH_SHA384 = SignatureAlgorithmOID.ECDSA_WITH_SHA384 +OID_ECDSA_WITH_SHA512 = SignatureAlgorithmOID.ECDSA_WITH_SHA512 +OID_RSA_WITH_MD5 = SignatureAlgorithmOID.RSA_WITH_MD5 +OID_RSA_WITH_SHA1 = SignatureAlgorithmOID.RSA_WITH_SHA1 +OID_RSA_WITH_SHA224 = SignatureAlgorithmOID.RSA_WITH_SHA224 +OID_RSA_WITH_SHA256 = SignatureAlgorithmOID.RSA_WITH_SHA256 +OID_RSA_WITH_SHA384 = SignatureAlgorithmOID.RSA_WITH_SHA384 +OID_RSA_WITH_SHA512 = SignatureAlgorithmOID.RSA_WITH_SHA512 +OID_RSASSA_PSS = SignatureAlgorithmOID.RSASSA_PSS + +OID_COMMON_NAME = NameOID.COMMON_NAME +OID_COUNTRY_NAME = NameOID.COUNTRY_NAME +OID_DOMAIN_COMPONENT = NameOID.DOMAIN_COMPONENT +OID_DN_QUALIFIER = NameOID.DN_QUALIFIER +OID_EMAIL_ADDRESS = NameOID.EMAIL_ADDRESS +OID_GENERATION_QUALIFIER = NameOID.GENERATION_QUALIFIER +OID_GIVEN_NAME = NameOID.GIVEN_NAME +OID_LOCALITY_NAME = NameOID.LOCALITY_NAME +OID_ORGANIZATIONAL_UNIT_NAME = NameOID.ORGANIZATIONAL_UNIT_NAME +OID_ORGANIZATION_NAME = NameOID.ORGANIZATION_NAME +OID_PSEUDONYM = NameOID.PSEUDONYM +OID_SERIAL_NUMBER = NameOID.SERIAL_NUMBER +OID_STATE_OR_PROVINCE_NAME = NameOID.STATE_OR_PROVINCE_NAME +OID_SURNAME = NameOID.SURNAME +OID_TITLE = NameOID.TITLE + +OID_CLIENT_AUTH = ExtendedKeyUsageOID.CLIENT_AUTH +OID_CODE_SIGNING = ExtendedKeyUsageOID.CODE_SIGNING +OID_EMAIL_PROTECTION = ExtendedKeyUsageOID.EMAIL_PROTECTION +OID_OCSP_SIGNING = ExtendedKeyUsageOID.OCSP_SIGNING +OID_SERVER_AUTH = ExtendedKeyUsageOID.SERVER_AUTH +OID_TIME_STAMPING = ExtendedKeyUsageOID.TIME_STAMPING + +OID_ANY_POLICY = CertificatePoliciesOID.ANY_POLICY +OID_CPS_QUALIFIER = CertificatePoliciesOID.CPS_QUALIFIER +OID_CPS_USER_NOTICE = CertificatePoliciesOID.CPS_USER_NOTICE + +OID_CERTIFICATE_ISSUER = CRLEntryExtensionOID.CERTIFICATE_ISSUER +OID_CRL_REASON = CRLEntryExtensionOID.CRL_REASON +OID_INVALIDITY_DATE = CRLEntryExtensionOID.INVALIDITY_DATE + +OID_CA_ISSUERS = AuthorityInformationAccessOID.CA_ISSUERS +OID_OCSP = AuthorityInformationAccessOID.OCSP + +__all__ = [ + "certificate_transparency", + "load_pem_x509_certificate", + "load_pem_x509_certificates", + "load_der_x509_certificate", + "load_pem_x509_csr", + "load_der_x509_csr", + "load_pem_x509_crl", + "load_der_x509_crl", + "random_serial_number", + "Attribute", + "AttributeNotFound", + "Attributes", + "InvalidVersion", + "DeltaCRLIndicator", + "DuplicateExtension", + "ExtensionNotFound", + "UnsupportedGeneralNameType", + "NameAttribute", + "Name", + "RelativeDistinguishedName", + "ObjectIdentifier", + "ExtensionType", + "Extensions", + "Extension", + "ExtendedKeyUsage", + "FreshestCRL", + "IssuingDistributionPoint", + "TLSFeature", + "TLSFeatureType", + "OCSPAcceptableResponses", + "OCSPNoCheck", + "BasicConstraints", + "CRLNumber", + "KeyUsage", + "AuthorityInformationAccess", + "SubjectInformationAccess", + "AccessDescription", + "CertificatePolicies", + "PolicyInformation", + "UserNotice", + "NoticeReference", + "SubjectKeyIdentifier", + "NameConstraints", + "CRLDistributionPoints", + "DistributionPoint", + "ReasonFlags", + "InhibitAnyPolicy", + "SubjectAlternativeName", + "IssuerAlternativeName", + "AuthorityKeyIdentifier", + "GeneralNames", + "GeneralName", + "RFC822Name", + "DNSName", + "UniformResourceIdentifier", + "RegisteredID", + "DirectoryName", + "IPAddress", + "OtherName", + "Certificate", + "CertificateRevocationList", + "CertificateRevocationListBuilder", + "CertificateSigningRequest", + "RevokedCertificate", + "RevokedCertificateBuilder", + "CertificateSigningRequestBuilder", + "CertificateBuilder", + "Version", + "OID_CA_ISSUERS", + "OID_OCSP", + "CertificateIssuer", + "CRLReason", + "InvalidityDate", + "UnrecognizedExtension", + "PolicyConstraints", + "PrecertificateSignedCertificateTimestamps", + "PrecertPoison", + "OCSPNonce", + "SignedCertificateTimestamps", + "SignatureAlgorithmOID", + "NameOID", + "MSCertificateTemplate", +] diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/x509/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/x509/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..02466b1eec8e4b6a71dd6e6fde548a526aef8517 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/x509/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/x509/__pycache__/base.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/x509/__pycache__/base.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..89d7cd04cbb0719a040ae464640c433e165824b5 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/x509/__pycache__/base.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/x509/__pycache__/certificate_transparency.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/x509/__pycache__/certificate_transparency.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..690abf9d1166de5828a66420e6367caff6ee6616 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/x509/__pycache__/certificate_transparency.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/x509/__pycache__/extensions.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/x509/__pycache__/extensions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0ba8bcf48b221b6fe969f3e35bd79bf6bcced805 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/x509/__pycache__/extensions.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/x509/__pycache__/general_name.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/x509/__pycache__/general_name.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..98bd1efae6b8659f9aa1bf1964e724d1fbe987af Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/x509/__pycache__/general_name.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/x509/__pycache__/name.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/x509/__pycache__/name.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..040b831458917f12f2e5e20fe63e52059a883b9b Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/x509/__pycache__/name.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/x509/__pycache__/ocsp.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/x509/__pycache__/ocsp.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..10293ab34b8e4dcbb81251aed3ea257672643f37 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/x509/__pycache__/ocsp.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/x509/__pycache__/oid.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/x509/__pycache__/oid.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e5a76ab102001ff9740106094756e09b45ee0456 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/x509/__pycache__/oid.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/x509/base.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/x509/base.py new file mode 100644 index 0000000000000000000000000000000000000000..576385e088d83a7016b4bc1f11170f66d58a6e1e --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/x509/base.py @@ -0,0 +1,1173 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc +import datetime +import os +import typing + +from cryptography import utils +from cryptography.hazmat.bindings._rust import x509 as rust_x509 +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import ( + dsa, + ec, + ed448, + ed25519, + padding, + rsa, + x448, + x25519, +) +from cryptography.hazmat.primitives.asymmetric.types import ( + CertificateIssuerPrivateKeyTypes, + CertificateIssuerPublicKeyTypes, + CertificatePublicKeyTypes, +) +from cryptography.x509.extensions import ( + Extension, + Extensions, + ExtensionType, + _make_sequence_methods, +) +from cryptography.x509.name import Name, _ASN1Type +from cryptography.x509.oid import ObjectIdentifier + +_EARLIEST_UTC_TIME = datetime.datetime(1950, 1, 1) + +# This must be kept in sync with sign.rs's list of allowable types in +# identify_hash_type +_AllowedHashTypes = typing.Union[ + hashes.SHA224, + hashes.SHA256, + hashes.SHA384, + hashes.SHA512, + hashes.SHA3_224, + hashes.SHA3_256, + hashes.SHA3_384, + hashes.SHA3_512, +] + + +class AttributeNotFound(Exception): + def __init__(self, msg: str, oid: ObjectIdentifier) -> None: + super().__init__(msg) + self.oid = oid + + +def _reject_duplicate_extension( + extension: Extension[ExtensionType], + extensions: typing.List[Extension[ExtensionType]], +) -> None: + # This is quadratic in the number of extensions + for e in extensions: + if e.oid == extension.oid: + raise ValueError("This extension has already been set.") + + +def _reject_duplicate_attribute( + oid: ObjectIdentifier, + attributes: typing.List[ + typing.Tuple[ObjectIdentifier, bytes, typing.Optional[int]] + ], +) -> None: + # This is quadratic in the number of attributes + for attr_oid, _, _ in attributes: + if attr_oid == oid: + raise ValueError("This attribute has already been set.") + + +def _convert_to_naive_utc_time(time: datetime.datetime) -> datetime.datetime: + """Normalizes a datetime to a naive datetime in UTC. + + time -- datetime to normalize. Assumed to be in UTC if not timezone + aware. + """ + if time.tzinfo is not None: + offset = time.utcoffset() + offset = offset if offset else datetime.timedelta() + return time.replace(tzinfo=None) - offset + else: + return time + + +class Attribute: + def __init__( + self, + oid: ObjectIdentifier, + value: bytes, + _type: int = _ASN1Type.UTF8String.value, + ) -> None: + self._oid = oid + self._value = value + self._type = _type + + @property + def oid(self) -> ObjectIdentifier: + return self._oid + + @property + def value(self) -> bytes: + return self._value + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, Attribute): + return NotImplemented + + return ( + self.oid == other.oid + and self.value == other.value + and self._type == other._type + ) + + def __hash__(self) -> int: + return hash((self.oid, self.value, self._type)) + + +class Attributes: + def __init__( + self, + attributes: typing.Iterable[Attribute], + ) -> None: + self._attributes = list(attributes) + + __len__, __iter__, __getitem__ = _make_sequence_methods("_attributes") + + def __repr__(self) -> str: + return f"" + + def get_attribute_for_oid(self, oid: ObjectIdentifier) -> Attribute: + for attr in self: + if attr.oid == oid: + return attr + + raise AttributeNotFound(f"No {oid} attribute was found", oid) + + +class Version(utils.Enum): + v1 = 0 + v3 = 2 + + +class InvalidVersion(Exception): + def __init__(self, msg: str, parsed_version: int) -> None: + super().__init__(msg) + self.parsed_version = parsed_version + + +class Certificate(metaclass=abc.ABCMeta): + @abc.abstractmethod + def fingerprint(self, algorithm: hashes.HashAlgorithm) -> bytes: + """ + Returns bytes using digest passed. + """ + + @property + @abc.abstractmethod + def serial_number(self) -> int: + """ + Returns certificate serial number + """ + + @property + @abc.abstractmethod + def version(self) -> Version: + """ + Returns the certificate version + """ + + @abc.abstractmethod + def public_key(self) -> CertificatePublicKeyTypes: + """ + Returns the public key + """ + + @property + @abc.abstractmethod + def not_valid_before(self) -> datetime.datetime: + """ + Not before time (represented as UTC datetime) + """ + + @property + @abc.abstractmethod + def not_valid_after(self) -> datetime.datetime: + """ + Not after time (represented as UTC datetime) + """ + + @property + @abc.abstractmethod + def issuer(self) -> Name: + """ + Returns the issuer name object. + """ + + @property + @abc.abstractmethod + def subject(self) -> Name: + """ + Returns the subject name object. + """ + + @property + @abc.abstractmethod + def signature_hash_algorithm( + self, + ) -> typing.Optional[hashes.HashAlgorithm]: + """ + Returns a HashAlgorithm corresponding to the type of the digest signed + in the certificate. + """ + + @property + @abc.abstractmethod + def signature_algorithm_oid(self) -> ObjectIdentifier: + """ + Returns the ObjectIdentifier of the signature algorithm. + """ + + @property + @abc.abstractmethod + def signature_algorithm_parameters( + self, + ) -> typing.Union[None, padding.PSS, padding.PKCS1v15, ec.ECDSA]: + """ + Returns the signature algorithm parameters. + """ + + @property + @abc.abstractmethod + def extensions(self) -> Extensions: + """ + Returns an Extensions object. + """ + + @property + @abc.abstractmethod + def signature(self) -> bytes: + """ + Returns the signature bytes. + """ + + @property + @abc.abstractmethod + def tbs_certificate_bytes(self) -> bytes: + """ + Returns the tbsCertificate payload bytes as defined in RFC 5280. + """ + + @property + @abc.abstractmethod + def tbs_precertificate_bytes(self) -> bytes: + """ + Returns the tbsCertificate payload bytes with the SCT list extension + stripped. + """ + + @abc.abstractmethod + def __eq__(self, other: object) -> bool: + """ + Checks equality. + """ + + @abc.abstractmethod + def __hash__(self) -> int: + """ + Computes a hash. + """ + + @abc.abstractmethod + def public_bytes(self, encoding: serialization.Encoding) -> bytes: + """ + Serializes the certificate to PEM or DER format. + """ + + @abc.abstractmethod + def verify_directly_issued_by(self, issuer: Certificate) -> None: + """ + This method verifies that certificate issuer name matches the + issuer subject name and that the certificate is signed by the + issuer's private key. No other validation is performed. + """ + + +# Runtime isinstance checks need this since the rust class is not a subclass. +Certificate.register(rust_x509.Certificate) + + +class RevokedCertificate(metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def serial_number(self) -> int: + """ + Returns the serial number of the revoked certificate. + """ + + @property + @abc.abstractmethod + def revocation_date(self) -> datetime.datetime: + """ + Returns the date of when this certificate was revoked. + """ + + @property + @abc.abstractmethod + def extensions(self) -> Extensions: + """ + Returns an Extensions object containing a list of Revoked extensions. + """ + + +# Runtime isinstance checks need this since the rust class is not a subclass. +RevokedCertificate.register(rust_x509.RevokedCertificate) + + +class _RawRevokedCertificate(RevokedCertificate): + def __init__( + self, + serial_number: int, + revocation_date: datetime.datetime, + extensions: Extensions, + ): + self._serial_number = serial_number + self._revocation_date = revocation_date + self._extensions = extensions + + @property + def serial_number(self) -> int: + return self._serial_number + + @property + def revocation_date(self) -> datetime.datetime: + return self._revocation_date + + @property + def extensions(self) -> Extensions: + return self._extensions + + +class CertificateRevocationList(metaclass=abc.ABCMeta): + @abc.abstractmethod + def public_bytes(self, encoding: serialization.Encoding) -> bytes: + """ + Serializes the CRL to PEM or DER format. + """ + + @abc.abstractmethod + def fingerprint(self, algorithm: hashes.HashAlgorithm) -> bytes: + """ + Returns bytes using digest passed. + """ + + @abc.abstractmethod + def get_revoked_certificate_by_serial_number( + self, serial_number: int + ) -> typing.Optional[RevokedCertificate]: + """ + Returns an instance of RevokedCertificate or None if the serial_number + is not in the CRL. + """ + + @property + @abc.abstractmethod + def signature_hash_algorithm( + self, + ) -> typing.Optional[hashes.HashAlgorithm]: + """ + Returns a HashAlgorithm corresponding to the type of the digest signed + in the certificate. + """ + + @property + @abc.abstractmethod + def signature_algorithm_oid(self) -> ObjectIdentifier: + """ + Returns the ObjectIdentifier of the signature algorithm. + """ + + @property + @abc.abstractmethod + def issuer(self) -> Name: + """ + Returns the X509Name with the issuer of this CRL. + """ + + @property + @abc.abstractmethod + def next_update(self) -> typing.Optional[datetime.datetime]: + """ + Returns the date of next update for this CRL. + """ + + @property + @abc.abstractmethod + def last_update(self) -> datetime.datetime: + """ + Returns the date of last update for this CRL. + """ + + @property + @abc.abstractmethod + def extensions(self) -> Extensions: + """ + Returns an Extensions object containing a list of CRL extensions. + """ + + @property + @abc.abstractmethod + def signature(self) -> bytes: + """ + Returns the signature bytes. + """ + + @property + @abc.abstractmethod + def tbs_certlist_bytes(self) -> bytes: + """ + Returns the tbsCertList payload bytes as defined in RFC 5280. + """ + + @abc.abstractmethod + def __eq__(self, other: object) -> bool: + """ + Checks equality. + """ + + @abc.abstractmethod + def __len__(self) -> int: + """ + Number of revoked certificates in the CRL. + """ + + @typing.overload + def __getitem__(self, idx: int) -> RevokedCertificate: + ... + + @typing.overload + def __getitem__(self, idx: slice) -> typing.List[RevokedCertificate]: + ... + + @abc.abstractmethod + def __getitem__( + self, idx: typing.Union[int, slice] + ) -> typing.Union[RevokedCertificate, typing.List[RevokedCertificate]]: + """ + Returns a revoked certificate (or slice of revoked certificates). + """ + + @abc.abstractmethod + def __iter__(self) -> typing.Iterator[RevokedCertificate]: + """ + Iterator over the revoked certificates + """ + + @abc.abstractmethod + def is_signature_valid( + self, public_key: CertificateIssuerPublicKeyTypes + ) -> bool: + """ + Verifies signature of revocation list against given public key. + """ + + +CertificateRevocationList.register(rust_x509.CertificateRevocationList) + + +class CertificateSigningRequest(metaclass=abc.ABCMeta): + @abc.abstractmethod + def __eq__(self, other: object) -> bool: + """ + Checks equality. + """ + + @abc.abstractmethod + def __hash__(self) -> int: + """ + Computes a hash. + """ + + @abc.abstractmethod + def public_key(self) -> CertificatePublicKeyTypes: + """ + Returns the public key + """ + + @property + @abc.abstractmethod + def subject(self) -> Name: + """ + Returns the subject name object. + """ + + @property + @abc.abstractmethod + def signature_hash_algorithm( + self, + ) -> typing.Optional[hashes.HashAlgorithm]: + """ + Returns a HashAlgorithm corresponding to the type of the digest signed + in the certificate. + """ + + @property + @abc.abstractmethod + def signature_algorithm_oid(self) -> ObjectIdentifier: + """ + Returns the ObjectIdentifier of the signature algorithm. + """ + + @property + @abc.abstractmethod + def extensions(self) -> Extensions: + """ + Returns the extensions in the signing request. + """ + + @property + @abc.abstractmethod + def attributes(self) -> Attributes: + """ + Returns an Attributes object. + """ + + @abc.abstractmethod + def public_bytes(self, encoding: serialization.Encoding) -> bytes: + """ + Encodes the request to PEM or DER format. + """ + + @property + @abc.abstractmethod + def signature(self) -> bytes: + """ + Returns the signature bytes. + """ + + @property + @abc.abstractmethod + def tbs_certrequest_bytes(self) -> bytes: + """ + Returns the PKCS#10 CertificationRequestInfo bytes as defined in RFC + 2986. + """ + + @property + @abc.abstractmethod + def is_signature_valid(self) -> bool: + """ + Verifies signature of signing request. + """ + + @abc.abstractmethod + def get_attribute_for_oid(self, oid: ObjectIdentifier) -> bytes: + """ + Get the attribute value for a given OID. + """ + + +# Runtime isinstance checks need this since the rust class is not a subclass. +CertificateSigningRequest.register(rust_x509.CertificateSigningRequest) + + +# Backend argument preserved for API compatibility, but ignored. +def load_pem_x509_certificate( + data: bytes, backend: typing.Any = None +) -> Certificate: + return rust_x509.load_pem_x509_certificate(data) + + +def load_pem_x509_certificates(data: bytes) -> typing.List[Certificate]: + return rust_x509.load_pem_x509_certificates(data) + + +# Backend argument preserved for API compatibility, but ignored. +def load_der_x509_certificate( + data: bytes, backend: typing.Any = None +) -> Certificate: + return rust_x509.load_der_x509_certificate(data) + + +# Backend argument preserved for API compatibility, but ignored. +def load_pem_x509_csr( + data: bytes, backend: typing.Any = None +) -> CertificateSigningRequest: + return rust_x509.load_pem_x509_csr(data) + + +# Backend argument preserved for API compatibility, but ignored. +def load_der_x509_csr( + data: bytes, backend: typing.Any = None +) -> CertificateSigningRequest: + return rust_x509.load_der_x509_csr(data) + + +# Backend argument preserved for API compatibility, but ignored. +def load_pem_x509_crl( + data: bytes, backend: typing.Any = None +) -> CertificateRevocationList: + return rust_x509.load_pem_x509_crl(data) + + +# Backend argument preserved for API compatibility, but ignored. +def load_der_x509_crl( + data: bytes, backend: typing.Any = None +) -> CertificateRevocationList: + return rust_x509.load_der_x509_crl(data) + + +class CertificateSigningRequestBuilder: + def __init__( + self, + subject_name: typing.Optional[Name] = None, + extensions: typing.List[Extension[ExtensionType]] = [], + attributes: typing.List[ + typing.Tuple[ObjectIdentifier, bytes, typing.Optional[int]] + ] = [], + ): + """ + Creates an empty X.509 certificate request (v1). + """ + self._subject_name = subject_name + self._extensions = extensions + self._attributes = attributes + + def subject_name(self, name: Name) -> CertificateSigningRequestBuilder: + """ + Sets the certificate requestor's distinguished name. + """ + if not isinstance(name, Name): + raise TypeError("Expecting x509.Name object.") + if self._subject_name is not None: + raise ValueError("The subject name may only be set once.") + return CertificateSigningRequestBuilder( + name, self._extensions, self._attributes + ) + + def add_extension( + self, extval: ExtensionType, critical: bool + ) -> CertificateSigningRequestBuilder: + """ + Adds an X.509 extension to the certificate request. + """ + if not isinstance(extval, ExtensionType): + raise TypeError("extension must be an ExtensionType") + + extension = Extension(extval.oid, critical, extval) + _reject_duplicate_extension(extension, self._extensions) + + return CertificateSigningRequestBuilder( + self._subject_name, + self._extensions + [extension], + self._attributes, + ) + + def add_attribute( + self, + oid: ObjectIdentifier, + value: bytes, + *, + _tag: typing.Optional[_ASN1Type] = None, + ) -> CertificateSigningRequestBuilder: + """ + Adds an X.509 attribute with an OID and associated value. + """ + if not isinstance(oid, ObjectIdentifier): + raise TypeError("oid must be an ObjectIdentifier") + + if not isinstance(value, bytes): + raise TypeError("value must be bytes") + + if _tag is not None and not isinstance(_tag, _ASN1Type): + raise TypeError("tag must be _ASN1Type") + + _reject_duplicate_attribute(oid, self._attributes) + + if _tag is not None: + tag = _tag.value + else: + tag = None + + return CertificateSigningRequestBuilder( + self._subject_name, + self._extensions, + self._attributes + [(oid, value, tag)], + ) + + def sign( + self, + private_key: CertificateIssuerPrivateKeyTypes, + algorithm: typing.Optional[_AllowedHashTypes], + backend: typing.Any = None, + ) -> CertificateSigningRequest: + """ + Signs the request using the requestor's private key. + """ + if self._subject_name is None: + raise ValueError("A CertificateSigningRequest must have a subject") + return rust_x509.create_x509_csr(self, private_key, algorithm) + + +class CertificateBuilder: + _extensions: typing.List[Extension[ExtensionType]] + + def __init__( + self, + issuer_name: typing.Optional[Name] = None, + subject_name: typing.Optional[Name] = None, + public_key: typing.Optional[CertificatePublicKeyTypes] = None, + serial_number: typing.Optional[int] = None, + not_valid_before: typing.Optional[datetime.datetime] = None, + not_valid_after: typing.Optional[datetime.datetime] = None, + extensions: typing.List[Extension[ExtensionType]] = [], + ) -> None: + self._version = Version.v3 + self._issuer_name = issuer_name + self._subject_name = subject_name + self._public_key = public_key + self._serial_number = serial_number + self._not_valid_before = not_valid_before + self._not_valid_after = not_valid_after + self._extensions = extensions + + def issuer_name(self, name: Name) -> CertificateBuilder: + """ + Sets the CA's distinguished name. + """ + if not isinstance(name, Name): + raise TypeError("Expecting x509.Name object.") + if self._issuer_name is not None: + raise ValueError("The issuer name may only be set once.") + return CertificateBuilder( + name, + self._subject_name, + self._public_key, + self._serial_number, + self._not_valid_before, + self._not_valid_after, + self._extensions, + ) + + def subject_name(self, name: Name) -> CertificateBuilder: + """ + Sets the requestor's distinguished name. + """ + if not isinstance(name, Name): + raise TypeError("Expecting x509.Name object.") + if self._subject_name is not None: + raise ValueError("The subject name may only be set once.") + return CertificateBuilder( + self._issuer_name, + name, + self._public_key, + self._serial_number, + self._not_valid_before, + self._not_valid_after, + self._extensions, + ) + + def public_key( + self, + key: CertificatePublicKeyTypes, + ) -> CertificateBuilder: + """ + Sets the requestor's public key (as found in the signing request). + """ + if not isinstance( + key, + ( + dsa.DSAPublicKey, + rsa.RSAPublicKey, + ec.EllipticCurvePublicKey, + ed25519.Ed25519PublicKey, + ed448.Ed448PublicKey, + x25519.X25519PublicKey, + x448.X448PublicKey, + ), + ): + raise TypeError( + "Expecting one of DSAPublicKey, RSAPublicKey," + " EllipticCurvePublicKey, Ed25519PublicKey," + " Ed448PublicKey, X25519PublicKey, or " + "X448PublicKey." + ) + if self._public_key is not None: + raise ValueError("The public key may only be set once.") + return CertificateBuilder( + self._issuer_name, + self._subject_name, + key, + self._serial_number, + self._not_valid_before, + self._not_valid_after, + self._extensions, + ) + + def serial_number(self, number: int) -> CertificateBuilder: + """ + Sets the certificate serial number. + """ + if not isinstance(number, int): + raise TypeError("Serial number must be of integral type.") + if self._serial_number is not None: + raise ValueError("The serial number may only be set once.") + if number <= 0: + raise ValueError("The serial number should be positive.") + + # ASN.1 integers are always signed, so most significant bit must be + # zero. + if number.bit_length() >= 160: # As defined in RFC 5280 + raise ValueError( + "The serial number should not be more than 159 " "bits." + ) + return CertificateBuilder( + self._issuer_name, + self._subject_name, + self._public_key, + number, + self._not_valid_before, + self._not_valid_after, + self._extensions, + ) + + def not_valid_before(self, time: datetime.datetime) -> CertificateBuilder: + """ + Sets the certificate activation time. + """ + if not isinstance(time, datetime.datetime): + raise TypeError("Expecting datetime object.") + if self._not_valid_before is not None: + raise ValueError("The not valid before may only be set once.") + time = _convert_to_naive_utc_time(time) + if time < _EARLIEST_UTC_TIME: + raise ValueError( + "The not valid before date must be on or after" + " 1950 January 1)." + ) + if self._not_valid_after is not None and time > self._not_valid_after: + raise ValueError( + "The not valid before date must be before the not valid after " + "date." + ) + return CertificateBuilder( + self._issuer_name, + self._subject_name, + self._public_key, + self._serial_number, + time, + self._not_valid_after, + self._extensions, + ) + + def not_valid_after(self, time: datetime.datetime) -> CertificateBuilder: + """ + Sets the certificate expiration time. + """ + if not isinstance(time, datetime.datetime): + raise TypeError("Expecting datetime object.") + if self._not_valid_after is not None: + raise ValueError("The not valid after may only be set once.") + time = _convert_to_naive_utc_time(time) + if time < _EARLIEST_UTC_TIME: + raise ValueError( + "The not valid after date must be on or after" + " 1950 January 1." + ) + if ( + self._not_valid_before is not None + and time < self._not_valid_before + ): + raise ValueError( + "The not valid after date must be after the not valid before " + "date." + ) + return CertificateBuilder( + self._issuer_name, + self._subject_name, + self._public_key, + self._serial_number, + self._not_valid_before, + time, + self._extensions, + ) + + def add_extension( + self, extval: ExtensionType, critical: bool + ) -> CertificateBuilder: + """ + Adds an X.509 extension to the certificate. + """ + if not isinstance(extval, ExtensionType): + raise TypeError("extension must be an ExtensionType") + + extension = Extension(extval.oid, critical, extval) + _reject_duplicate_extension(extension, self._extensions) + + return CertificateBuilder( + self._issuer_name, + self._subject_name, + self._public_key, + self._serial_number, + self._not_valid_before, + self._not_valid_after, + self._extensions + [extension], + ) + + def sign( + self, + private_key: CertificateIssuerPrivateKeyTypes, + algorithm: typing.Optional[_AllowedHashTypes], + backend: typing.Any = None, + *, + rsa_padding: typing.Optional[ + typing.Union[padding.PSS, padding.PKCS1v15] + ] = None, + ) -> Certificate: + """ + Signs the certificate using the CA's private key. + """ + if self._subject_name is None: + raise ValueError("A certificate must have a subject name") + + if self._issuer_name is None: + raise ValueError("A certificate must have an issuer name") + + if self._serial_number is None: + raise ValueError("A certificate must have a serial number") + + if self._not_valid_before is None: + raise ValueError("A certificate must have a not valid before time") + + if self._not_valid_after is None: + raise ValueError("A certificate must have a not valid after time") + + if self._public_key is None: + raise ValueError("A certificate must have a public key") + + if rsa_padding is not None: + if not isinstance(rsa_padding, (padding.PSS, padding.PKCS1v15)): + raise TypeError("Padding must be PSS or PKCS1v15") + if not isinstance(private_key, rsa.RSAPrivateKey): + raise TypeError("Padding is only supported for RSA keys") + + return rust_x509.create_x509_certificate( + self, private_key, algorithm, rsa_padding + ) + + +class CertificateRevocationListBuilder: + _extensions: typing.List[Extension[ExtensionType]] + _revoked_certificates: typing.List[RevokedCertificate] + + def __init__( + self, + issuer_name: typing.Optional[Name] = None, + last_update: typing.Optional[datetime.datetime] = None, + next_update: typing.Optional[datetime.datetime] = None, + extensions: typing.List[Extension[ExtensionType]] = [], + revoked_certificates: typing.List[RevokedCertificate] = [], + ): + self._issuer_name = issuer_name + self._last_update = last_update + self._next_update = next_update + self._extensions = extensions + self._revoked_certificates = revoked_certificates + + def issuer_name( + self, issuer_name: Name + ) -> CertificateRevocationListBuilder: + if not isinstance(issuer_name, Name): + raise TypeError("Expecting x509.Name object.") + if self._issuer_name is not None: + raise ValueError("The issuer name may only be set once.") + return CertificateRevocationListBuilder( + issuer_name, + self._last_update, + self._next_update, + self._extensions, + self._revoked_certificates, + ) + + def last_update( + self, last_update: datetime.datetime + ) -> CertificateRevocationListBuilder: + if not isinstance(last_update, datetime.datetime): + raise TypeError("Expecting datetime object.") + if self._last_update is not None: + raise ValueError("Last update may only be set once.") + last_update = _convert_to_naive_utc_time(last_update) + if last_update < _EARLIEST_UTC_TIME: + raise ValueError( + "The last update date must be on or after" " 1950 January 1." + ) + if self._next_update is not None and last_update > self._next_update: + raise ValueError( + "The last update date must be before the next update date." + ) + return CertificateRevocationListBuilder( + self._issuer_name, + last_update, + self._next_update, + self._extensions, + self._revoked_certificates, + ) + + def next_update( + self, next_update: datetime.datetime + ) -> CertificateRevocationListBuilder: + if not isinstance(next_update, datetime.datetime): + raise TypeError("Expecting datetime object.") + if self._next_update is not None: + raise ValueError("Last update may only be set once.") + next_update = _convert_to_naive_utc_time(next_update) + if next_update < _EARLIEST_UTC_TIME: + raise ValueError( + "The last update date must be on or after" " 1950 January 1." + ) + if self._last_update is not None and next_update < self._last_update: + raise ValueError( + "The next update date must be after the last update date." + ) + return CertificateRevocationListBuilder( + self._issuer_name, + self._last_update, + next_update, + self._extensions, + self._revoked_certificates, + ) + + def add_extension( + self, extval: ExtensionType, critical: bool + ) -> CertificateRevocationListBuilder: + """ + Adds an X.509 extension to the certificate revocation list. + """ + if not isinstance(extval, ExtensionType): + raise TypeError("extension must be an ExtensionType") + + extension = Extension(extval.oid, critical, extval) + _reject_duplicate_extension(extension, self._extensions) + return CertificateRevocationListBuilder( + self._issuer_name, + self._last_update, + self._next_update, + self._extensions + [extension], + self._revoked_certificates, + ) + + def add_revoked_certificate( + self, revoked_certificate: RevokedCertificate + ) -> CertificateRevocationListBuilder: + """ + Adds a revoked certificate to the CRL. + """ + if not isinstance(revoked_certificate, RevokedCertificate): + raise TypeError("Must be an instance of RevokedCertificate") + + return CertificateRevocationListBuilder( + self._issuer_name, + self._last_update, + self._next_update, + self._extensions, + self._revoked_certificates + [revoked_certificate], + ) + + def sign( + self, + private_key: CertificateIssuerPrivateKeyTypes, + algorithm: typing.Optional[_AllowedHashTypes], + backend: typing.Any = None, + ) -> CertificateRevocationList: + if self._issuer_name is None: + raise ValueError("A CRL must have an issuer name") + + if self._last_update is None: + raise ValueError("A CRL must have a last update time") + + if self._next_update is None: + raise ValueError("A CRL must have a next update time") + + return rust_x509.create_x509_crl(self, private_key, algorithm) + + +class RevokedCertificateBuilder: + def __init__( + self, + serial_number: typing.Optional[int] = None, + revocation_date: typing.Optional[datetime.datetime] = None, + extensions: typing.List[Extension[ExtensionType]] = [], + ): + self._serial_number = serial_number + self._revocation_date = revocation_date + self._extensions = extensions + + def serial_number(self, number: int) -> RevokedCertificateBuilder: + if not isinstance(number, int): + raise TypeError("Serial number must be of integral type.") + if self._serial_number is not None: + raise ValueError("The serial number may only be set once.") + if number <= 0: + raise ValueError("The serial number should be positive") + + # ASN.1 integers are always signed, so most significant bit must be + # zero. + if number.bit_length() >= 160: # As defined in RFC 5280 + raise ValueError( + "The serial number should not be more than 159 " "bits." + ) + return RevokedCertificateBuilder( + number, self._revocation_date, self._extensions + ) + + def revocation_date( + self, time: datetime.datetime + ) -> RevokedCertificateBuilder: + if not isinstance(time, datetime.datetime): + raise TypeError("Expecting datetime object.") + if self._revocation_date is not None: + raise ValueError("The revocation date may only be set once.") + time = _convert_to_naive_utc_time(time) + if time < _EARLIEST_UTC_TIME: + raise ValueError( + "The revocation date must be on or after" " 1950 January 1." + ) + return RevokedCertificateBuilder( + self._serial_number, time, self._extensions + ) + + def add_extension( + self, extval: ExtensionType, critical: bool + ) -> RevokedCertificateBuilder: + if not isinstance(extval, ExtensionType): + raise TypeError("extension must be an ExtensionType") + + extension = Extension(extval.oid, critical, extval) + _reject_duplicate_extension(extension, self._extensions) + return RevokedCertificateBuilder( + self._serial_number, + self._revocation_date, + self._extensions + [extension], + ) + + def build(self, backend: typing.Any = None) -> RevokedCertificate: + if self._serial_number is None: + raise ValueError("A revoked certificate must have a serial number") + if self._revocation_date is None: + raise ValueError( + "A revoked certificate must have a revocation date" + ) + return _RawRevokedCertificate( + self._serial_number, + self._revocation_date, + Extensions(self._extensions), + ) + + +def random_serial_number() -> int: + return int.from_bytes(os.urandom(20), "big") >> 1 diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/x509/certificate_transparency.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/x509/certificate_transparency.py new file mode 100644 index 0000000000000000000000000000000000000000..73647ee716fc1c36bf255347617308522b724e5d --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/x509/certificate_transparency.py @@ -0,0 +1,97 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc +import datetime + +from cryptography import utils +from cryptography.hazmat.bindings._rust import x509 as rust_x509 +from cryptography.hazmat.primitives.hashes import HashAlgorithm + + +class LogEntryType(utils.Enum): + X509_CERTIFICATE = 0 + PRE_CERTIFICATE = 1 + + +class Version(utils.Enum): + v1 = 0 + + +class SignatureAlgorithm(utils.Enum): + """ + Signature algorithms that are valid for SCTs. + + These are exactly the same as SignatureAlgorithm in RFC 5246 (TLS 1.2). + + See: + """ + + ANONYMOUS = 0 + RSA = 1 + DSA = 2 + ECDSA = 3 + + +class SignedCertificateTimestamp(metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def version(self) -> Version: + """ + Returns the SCT version. + """ + + @property + @abc.abstractmethod + def log_id(self) -> bytes: + """ + Returns an identifier indicating which log this SCT is for. + """ + + @property + @abc.abstractmethod + def timestamp(self) -> datetime.datetime: + """ + Returns the timestamp for this SCT. + """ + + @property + @abc.abstractmethod + def entry_type(self) -> LogEntryType: + """ + Returns whether this is an SCT for a certificate or pre-certificate. + """ + + @property + @abc.abstractmethod + def signature_hash_algorithm(self) -> HashAlgorithm: + """ + Returns the hash algorithm used for the SCT's signature. + """ + + @property + @abc.abstractmethod + def signature_algorithm(self) -> SignatureAlgorithm: + """ + Returns the signing algorithm used for the SCT's signature. + """ + + @property + @abc.abstractmethod + def signature(self) -> bytes: + """ + Returns the signature for this SCT. + """ + + @property + @abc.abstractmethod + def extension_bytes(self) -> bytes: + """ + Returns the raw bytes of any extensions for this SCT. + """ + + +SignedCertificateTimestamp.register(rust_x509.Sct) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/x509/extensions.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/x509/extensions.py new file mode 100644 index 0000000000000000000000000000000000000000..ac99592f55a73a62e70dae2fad3c696635129bdd --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/x509/extensions.py @@ -0,0 +1,2215 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc +import datetime +import hashlib +import ipaddress +import typing + +from cryptography import utils +from cryptography.hazmat.bindings._rust import asn1 +from cryptography.hazmat.bindings._rust import x509 as rust_x509 +from cryptography.hazmat.primitives import constant_time, serialization +from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePublicKey +from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey +from cryptography.hazmat.primitives.asymmetric.types import ( + CertificateIssuerPublicKeyTypes, + CertificatePublicKeyTypes, +) +from cryptography.x509.certificate_transparency import ( + SignedCertificateTimestamp, +) +from cryptography.x509.general_name import ( + DirectoryName, + DNSName, + GeneralName, + IPAddress, + OtherName, + RegisteredID, + RFC822Name, + UniformResourceIdentifier, + _IPAddressTypes, +) +from cryptography.x509.name import Name, RelativeDistinguishedName +from cryptography.x509.oid import ( + CRLEntryExtensionOID, + ExtensionOID, + ObjectIdentifier, + OCSPExtensionOID, +) + +ExtensionTypeVar = typing.TypeVar( + "ExtensionTypeVar", bound="ExtensionType", covariant=True +) + + +def _key_identifier_from_public_key( + public_key: CertificatePublicKeyTypes, +) -> bytes: + if isinstance(public_key, RSAPublicKey): + data = public_key.public_bytes( + serialization.Encoding.DER, + serialization.PublicFormat.PKCS1, + ) + elif isinstance(public_key, EllipticCurvePublicKey): + data = public_key.public_bytes( + serialization.Encoding.X962, + serialization.PublicFormat.UncompressedPoint, + ) + else: + # This is a very slow way to do this. + serialized = public_key.public_bytes( + serialization.Encoding.DER, + serialization.PublicFormat.SubjectPublicKeyInfo, + ) + data = asn1.parse_spki_for_data(serialized) + + return hashlib.sha1(data).digest() + + +def _make_sequence_methods(field_name: str): + def len_method(self) -> int: + return len(getattr(self, field_name)) + + def iter_method(self): + return iter(getattr(self, field_name)) + + def getitem_method(self, idx): + return getattr(self, field_name)[idx] + + return len_method, iter_method, getitem_method + + +class DuplicateExtension(Exception): + def __init__(self, msg: str, oid: ObjectIdentifier) -> None: + super().__init__(msg) + self.oid = oid + + +class ExtensionNotFound(Exception): + def __init__(self, msg: str, oid: ObjectIdentifier) -> None: + super().__init__(msg) + self.oid = oid + + +class ExtensionType(metaclass=abc.ABCMeta): + oid: typing.ClassVar[ObjectIdentifier] + + def public_bytes(self) -> bytes: + """ + Serializes the extension type to DER. + """ + raise NotImplementedError( + "public_bytes is not implemented for extension type {!r}".format( + self + ) + ) + + +class Extensions: + def __init__( + self, extensions: typing.Iterable[Extension[ExtensionType]] + ) -> None: + self._extensions = list(extensions) + + def get_extension_for_oid( + self, oid: ObjectIdentifier + ) -> Extension[ExtensionType]: + for ext in self: + if ext.oid == oid: + return ext + + raise ExtensionNotFound(f"No {oid} extension was found", oid) + + def get_extension_for_class( + self, extclass: typing.Type[ExtensionTypeVar] + ) -> Extension[ExtensionTypeVar]: + if extclass is UnrecognizedExtension: + raise TypeError( + "UnrecognizedExtension can't be used with " + "get_extension_for_class because more than one instance of the" + " class may be present." + ) + + for ext in self: + if isinstance(ext.value, extclass): + return ext + + raise ExtensionNotFound( + f"No {extclass} extension was found", extclass.oid + ) + + __len__, __iter__, __getitem__ = _make_sequence_methods("_extensions") + + def __repr__(self) -> str: + return f"" + + +class CRLNumber(ExtensionType): + oid = ExtensionOID.CRL_NUMBER + + def __init__(self, crl_number: int) -> None: + if not isinstance(crl_number, int): + raise TypeError("crl_number must be an integer") + + self._crl_number = crl_number + + def __eq__(self, other: object) -> bool: + if not isinstance(other, CRLNumber): + return NotImplemented + + return self.crl_number == other.crl_number + + def __hash__(self) -> int: + return hash(self.crl_number) + + def __repr__(self) -> str: + return f"" + + @property + def crl_number(self) -> int: + return self._crl_number + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class AuthorityKeyIdentifier(ExtensionType): + oid = ExtensionOID.AUTHORITY_KEY_IDENTIFIER + + def __init__( + self, + key_identifier: typing.Optional[bytes], + authority_cert_issuer: typing.Optional[typing.Iterable[GeneralName]], + authority_cert_serial_number: typing.Optional[int], + ) -> None: + if (authority_cert_issuer is None) != ( + authority_cert_serial_number is None + ): + raise ValueError( + "authority_cert_issuer and authority_cert_serial_number " + "must both be present or both None" + ) + + if authority_cert_issuer is not None: + authority_cert_issuer = list(authority_cert_issuer) + if not all( + isinstance(x, GeneralName) for x in authority_cert_issuer + ): + raise TypeError( + "authority_cert_issuer must be a list of GeneralName " + "objects" + ) + + if authority_cert_serial_number is not None and not isinstance( + authority_cert_serial_number, int + ): + raise TypeError("authority_cert_serial_number must be an integer") + + self._key_identifier = key_identifier + self._authority_cert_issuer = authority_cert_issuer + self._authority_cert_serial_number = authority_cert_serial_number + + # This takes a subset of CertificatePublicKeyTypes because an issuer + # cannot have an X25519/X448 key. This introduces some unfortunate + # asymmetry that requires typing users to explicitly + # narrow their type, but we should make this accurate and not just + # convenient. + @classmethod + def from_issuer_public_key( + cls, public_key: CertificateIssuerPublicKeyTypes + ) -> AuthorityKeyIdentifier: + digest = _key_identifier_from_public_key(public_key) + return cls( + key_identifier=digest, + authority_cert_issuer=None, + authority_cert_serial_number=None, + ) + + @classmethod + def from_issuer_subject_key_identifier( + cls, ski: SubjectKeyIdentifier + ) -> AuthorityKeyIdentifier: + return cls( + key_identifier=ski.digest, + authority_cert_issuer=None, + authority_cert_serial_number=None, + ) + + def __repr__(self) -> str: + return ( + "".format(self) + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, AuthorityKeyIdentifier): + return NotImplemented + + return ( + self.key_identifier == other.key_identifier + and self.authority_cert_issuer == other.authority_cert_issuer + and self.authority_cert_serial_number + == other.authority_cert_serial_number + ) + + def __hash__(self) -> int: + if self.authority_cert_issuer is None: + aci = None + else: + aci = tuple(self.authority_cert_issuer) + return hash( + (self.key_identifier, aci, self.authority_cert_serial_number) + ) + + @property + def key_identifier(self) -> typing.Optional[bytes]: + return self._key_identifier + + @property + def authority_cert_issuer( + self, + ) -> typing.Optional[typing.List[GeneralName]]: + return self._authority_cert_issuer + + @property + def authority_cert_serial_number(self) -> typing.Optional[int]: + return self._authority_cert_serial_number + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class SubjectKeyIdentifier(ExtensionType): + oid = ExtensionOID.SUBJECT_KEY_IDENTIFIER + + def __init__(self, digest: bytes) -> None: + self._digest = digest + + @classmethod + def from_public_key( + cls, public_key: CertificatePublicKeyTypes + ) -> SubjectKeyIdentifier: + return cls(_key_identifier_from_public_key(public_key)) + + @property + def digest(self) -> bytes: + return self._digest + + @property + def key_identifier(self) -> bytes: + return self._digest + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, SubjectKeyIdentifier): + return NotImplemented + + return constant_time.bytes_eq(self.digest, other.digest) + + def __hash__(self) -> int: + return hash(self.digest) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class AuthorityInformationAccess(ExtensionType): + oid = ExtensionOID.AUTHORITY_INFORMATION_ACCESS + + def __init__( + self, descriptions: typing.Iterable[AccessDescription] + ) -> None: + descriptions = list(descriptions) + if not all(isinstance(x, AccessDescription) for x in descriptions): + raise TypeError( + "Every item in the descriptions list must be an " + "AccessDescription" + ) + + self._descriptions = descriptions + + __len__, __iter__, __getitem__ = _make_sequence_methods("_descriptions") + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, AuthorityInformationAccess): + return NotImplemented + + return self._descriptions == other._descriptions + + def __hash__(self) -> int: + return hash(tuple(self._descriptions)) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class SubjectInformationAccess(ExtensionType): + oid = ExtensionOID.SUBJECT_INFORMATION_ACCESS + + def __init__( + self, descriptions: typing.Iterable[AccessDescription] + ) -> None: + descriptions = list(descriptions) + if not all(isinstance(x, AccessDescription) for x in descriptions): + raise TypeError( + "Every item in the descriptions list must be an " + "AccessDescription" + ) + + self._descriptions = descriptions + + __len__, __iter__, __getitem__ = _make_sequence_methods("_descriptions") + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, SubjectInformationAccess): + return NotImplemented + + return self._descriptions == other._descriptions + + def __hash__(self) -> int: + return hash(tuple(self._descriptions)) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class AccessDescription: + def __init__( + self, access_method: ObjectIdentifier, access_location: GeneralName + ) -> None: + if not isinstance(access_method, ObjectIdentifier): + raise TypeError("access_method must be an ObjectIdentifier") + + if not isinstance(access_location, GeneralName): + raise TypeError("access_location must be a GeneralName") + + self._access_method = access_method + self._access_location = access_location + + def __repr__(self) -> str: + return ( + "".format(self) + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, AccessDescription): + return NotImplemented + + return ( + self.access_method == other.access_method + and self.access_location == other.access_location + ) + + def __hash__(self) -> int: + return hash((self.access_method, self.access_location)) + + @property + def access_method(self) -> ObjectIdentifier: + return self._access_method + + @property + def access_location(self) -> GeneralName: + return self._access_location + + +class BasicConstraints(ExtensionType): + oid = ExtensionOID.BASIC_CONSTRAINTS + + def __init__(self, ca: bool, path_length: typing.Optional[int]) -> None: + if not isinstance(ca, bool): + raise TypeError("ca must be a boolean value") + + if path_length is not None and not ca: + raise ValueError("path_length must be None when ca is False") + + if path_length is not None and ( + not isinstance(path_length, int) or path_length < 0 + ): + raise TypeError( + "path_length must be a non-negative integer or None" + ) + + self._ca = ca + self._path_length = path_length + + @property + def ca(self) -> bool: + return self._ca + + @property + def path_length(self) -> typing.Optional[int]: + return self._path_length + + def __repr__(self) -> str: + return ( + "" + ).format(self) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, BasicConstraints): + return NotImplemented + + return self.ca == other.ca and self.path_length == other.path_length + + def __hash__(self) -> int: + return hash((self.ca, self.path_length)) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class DeltaCRLIndicator(ExtensionType): + oid = ExtensionOID.DELTA_CRL_INDICATOR + + def __init__(self, crl_number: int) -> None: + if not isinstance(crl_number, int): + raise TypeError("crl_number must be an integer") + + self._crl_number = crl_number + + @property + def crl_number(self) -> int: + return self._crl_number + + def __eq__(self, other: object) -> bool: + if not isinstance(other, DeltaCRLIndicator): + return NotImplemented + + return self.crl_number == other.crl_number + + def __hash__(self) -> int: + return hash(self.crl_number) + + def __repr__(self) -> str: + return f"" + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class CRLDistributionPoints(ExtensionType): + oid = ExtensionOID.CRL_DISTRIBUTION_POINTS + + def __init__( + self, distribution_points: typing.Iterable[DistributionPoint] + ) -> None: + distribution_points = list(distribution_points) + if not all( + isinstance(x, DistributionPoint) for x in distribution_points + ): + raise TypeError( + "distribution_points must be a list of DistributionPoint " + "objects" + ) + + self._distribution_points = distribution_points + + __len__, __iter__, __getitem__ = _make_sequence_methods( + "_distribution_points" + ) + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, CRLDistributionPoints): + return NotImplemented + + return self._distribution_points == other._distribution_points + + def __hash__(self) -> int: + return hash(tuple(self._distribution_points)) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class FreshestCRL(ExtensionType): + oid = ExtensionOID.FRESHEST_CRL + + def __init__( + self, distribution_points: typing.Iterable[DistributionPoint] + ) -> None: + distribution_points = list(distribution_points) + if not all( + isinstance(x, DistributionPoint) for x in distribution_points + ): + raise TypeError( + "distribution_points must be a list of DistributionPoint " + "objects" + ) + + self._distribution_points = distribution_points + + __len__, __iter__, __getitem__ = _make_sequence_methods( + "_distribution_points" + ) + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, FreshestCRL): + return NotImplemented + + return self._distribution_points == other._distribution_points + + def __hash__(self) -> int: + return hash(tuple(self._distribution_points)) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class DistributionPoint: + def __init__( + self, + full_name: typing.Optional[typing.Iterable[GeneralName]], + relative_name: typing.Optional[RelativeDistinguishedName], + reasons: typing.Optional[typing.FrozenSet[ReasonFlags]], + crl_issuer: typing.Optional[typing.Iterable[GeneralName]], + ) -> None: + if full_name and relative_name: + raise ValueError( + "You cannot provide both full_name and relative_name, at " + "least one must be None." + ) + if not full_name and not relative_name and not crl_issuer: + raise ValueError( + "Either full_name, relative_name or crl_issuer must be " + "provided." + ) + + if full_name is not None: + full_name = list(full_name) + if not all(isinstance(x, GeneralName) for x in full_name): + raise TypeError( + "full_name must be a list of GeneralName objects" + ) + + if relative_name: + if not isinstance(relative_name, RelativeDistinguishedName): + raise TypeError( + "relative_name must be a RelativeDistinguishedName" + ) + + if crl_issuer is not None: + crl_issuer = list(crl_issuer) + if not all(isinstance(x, GeneralName) for x in crl_issuer): + raise TypeError( + "crl_issuer must be None or a list of general names" + ) + + if reasons and ( + not isinstance(reasons, frozenset) + or not all(isinstance(x, ReasonFlags) for x in reasons) + ): + raise TypeError("reasons must be None or frozenset of ReasonFlags") + + if reasons and ( + ReasonFlags.unspecified in reasons + or ReasonFlags.remove_from_crl in reasons + ): + raise ValueError( + "unspecified and remove_from_crl are not valid reasons in a " + "DistributionPoint" + ) + + self._full_name = full_name + self._relative_name = relative_name + self._reasons = reasons + self._crl_issuer = crl_issuer + + def __repr__(self) -> str: + return ( + "".format(self) + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, DistributionPoint): + return NotImplemented + + return ( + self.full_name == other.full_name + and self.relative_name == other.relative_name + and self.reasons == other.reasons + and self.crl_issuer == other.crl_issuer + ) + + def __hash__(self) -> int: + if self.full_name is not None: + fn: typing.Optional[typing.Tuple[GeneralName, ...]] = tuple( + self.full_name + ) + else: + fn = None + + if self.crl_issuer is not None: + crl_issuer: typing.Optional[ + typing.Tuple[GeneralName, ...] + ] = tuple(self.crl_issuer) + else: + crl_issuer = None + + return hash((fn, self.relative_name, self.reasons, crl_issuer)) + + @property + def full_name(self) -> typing.Optional[typing.List[GeneralName]]: + return self._full_name + + @property + def relative_name(self) -> typing.Optional[RelativeDistinguishedName]: + return self._relative_name + + @property + def reasons(self) -> typing.Optional[typing.FrozenSet[ReasonFlags]]: + return self._reasons + + @property + def crl_issuer(self) -> typing.Optional[typing.List[GeneralName]]: + return self._crl_issuer + + +class ReasonFlags(utils.Enum): + unspecified = "unspecified" + key_compromise = "keyCompromise" + ca_compromise = "cACompromise" + affiliation_changed = "affiliationChanged" + superseded = "superseded" + cessation_of_operation = "cessationOfOperation" + certificate_hold = "certificateHold" + privilege_withdrawn = "privilegeWithdrawn" + aa_compromise = "aACompromise" + remove_from_crl = "removeFromCRL" + + +# These are distribution point bit string mappings. Not to be confused with +# CRLReason reason flags bit string mappings. +# ReasonFlags ::= BIT STRING { +# unused (0), +# keyCompromise (1), +# cACompromise (2), +# affiliationChanged (3), +# superseded (4), +# cessationOfOperation (5), +# certificateHold (6), +# privilegeWithdrawn (7), +# aACompromise (8) } +_REASON_BIT_MAPPING = { + 1: ReasonFlags.key_compromise, + 2: ReasonFlags.ca_compromise, + 3: ReasonFlags.affiliation_changed, + 4: ReasonFlags.superseded, + 5: ReasonFlags.cessation_of_operation, + 6: ReasonFlags.certificate_hold, + 7: ReasonFlags.privilege_withdrawn, + 8: ReasonFlags.aa_compromise, +} + +_CRLREASONFLAGS = { + ReasonFlags.key_compromise: 1, + ReasonFlags.ca_compromise: 2, + ReasonFlags.affiliation_changed: 3, + ReasonFlags.superseded: 4, + ReasonFlags.cessation_of_operation: 5, + ReasonFlags.certificate_hold: 6, + ReasonFlags.privilege_withdrawn: 7, + ReasonFlags.aa_compromise: 8, +} + + +class PolicyConstraints(ExtensionType): + oid = ExtensionOID.POLICY_CONSTRAINTS + + def __init__( + self, + require_explicit_policy: typing.Optional[int], + inhibit_policy_mapping: typing.Optional[int], + ) -> None: + if require_explicit_policy is not None and not isinstance( + require_explicit_policy, int + ): + raise TypeError( + "require_explicit_policy must be a non-negative integer or " + "None" + ) + + if inhibit_policy_mapping is not None and not isinstance( + inhibit_policy_mapping, int + ): + raise TypeError( + "inhibit_policy_mapping must be a non-negative integer or None" + ) + + if inhibit_policy_mapping is None and require_explicit_policy is None: + raise ValueError( + "At least one of require_explicit_policy and " + "inhibit_policy_mapping must not be None" + ) + + self._require_explicit_policy = require_explicit_policy + self._inhibit_policy_mapping = inhibit_policy_mapping + + def __repr__(self) -> str: + return ( + "".format(self) + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, PolicyConstraints): + return NotImplemented + + return ( + self.require_explicit_policy == other.require_explicit_policy + and self.inhibit_policy_mapping == other.inhibit_policy_mapping + ) + + def __hash__(self) -> int: + return hash( + (self.require_explicit_policy, self.inhibit_policy_mapping) + ) + + @property + def require_explicit_policy(self) -> typing.Optional[int]: + return self._require_explicit_policy + + @property + def inhibit_policy_mapping(self) -> typing.Optional[int]: + return self._inhibit_policy_mapping + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class CertificatePolicies(ExtensionType): + oid = ExtensionOID.CERTIFICATE_POLICIES + + def __init__(self, policies: typing.Iterable[PolicyInformation]) -> None: + policies = list(policies) + if not all(isinstance(x, PolicyInformation) for x in policies): + raise TypeError( + "Every item in the policies list must be a " + "PolicyInformation" + ) + + self._policies = policies + + __len__, __iter__, __getitem__ = _make_sequence_methods("_policies") + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, CertificatePolicies): + return NotImplemented + + return self._policies == other._policies + + def __hash__(self) -> int: + return hash(tuple(self._policies)) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class PolicyInformation: + def __init__( + self, + policy_identifier: ObjectIdentifier, + policy_qualifiers: typing.Optional[ + typing.Iterable[typing.Union[str, UserNotice]] + ], + ) -> None: + if not isinstance(policy_identifier, ObjectIdentifier): + raise TypeError("policy_identifier must be an ObjectIdentifier") + + self._policy_identifier = policy_identifier + + if policy_qualifiers is not None: + policy_qualifiers = list(policy_qualifiers) + if not all( + isinstance(x, (str, UserNotice)) for x in policy_qualifiers + ): + raise TypeError( + "policy_qualifiers must be a list of strings and/or " + "UserNotice objects or None" + ) + + self._policy_qualifiers = policy_qualifiers + + def __repr__(self) -> str: + return ( + "".format(self) + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, PolicyInformation): + return NotImplemented + + return ( + self.policy_identifier == other.policy_identifier + and self.policy_qualifiers == other.policy_qualifiers + ) + + def __hash__(self) -> int: + if self.policy_qualifiers is not None: + pq: typing.Optional[ + typing.Tuple[typing.Union[str, UserNotice], ...] + ] = tuple(self.policy_qualifiers) + else: + pq = None + + return hash((self.policy_identifier, pq)) + + @property + def policy_identifier(self) -> ObjectIdentifier: + return self._policy_identifier + + @property + def policy_qualifiers( + self, + ) -> typing.Optional[typing.List[typing.Union[str, UserNotice]]]: + return self._policy_qualifiers + + +class UserNotice: + def __init__( + self, + notice_reference: typing.Optional[NoticeReference], + explicit_text: typing.Optional[str], + ) -> None: + if notice_reference and not isinstance( + notice_reference, NoticeReference + ): + raise TypeError( + "notice_reference must be None or a NoticeReference" + ) + + self._notice_reference = notice_reference + self._explicit_text = explicit_text + + def __repr__(self) -> str: + return ( + "".format(self) + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, UserNotice): + return NotImplemented + + return ( + self.notice_reference == other.notice_reference + and self.explicit_text == other.explicit_text + ) + + def __hash__(self) -> int: + return hash((self.notice_reference, self.explicit_text)) + + @property + def notice_reference(self) -> typing.Optional[NoticeReference]: + return self._notice_reference + + @property + def explicit_text(self) -> typing.Optional[str]: + return self._explicit_text + + +class NoticeReference: + def __init__( + self, + organization: typing.Optional[str], + notice_numbers: typing.Iterable[int], + ) -> None: + self._organization = organization + notice_numbers = list(notice_numbers) + if not all(isinstance(x, int) for x in notice_numbers): + raise TypeError("notice_numbers must be a list of integers") + + self._notice_numbers = notice_numbers + + def __repr__(self) -> str: + return ( + "".format(self) + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, NoticeReference): + return NotImplemented + + return ( + self.organization == other.organization + and self.notice_numbers == other.notice_numbers + ) + + def __hash__(self) -> int: + return hash((self.organization, tuple(self.notice_numbers))) + + @property + def organization(self) -> typing.Optional[str]: + return self._organization + + @property + def notice_numbers(self) -> typing.List[int]: + return self._notice_numbers + + +class ExtendedKeyUsage(ExtensionType): + oid = ExtensionOID.EXTENDED_KEY_USAGE + + def __init__(self, usages: typing.Iterable[ObjectIdentifier]) -> None: + usages = list(usages) + if not all(isinstance(x, ObjectIdentifier) for x in usages): + raise TypeError( + "Every item in the usages list must be an ObjectIdentifier" + ) + + self._usages = usages + + __len__, __iter__, __getitem__ = _make_sequence_methods("_usages") + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, ExtendedKeyUsage): + return NotImplemented + + return self._usages == other._usages + + def __hash__(self) -> int: + return hash(tuple(self._usages)) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class OCSPNoCheck(ExtensionType): + oid = ExtensionOID.OCSP_NO_CHECK + + def __eq__(self, other: object) -> bool: + if not isinstance(other, OCSPNoCheck): + return NotImplemented + + return True + + def __hash__(self) -> int: + return hash(OCSPNoCheck) + + def __repr__(self) -> str: + return "" + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class PrecertPoison(ExtensionType): + oid = ExtensionOID.PRECERT_POISON + + def __eq__(self, other: object) -> bool: + if not isinstance(other, PrecertPoison): + return NotImplemented + + return True + + def __hash__(self) -> int: + return hash(PrecertPoison) + + def __repr__(self) -> str: + return "" + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class TLSFeature(ExtensionType): + oid = ExtensionOID.TLS_FEATURE + + def __init__(self, features: typing.Iterable[TLSFeatureType]) -> None: + features = list(features) + if ( + not all(isinstance(x, TLSFeatureType) for x in features) + or len(features) == 0 + ): + raise TypeError( + "features must be a list of elements from the TLSFeatureType " + "enum" + ) + + self._features = features + + __len__, __iter__, __getitem__ = _make_sequence_methods("_features") + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, TLSFeature): + return NotImplemented + + return self._features == other._features + + def __hash__(self) -> int: + return hash(tuple(self._features)) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class TLSFeatureType(utils.Enum): + # status_request is defined in RFC 6066 and is used for what is commonly + # called OCSP Must-Staple when present in the TLS Feature extension in an + # X.509 certificate. + status_request = 5 + # status_request_v2 is defined in RFC 6961 and allows multiple OCSP + # responses to be provided. It is not currently in use by clients or + # servers. + status_request_v2 = 17 + + +_TLS_FEATURE_TYPE_TO_ENUM = {x.value: x for x in TLSFeatureType} + + +class InhibitAnyPolicy(ExtensionType): + oid = ExtensionOID.INHIBIT_ANY_POLICY + + def __init__(self, skip_certs: int) -> None: + if not isinstance(skip_certs, int): + raise TypeError("skip_certs must be an integer") + + if skip_certs < 0: + raise ValueError("skip_certs must be a non-negative integer") + + self._skip_certs = skip_certs + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, InhibitAnyPolicy): + return NotImplemented + + return self.skip_certs == other.skip_certs + + def __hash__(self) -> int: + return hash(self.skip_certs) + + @property + def skip_certs(self) -> int: + return self._skip_certs + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class KeyUsage(ExtensionType): + oid = ExtensionOID.KEY_USAGE + + def __init__( + self, + digital_signature: bool, + content_commitment: bool, + key_encipherment: bool, + data_encipherment: bool, + key_agreement: bool, + key_cert_sign: bool, + crl_sign: bool, + encipher_only: bool, + decipher_only: bool, + ) -> None: + if not key_agreement and (encipher_only or decipher_only): + raise ValueError( + "encipher_only and decipher_only can only be true when " + "key_agreement is true" + ) + + self._digital_signature = digital_signature + self._content_commitment = content_commitment + self._key_encipherment = key_encipherment + self._data_encipherment = data_encipherment + self._key_agreement = key_agreement + self._key_cert_sign = key_cert_sign + self._crl_sign = crl_sign + self._encipher_only = encipher_only + self._decipher_only = decipher_only + + @property + def digital_signature(self) -> bool: + return self._digital_signature + + @property + def content_commitment(self) -> bool: + return self._content_commitment + + @property + def key_encipherment(self) -> bool: + return self._key_encipherment + + @property + def data_encipherment(self) -> bool: + return self._data_encipherment + + @property + def key_agreement(self) -> bool: + return self._key_agreement + + @property + def key_cert_sign(self) -> bool: + return self._key_cert_sign + + @property + def crl_sign(self) -> bool: + return self._crl_sign + + @property + def encipher_only(self) -> bool: + if not self.key_agreement: + raise ValueError( + "encipher_only is undefined unless key_agreement is true" + ) + else: + return self._encipher_only + + @property + def decipher_only(self) -> bool: + if not self.key_agreement: + raise ValueError( + "decipher_only is undefined unless key_agreement is true" + ) + else: + return self._decipher_only + + def __repr__(self) -> str: + try: + encipher_only = self.encipher_only + decipher_only = self.decipher_only + except ValueError: + # Users found None confusing because even though encipher/decipher + # have no meaning unless key_agreement is true, to construct an + # instance of the class you still need to pass False. + encipher_only = False + decipher_only = False + + return ( + "" + ).format(self, encipher_only, decipher_only) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, KeyUsage): + return NotImplemented + + return ( + self.digital_signature == other.digital_signature + and self.content_commitment == other.content_commitment + and self.key_encipherment == other.key_encipherment + and self.data_encipherment == other.data_encipherment + and self.key_agreement == other.key_agreement + and self.key_cert_sign == other.key_cert_sign + and self.crl_sign == other.crl_sign + and self._encipher_only == other._encipher_only + and self._decipher_only == other._decipher_only + ) + + def __hash__(self) -> int: + return hash( + ( + self.digital_signature, + self.content_commitment, + self.key_encipherment, + self.data_encipherment, + self.key_agreement, + self.key_cert_sign, + self.crl_sign, + self._encipher_only, + self._decipher_only, + ) + ) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class NameConstraints(ExtensionType): + oid = ExtensionOID.NAME_CONSTRAINTS + + def __init__( + self, + permitted_subtrees: typing.Optional[typing.Iterable[GeneralName]], + excluded_subtrees: typing.Optional[typing.Iterable[GeneralName]], + ) -> None: + if permitted_subtrees is not None: + permitted_subtrees = list(permitted_subtrees) + if not permitted_subtrees: + raise ValueError( + "permitted_subtrees must be a non-empty list or None" + ) + if not all(isinstance(x, GeneralName) for x in permitted_subtrees): + raise TypeError( + "permitted_subtrees must be a list of GeneralName objects " + "or None" + ) + + self._validate_tree(permitted_subtrees) + + if excluded_subtrees is not None: + excluded_subtrees = list(excluded_subtrees) + if not excluded_subtrees: + raise ValueError( + "excluded_subtrees must be a non-empty list or None" + ) + if not all(isinstance(x, GeneralName) for x in excluded_subtrees): + raise TypeError( + "excluded_subtrees must be a list of GeneralName objects " + "or None" + ) + + self._validate_tree(excluded_subtrees) + + if permitted_subtrees is None and excluded_subtrees is None: + raise ValueError( + "At least one of permitted_subtrees and excluded_subtrees " + "must not be None" + ) + + self._permitted_subtrees = permitted_subtrees + self._excluded_subtrees = excluded_subtrees + + def __eq__(self, other: object) -> bool: + if not isinstance(other, NameConstraints): + return NotImplemented + + return ( + self.excluded_subtrees == other.excluded_subtrees + and self.permitted_subtrees == other.permitted_subtrees + ) + + def _validate_tree(self, tree: typing.Iterable[GeneralName]) -> None: + self._validate_ip_name(tree) + self._validate_dns_name(tree) + + def _validate_ip_name(self, tree: typing.Iterable[GeneralName]) -> None: + if any( + isinstance(name, IPAddress) + and not isinstance( + name.value, (ipaddress.IPv4Network, ipaddress.IPv6Network) + ) + for name in tree + ): + raise TypeError( + "IPAddress name constraints must be an IPv4Network or" + " IPv6Network object" + ) + + def _validate_dns_name(self, tree: typing.Iterable[GeneralName]) -> None: + if any( + isinstance(name, DNSName) and "*" in name.value for name in tree + ): + raise ValueError( + "DNSName name constraints must not contain the '*' wildcard" + " character" + ) + + def __repr__(self) -> str: + return ( + "".format(self) + ) + + def __hash__(self) -> int: + if self.permitted_subtrees is not None: + ps: typing.Optional[typing.Tuple[GeneralName, ...]] = tuple( + self.permitted_subtrees + ) + else: + ps = None + + if self.excluded_subtrees is not None: + es: typing.Optional[typing.Tuple[GeneralName, ...]] = tuple( + self.excluded_subtrees + ) + else: + es = None + + return hash((ps, es)) + + @property + def permitted_subtrees( + self, + ) -> typing.Optional[typing.List[GeneralName]]: + return self._permitted_subtrees + + @property + def excluded_subtrees( + self, + ) -> typing.Optional[typing.List[GeneralName]]: + return self._excluded_subtrees + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class Extension(typing.Generic[ExtensionTypeVar]): + def __init__( + self, oid: ObjectIdentifier, critical: bool, value: ExtensionTypeVar + ) -> None: + if not isinstance(oid, ObjectIdentifier): + raise TypeError( + "oid argument must be an ObjectIdentifier instance." + ) + + if not isinstance(critical, bool): + raise TypeError("critical must be a boolean value") + + self._oid = oid + self._critical = critical + self._value = value + + @property + def oid(self) -> ObjectIdentifier: + return self._oid + + @property + def critical(self) -> bool: + return self._critical + + @property + def value(self) -> ExtensionTypeVar: + return self._value + + def __repr__(self) -> str: + return ( + "" + ).format(self) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, Extension): + return NotImplemented + + return ( + self.oid == other.oid + and self.critical == other.critical + and self.value == other.value + ) + + def __hash__(self) -> int: + return hash((self.oid, self.critical, self.value)) + + +class GeneralNames: + def __init__(self, general_names: typing.Iterable[GeneralName]) -> None: + general_names = list(general_names) + if not all(isinstance(x, GeneralName) for x in general_names): + raise TypeError( + "Every item in the general_names list must be an " + "object conforming to the GeneralName interface" + ) + + self._general_names = general_names + + __len__, __iter__, __getitem__ = _make_sequence_methods("_general_names") + + @typing.overload + def get_values_for_type( + self, + type: typing.Union[ + typing.Type[DNSName], + typing.Type[UniformResourceIdentifier], + typing.Type[RFC822Name], + ], + ) -> typing.List[str]: + ... + + @typing.overload + def get_values_for_type( + self, + type: typing.Type[DirectoryName], + ) -> typing.List[Name]: + ... + + @typing.overload + def get_values_for_type( + self, + type: typing.Type[RegisteredID], + ) -> typing.List[ObjectIdentifier]: + ... + + @typing.overload + def get_values_for_type( + self, type: typing.Type[IPAddress] + ) -> typing.List[_IPAddressTypes]: + ... + + @typing.overload + def get_values_for_type( + self, type: typing.Type[OtherName] + ) -> typing.List[OtherName]: + ... + + def get_values_for_type( + self, + type: typing.Union[ + typing.Type[DNSName], + typing.Type[DirectoryName], + typing.Type[IPAddress], + typing.Type[OtherName], + typing.Type[RFC822Name], + typing.Type[RegisteredID], + typing.Type[UniformResourceIdentifier], + ], + ) -> typing.Union[ + typing.List[_IPAddressTypes], + typing.List[str], + typing.List[OtherName], + typing.List[Name], + typing.List[ObjectIdentifier], + ]: + # Return the value of each GeneralName, except for OtherName instances + # which we return directly because it has two important properties not + # just one value. + objs = (i for i in self if isinstance(i, type)) + if type != OtherName: + return [i.value for i in objs] + return list(objs) + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, GeneralNames): + return NotImplemented + + return self._general_names == other._general_names + + def __hash__(self) -> int: + return hash(tuple(self._general_names)) + + +class SubjectAlternativeName(ExtensionType): + oid = ExtensionOID.SUBJECT_ALTERNATIVE_NAME + + def __init__(self, general_names: typing.Iterable[GeneralName]) -> None: + self._general_names = GeneralNames(general_names) + + __len__, __iter__, __getitem__ = _make_sequence_methods("_general_names") + + @typing.overload + def get_values_for_type( + self, + type: typing.Union[ + typing.Type[DNSName], + typing.Type[UniformResourceIdentifier], + typing.Type[RFC822Name], + ], + ) -> typing.List[str]: + ... + + @typing.overload + def get_values_for_type( + self, + type: typing.Type[DirectoryName], + ) -> typing.List[Name]: + ... + + @typing.overload + def get_values_for_type( + self, + type: typing.Type[RegisteredID], + ) -> typing.List[ObjectIdentifier]: + ... + + @typing.overload + def get_values_for_type( + self, type: typing.Type[IPAddress] + ) -> typing.List[_IPAddressTypes]: + ... + + @typing.overload + def get_values_for_type( + self, type: typing.Type[OtherName] + ) -> typing.List[OtherName]: + ... + + def get_values_for_type( + self, + type: typing.Union[ + typing.Type[DNSName], + typing.Type[DirectoryName], + typing.Type[IPAddress], + typing.Type[OtherName], + typing.Type[RFC822Name], + typing.Type[RegisteredID], + typing.Type[UniformResourceIdentifier], + ], + ) -> typing.Union[ + typing.List[_IPAddressTypes], + typing.List[str], + typing.List[OtherName], + typing.List[Name], + typing.List[ObjectIdentifier], + ]: + return self._general_names.get_values_for_type(type) + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, SubjectAlternativeName): + return NotImplemented + + return self._general_names == other._general_names + + def __hash__(self) -> int: + return hash(self._general_names) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class IssuerAlternativeName(ExtensionType): + oid = ExtensionOID.ISSUER_ALTERNATIVE_NAME + + def __init__(self, general_names: typing.Iterable[GeneralName]) -> None: + self._general_names = GeneralNames(general_names) + + __len__, __iter__, __getitem__ = _make_sequence_methods("_general_names") + + @typing.overload + def get_values_for_type( + self, + type: typing.Union[ + typing.Type[DNSName], + typing.Type[UniformResourceIdentifier], + typing.Type[RFC822Name], + ], + ) -> typing.List[str]: + ... + + @typing.overload + def get_values_for_type( + self, + type: typing.Type[DirectoryName], + ) -> typing.List[Name]: + ... + + @typing.overload + def get_values_for_type( + self, + type: typing.Type[RegisteredID], + ) -> typing.List[ObjectIdentifier]: + ... + + @typing.overload + def get_values_for_type( + self, type: typing.Type[IPAddress] + ) -> typing.List[_IPAddressTypes]: + ... + + @typing.overload + def get_values_for_type( + self, type: typing.Type[OtherName] + ) -> typing.List[OtherName]: + ... + + def get_values_for_type( + self, + type: typing.Union[ + typing.Type[DNSName], + typing.Type[DirectoryName], + typing.Type[IPAddress], + typing.Type[OtherName], + typing.Type[RFC822Name], + typing.Type[RegisteredID], + typing.Type[UniformResourceIdentifier], + ], + ) -> typing.Union[ + typing.List[_IPAddressTypes], + typing.List[str], + typing.List[OtherName], + typing.List[Name], + typing.List[ObjectIdentifier], + ]: + return self._general_names.get_values_for_type(type) + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, IssuerAlternativeName): + return NotImplemented + + return self._general_names == other._general_names + + def __hash__(self) -> int: + return hash(self._general_names) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class CertificateIssuer(ExtensionType): + oid = CRLEntryExtensionOID.CERTIFICATE_ISSUER + + def __init__(self, general_names: typing.Iterable[GeneralName]) -> None: + self._general_names = GeneralNames(general_names) + + __len__, __iter__, __getitem__ = _make_sequence_methods("_general_names") + + @typing.overload + def get_values_for_type( + self, + type: typing.Union[ + typing.Type[DNSName], + typing.Type[UniformResourceIdentifier], + typing.Type[RFC822Name], + ], + ) -> typing.List[str]: + ... + + @typing.overload + def get_values_for_type( + self, + type: typing.Type[DirectoryName], + ) -> typing.List[Name]: + ... + + @typing.overload + def get_values_for_type( + self, + type: typing.Type[RegisteredID], + ) -> typing.List[ObjectIdentifier]: + ... + + @typing.overload + def get_values_for_type( + self, type: typing.Type[IPAddress] + ) -> typing.List[_IPAddressTypes]: + ... + + @typing.overload + def get_values_for_type( + self, type: typing.Type[OtherName] + ) -> typing.List[OtherName]: + ... + + def get_values_for_type( + self, + type: typing.Union[ + typing.Type[DNSName], + typing.Type[DirectoryName], + typing.Type[IPAddress], + typing.Type[OtherName], + typing.Type[RFC822Name], + typing.Type[RegisteredID], + typing.Type[UniformResourceIdentifier], + ], + ) -> typing.Union[ + typing.List[_IPAddressTypes], + typing.List[str], + typing.List[OtherName], + typing.List[Name], + typing.List[ObjectIdentifier], + ]: + return self._general_names.get_values_for_type(type) + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, CertificateIssuer): + return NotImplemented + + return self._general_names == other._general_names + + def __hash__(self) -> int: + return hash(self._general_names) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class CRLReason(ExtensionType): + oid = CRLEntryExtensionOID.CRL_REASON + + def __init__(self, reason: ReasonFlags) -> None: + if not isinstance(reason, ReasonFlags): + raise TypeError("reason must be an element from ReasonFlags") + + self._reason = reason + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, CRLReason): + return NotImplemented + + return self.reason == other.reason + + def __hash__(self) -> int: + return hash(self.reason) + + @property + def reason(self) -> ReasonFlags: + return self._reason + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class InvalidityDate(ExtensionType): + oid = CRLEntryExtensionOID.INVALIDITY_DATE + + def __init__(self, invalidity_date: datetime.datetime) -> None: + if not isinstance(invalidity_date, datetime.datetime): + raise TypeError("invalidity_date must be a datetime.datetime") + + self._invalidity_date = invalidity_date + + def __repr__(self) -> str: + return "".format( + self._invalidity_date + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, InvalidityDate): + return NotImplemented + + return self.invalidity_date == other.invalidity_date + + def __hash__(self) -> int: + return hash(self.invalidity_date) + + @property + def invalidity_date(self) -> datetime.datetime: + return self._invalidity_date + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class PrecertificateSignedCertificateTimestamps(ExtensionType): + oid = ExtensionOID.PRECERT_SIGNED_CERTIFICATE_TIMESTAMPS + + def __init__( + self, + signed_certificate_timestamps: typing.Iterable[ + SignedCertificateTimestamp + ], + ) -> None: + signed_certificate_timestamps = list(signed_certificate_timestamps) + if not all( + isinstance(sct, SignedCertificateTimestamp) + for sct in signed_certificate_timestamps + ): + raise TypeError( + "Every item in the signed_certificate_timestamps list must be " + "a SignedCertificateTimestamp" + ) + self._signed_certificate_timestamps = signed_certificate_timestamps + + __len__, __iter__, __getitem__ = _make_sequence_methods( + "_signed_certificate_timestamps" + ) + + def __repr__(self) -> str: + return "".format( + list(self) + ) + + def __hash__(self) -> int: + return hash(tuple(self._signed_certificate_timestamps)) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, PrecertificateSignedCertificateTimestamps): + return NotImplemented + + return ( + self._signed_certificate_timestamps + == other._signed_certificate_timestamps + ) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class SignedCertificateTimestamps(ExtensionType): + oid = ExtensionOID.SIGNED_CERTIFICATE_TIMESTAMPS + + def __init__( + self, + signed_certificate_timestamps: typing.Iterable[ + SignedCertificateTimestamp + ], + ) -> None: + signed_certificate_timestamps = list(signed_certificate_timestamps) + if not all( + isinstance(sct, SignedCertificateTimestamp) + for sct in signed_certificate_timestamps + ): + raise TypeError( + "Every item in the signed_certificate_timestamps list must be " + "a SignedCertificateTimestamp" + ) + self._signed_certificate_timestamps = signed_certificate_timestamps + + __len__, __iter__, __getitem__ = _make_sequence_methods( + "_signed_certificate_timestamps" + ) + + def __repr__(self) -> str: + return f"" + + def __hash__(self) -> int: + return hash(tuple(self._signed_certificate_timestamps)) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, SignedCertificateTimestamps): + return NotImplemented + + return ( + self._signed_certificate_timestamps + == other._signed_certificate_timestamps + ) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class OCSPNonce(ExtensionType): + oid = OCSPExtensionOID.NONCE + + def __init__(self, nonce: bytes) -> None: + if not isinstance(nonce, bytes): + raise TypeError("nonce must be bytes") + + self._nonce = nonce + + def __eq__(self, other: object) -> bool: + if not isinstance(other, OCSPNonce): + return NotImplemented + + return self.nonce == other.nonce + + def __hash__(self) -> int: + return hash(self.nonce) + + def __repr__(self) -> str: + return f"" + + @property + def nonce(self) -> bytes: + return self._nonce + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class OCSPAcceptableResponses(ExtensionType): + oid = OCSPExtensionOID.ACCEPTABLE_RESPONSES + + def __init__(self, responses: typing.Iterable[ObjectIdentifier]) -> None: + responses = list(responses) + if any(not isinstance(r, ObjectIdentifier) for r in responses): + raise TypeError("All responses must be ObjectIdentifiers") + + self._responses = responses + + def __eq__(self, other: object) -> bool: + if not isinstance(other, OCSPAcceptableResponses): + return NotImplemented + + return self._responses == other._responses + + def __hash__(self) -> int: + return hash(tuple(self._responses)) + + def __repr__(self) -> str: + return f"" + + def __iter__(self) -> typing.Iterator[ObjectIdentifier]: + return iter(self._responses) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class IssuingDistributionPoint(ExtensionType): + oid = ExtensionOID.ISSUING_DISTRIBUTION_POINT + + def __init__( + self, + full_name: typing.Optional[typing.Iterable[GeneralName]], + relative_name: typing.Optional[RelativeDistinguishedName], + only_contains_user_certs: bool, + only_contains_ca_certs: bool, + only_some_reasons: typing.Optional[typing.FrozenSet[ReasonFlags]], + indirect_crl: bool, + only_contains_attribute_certs: bool, + ) -> None: + if full_name is not None: + full_name = list(full_name) + + if only_some_reasons and ( + not isinstance(only_some_reasons, frozenset) + or not all(isinstance(x, ReasonFlags) for x in only_some_reasons) + ): + raise TypeError( + "only_some_reasons must be None or frozenset of ReasonFlags" + ) + + if only_some_reasons and ( + ReasonFlags.unspecified in only_some_reasons + or ReasonFlags.remove_from_crl in only_some_reasons + ): + raise ValueError( + "unspecified and remove_from_crl are not valid reasons in an " + "IssuingDistributionPoint" + ) + + if not ( + isinstance(only_contains_user_certs, bool) + and isinstance(only_contains_ca_certs, bool) + and isinstance(indirect_crl, bool) + and isinstance(only_contains_attribute_certs, bool) + ): + raise TypeError( + "only_contains_user_certs, only_contains_ca_certs, " + "indirect_crl and only_contains_attribute_certs " + "must all be boolean." + ) + + crl_constraints = [ + only_contains_user_certs, + only_contains_ca_certs, + indirect_crl, + only_contains_attribute_certs, + ] + + if len([x for x in crl_constraints if x]) > 1: + raise ValueError( + "Only one of the following can be set to True: " + "only_contains_user_certs, only_contains_ca_certs, " + "indirect_crl, only_contains_attribute_certs" + ) + + if not any( + [ + only_contains_user_certs, + only_contains_ca_certs, + indirect_crl, + only_contains_attribute_certs, + full_name, + relative_name, + only_some_reasons, + ] + ): + raise ValueError( + "Cannot create empty extension: " + "if only_contains_user_certs, only_contains_ca_certs, " + "indirect_crl, and only_contains_attribute_certs are all False" + ", then either full_name, relative_name, or only_some_reasons " + "must have a value." + ) + + self._only_contains_user_certs = only_contains_user_certs + self._only_contains_ca_certs = only_contains_ca_certs + self._indirect_crl = indirect_crl + self._only_contains_attribute_certs = only_contains_attribute_certs + self._only_some_reasons = only_some_reasons + self._full_name = full_name + self._relative_name = relative_name + + def __repr__(self) -> str: + return ( + "".format(self) + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, IssuingDistributionPoint): + return NotImplemented + + return ( + self.full_name == other.full_name + and self.relative_name == other.relative_name + and self.only_contains_user_certs == other.only_contains_user_certs + and self.only_contains_ca_certs == other.only_contains_ca_certs + and self.only_some_reasons == other.only_some_reasons + and self.indirect_crl == other.indirect_crl + and self.only_contains_attribute_certs + == other.only_contains_attribute_certs + ) + + def __hash__(self) -> int: + return hash( + ( + self.full_name, + self.relative_name, + self.only_contains_user_certs, + self.only_contains_ca_certs, + self.only_some_reasons, + self.indirect_crl, + self.only_contains_attribute_certs, + ) + ) + + @property + def full_name(self) -> typing.Optional[typing.List[GeneralName]]: + return self._full_name + + @property + def relative_name(self) -> typing.Optional[RelativeDistinguishedName]: + return self._relative_name + + @property + def only_contains_user_certs(self) -> bool: + return self._only_contains_user_certs + + @property + def only_contains_ca_certs(self) -> bool: + return self._only_contains_ca_certs + + @property + def only_some_reasons( + self, + ) -> typing.Optional[typing.FrozenSet[ReasonFlags]]: + return self._only_some_reasons + + @property + def indirect_crl(self) -> bool: + return self._indirect_crl + + @property + def only_contains_attribute_certs(self) -> bool: + return self._only_contains_attribute_certs + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class MSCertificateTemplate(ExtensionType): + oid = ExtensionOID.MS_CERTIFICATE_TEMPLATE + + def __init__( + self, + template_id: ObjectIdentifier, + major_version: typing.Optional[int], + minor_version: typing.Optional[int], + ) -> None: + if not isinstance(template_id, ObjectIdentifier): + raise TypeError("oid must be an ObjectIdentifier") + self._template_id = template_id + if ( + major_version is not None and not isinstance(major_version, int) + ) or ( + minor_version is not None and not isinstance(minor_version, int) + ): + raise TypeError( + "major_version and minor_version must be integers or None" + ) + self._major_version = major_version + self._minor_version = minor_version + + @property + def template_id(self) -> ObjectIdentifier: + return self._template_id + + @property + def major_version(self) -> typing.Optional[int]: + return self._major_version + + @property + def minor_version(self) -> typing.Optional[int]: + return self._minor_version + + def __repr__(self) -> str: + return ( + f"" + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, MSCertificateTemplate): + return NotImplemented + + return ( + self.template_id == other.template_id + and self.major_version == other.major_version + and self.minor_version == other.minor_version + ) + + def __hash__(self) -> int: + return hash((self.template_id, self.major_version, self.minor_version)) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class UnrecognizedExtension(ExtensionType): + def __init__(self, oid: ObjectIdentifier, value: bytes) -> None: + if not isinstance(oid, ObjectIdentifier): + raise TypeError("oid must be an ObjectIdentifier") + self._oid = oid + self._value = value + + @property + def oid(self) -> ObjectIdentifier: # type: ignore[override] + return self._oid + + @property + def value(self) -> bytes: + return self._value + + def __repr__(self) -> str: + return ( + "".format(self) + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, UnrecognizedExtension): + return NotImplemented + + return self.oid == other.oid and self.value == other.value + + def __hash__(self) -> int: + return hash((self.oid, self.value)) + + def public_bytes(self) -> bytes: + return self.value diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/x509/general_name.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/x509/general_name.py new file mode 100644 index 0000000000000000000000000000000000000000..79271afbf91e5660cb34e6c189e316614a77cf61 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/x509/general_name.py @@ -0,0 +1,283 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc +import ipaddress +import typing +from email.utils import parseaddr + +from cryptography.x509.name import Name +from cryptography.x509.oid import ObjectIdentifier + +_IPAddressTypes = typing.Union[ + ipaddress.IPv4Address, + ipaddress.IPv6Address, + ipaddress.IPv4Network, + ipaddress.IPv6Network, +] + + +class UnsupportedGeneralNameType(Exception): + pass + + +class GeneralName(metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def value(self) -> typing.Any: + """ + Return the value of the object + """ + + +class RFC822Name(GeneralName): + def __init__(self, value: str) -> None: + if isinstance(value, str): + try: + value.encode("ascii") + except UnicodeEncodeError: + raise ValueError( + "RFC822Name values should be passed as an A-label string. " + "This means unicode characters should be encoded via " + "a library like idna." + ) + else: + raise TypeError("value must be string") + + name, address = parseaddr(value) + if name or not address: + # parseaddr has found a name (e.g. Name ) or the entire + # value is an empty string. + raise ValueError("Invalid rfc822name value") + + self._value = value + + @property + def value(self) -> str: + return self._value + + @classmethod + def _init_without_validation(cls, value: str) -> RFC822Name: + instance = cls.__new__(cls) + instance._value = value + return instance + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, RFC822Name): + return NotImplemented + + return self.value == other.value + + def __hash__(self) -> int: + return hash(self.value) + + +class DNSName(GeneralName): + def __init__(self, value: str) -> None: + if isinstance(value, str): + try: + value.encode("ascii") + except UnicodeEncodeError: + raise ValueError( + "DNSName values should be passed as an A-label string. " + "This means unicode characters should be encoded via " + "a library like idna." + ) + else: + raise TypeError("value must be string") + + self._value = value + + @property + def value(self) -> str: + return self._value + + @classmethod + def _init_without_validation(cls, value: str) -> DNSName: + instance = cls.__new__(cls) + instance._value = value + return instance + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, DNSName): + return NotImplemented + + return self.value == other.value + + def __hash__(self) -> int: + return hash(self.value) + + +class UniformResourceIdentifier(GeneralName): + def __init__(self, value: str) -> None: + if isinstance(value, str): + try: + value.encode("ascii") + except UnicodeEncodeError: + raise ValueError( + "URI values should be passed as an A-label string. " + "This means unicode characters should be encoded via " + "a library like idna." + ) + else: + raise TypeError("value must be string") + + self._value = value + + @property + def value(self) -> str: + return self._value + + @classmethod + def _init_without_validation(cls, value: str) -> UniformResourceIdentifier: + instance = cls.__new__(cls) + instance._value = value + return instance + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, UniformResourceIdentifier): + return NotImplemented + + return self.value == other.value + + def __hash__(self) -> int: + return hash(self.value) + + +class DirectoryName(GeneralName): + def __init__(self, value: Name) -> None: + if not isinstance(value, Name): + raise TypeError("value must be a Name") + + self._value = value + + @property + def value(self) -> Name: + return self._value + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, DirectoryName): + return NotImplemented + + return self.value == other.value + + def __hash__(self) -> int: + return hash(self.value) + + +class RegisteredID(GeneralName): + def __init__(self, value: ObjectIdentifier) -> None: + if not isinstance(value, ObjectIdentifier): + raise TypeError("value must be an ObjectIdentifier") + + self._value = value + + @property + def value(self) -> ObjectIdentifier: + return self._value + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, RegisteredID): + return NotImplemented + + return self.value == other.value + + def __hash__(self) -> int: + return hash(self.value) + + +class IPAddress(GeneralName): + def __init__(self, value: _IPAddressTypes) -> None: + if not isinstance( + value, + ( + ipaddress.IPv4Address, + ipaddress.IPv6Address, + ipaddress.IPv4Network, + ipaddress.IPv6Network, + ), + ): + raise TypeError( + "value must be an instance of ipaddress.IPv4Address, " + "ipaddress.IPv6Address, ipaddress.IPv4Network, or " + "ipaddress.IPv6Network" + ) + + self._value = value + + @property + def value(self) -> _IPAddressTypes: + return self._value + + def _packed(self) -> bytes: + if isinstance( + self.value, (ipaddress.IPv4Address, ipaddress.IPv6Address) + ): + return self.value.packed + else: + return ( + self.value.network_address.packed + self.value.netmask.packed + ) + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, IPAddress): + return NotImplemented + + return self.value == other.value + + def __hash__(self) -> int: + return hash(self.value) + + +class OtherName(GeneralName): + def __init__(self, type_id: ObjectIdentifier, value: bytes) -> None: + if not isinstance(type_id, ObjectIdentifier): + raise TypeError("type_id must be an ObjectIdentifier") + if not isinstance(value, bytes): + raise TypeError("value must be a binary string") + + self._type_id = type_id + self._value = value + + @property + def type_id(self) -> ObjectIdentifier: + return self._type_id + + @property + def value(self) -> bytes: + return self._value + + def __repr__(self) -> str: + return "".format( + self.type_id, self.value + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, OtherName): + return NotImplemented + + return self.type_id == other.type_id and self.value == other.value + + def __hash__(self) -> int: + return hash((self.type_id, self.value)) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/x509/name.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/x509/name.py new file mode 100644 index 0000000000000000000000000000000000000000..ff98e8724af1411c3860642d7361f95f0bdeb4b0 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/x509/name.py @@ -0,0 +1,462 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import binascii +import re +import sys +import typing +import warnings + +from cryptography import utils +from cryptography.hazmat.bindings._rust import x509 as rust_x509 +from cryptography.x509.oid import NameOID, ObjectIdentifier + + +class _ASN1Type(utils.Enum): + BitString = 3 + OctetString = 4 + UTF8String = 12 + NumericString = 18 + PrintableString = 19 + T61String = 20 + IA5String = 22 + UTCTime = 23 + GeneralizedTime = 24 + VisibleString = 26 + UniversalString = 28 + BMPString = 30 + + +_ASN1_TYPE_TO_ENUM = {i.value: i for i in _ASN1Type} +_NAMEOID_DEFAULT_TYPE: typing.Dict[ObjectIdentifier, _ASN1Type] = { + NameOID.COUNTRY_NAME: _ASN1Type.PrintableString, + NameOID.JURISDICTION_COUNTRY_NAME: _ASN1Type.PrintableString, + NameOID.SERIAL_NUMBER: _ASN1Type.PrintableString, + NameOID.DN_QUALIFIER: _ASN1Type.PrintableString, + NameOID.EMAIL_ADDRESS: _ASN1Type.IA5String, + NameOID.DOMAIN_COMPONENT: _ASN1Type.IA5String, +} + +# Type alias +_OidNameMap = typing.Mapping[ObjectIdentifier, str] +_NameOidMap = typing.Mapping[str, ObjectIdentifier] + +#: Short attribute names from RFC 4514: +#: https://tools.ietf.org/html/rfc4514#page-7 +_NAMEOID_TO_NAME: _OidNameMap = { + NameOID.COMMON_NAME: "CN", + NameOID.LOCALITY_NAME: "L", + NameOID.STATE_OR_PROVINCE_NAME: "ST", + NameOID.ORGANIZATION_NAME: "O", + NameOID.ORGANIZATIONAL_UNIT_NAME: "OU", + NameOID.COUNTRY_NAME: "C", + NameOID.STREET_ADDRESS: "STREET", + NameOID.DOMAIN_COMPONENT: "DC", + NameOID.USER_ID: "UID", +} +_NAME_TO_NAMEOID = {v: k for k, v in _NAMEOID_TO_NAME.items()} + + +def _escape_dn_value(val: typing.Union[str, bytes]) -> str: + """Escape special characters in RFC4514 Distinguished Name value.""" + + if not val: + return "" + + # RFC 4514 Section 2.4 defines the value as being the # (U+0023) character + # followed by the hexadecimal encoding of the octets. + if isinstance(val, bytes): + return "#" + binascii.hexlify(val).decode("utf8") + + # See https://tools.ietf.org/html/rfc4514#section-2.4 + val = val.replace("\\", "\\\\") + val = val.replace('"', '\\"') + val = val.replace("+", "\\+") + val = val.replace(",", "\\,") + val = val.replace(";", "\\;") + val = val.replace("<", "\\<") + val = val.replace(">", "\\>") + val = val.replace("\0", "\\00") + + if val[0] in ("#", " "): + val = "\\" + val + if val[-1] == " ": + val = val[:-1] + "\\ " + + return val + + +def _unescape_dn_value(val: str) -> str: + if not val: + return "" + + # See https://tools.ietf.org/html/rfc4514#section-3 + + # special = escaped / SPACE / SHARP / EQUALS + # escaped = DQUOTE / PLUS / COMMA / SEMI / LANGLE / RANGLE + def sub(m): + val = m.group(1) + # Regular escape + if len(val) == 1: + return val + # Hex-value scape + return chr(int(val, 16)) + + return _RFC4514NameParser._PAIR_RE.sub(sub, val) + + +class NameAttribute: + def __init__( + self, + oid: ObjectIdentifier, + value: typing.Union[str, bytes], + _type: typing.Optional[_ASN1Type] = None, + *, + _validate: bool = True, + ) -> None: + if not isinstance(oid, ObjectIdentifier): + raise TypeError( + "oid argument must be an ObjectIdentifier instance." + ) + if _type == _ASN1Type.BitString: + if oid != NameOID.X500_UNIQUE_IDENTIFIER: + raise TypeError( + "oid must be X500_UNIQUE_IDENTIFIER for BitString type." + ) + if not isinstance(value, bytes): + raise TypeError("value must be bytes for BitString") + else: + if not isinstance(value, str): + raise TypeError("value argument must be a str") + + if ( + oid == NameOID.COUNTRY_NAME + or oid == NameOID.JURISDICTION_COUNTRY_NAME + ): + assert isinstance(value, str) + c_len = len(value.encode("utf8")) + if c_len != 2 and _validate is True: + raise ValueError( + "Country name must be a 2 character country code" + ) + elif c_len != 2: + warnings.warn( + "Country names should be two characters, but the " + "attribute is {} characters in length.".format(c_len), + stacklevel=2, + ) + + # The appropriate ASN1 string type varies by OID and is defined across + # multiple RFCs including 2459, 3280, and 5280. In general UTF8String + # is preferred (2459), but 3280 and 5280 specify several OIDs with + # alternate types. This means when we see the sentinel value we need + # to look up whether the OID has a non-UTF8 type. If it does, set it + # to that. Otherwise, UTF8! + if _type is None: + _type = _NAMEOID_DEFAULT_TYPE.get(oid, _ASN1Type.UTF8String) + + if not isinstance(_type, _ASN1Type): + raise TypeError("_type must be from the _ASN1Type enum") + + self._oid = oid + self._value = value + self._type = _type + + @property + def oid(self) -> ObjectIdentifier: + return self._oid + + @property + def value(self) -> typing.Union[str, bytes]: + return self._value + + @property + def rfc4514_attribute_name(self) -> str: + """ + The short attribute name (for example "CN") if available, + otherwise the OID dotted string. + """ + return _NAMEOID_TO_NAME.get(self.oid, self.oid.dotted_string) + + def rfc4514_string( + self, attr_name_overrides: typing.Optional[_OidNameMap] = None + ) -> str: + """ + Format as RFC4514 Distinguished Name string. + + Use short attribute name if available, otherwise fall back to OID + dotted string. + """ + attr_name = ( + attr_name_overrides.get(self.oid) if attr_name_overrides else None + ) + if attr_name is None: + attr_name = self.rfc4514_attribute_name + + return f"{attr_name}={_escape_dn_value(self.value)}" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, NameAttribute): + return NotImplemented + + return self.oid == other.oid and self.value == other.value + + def __hash__(self) -> int: + return hash((self.oid, self.value)) + + def __repr__(self) -> str: + return "".format(self) + + +class RelativeDistinguishedName: + def __init__(self, attributes: typing.Iterable[NameAttribute]): + attributes = list(attributes) + if not attributes: + raise ValueError("a relative distinguished name cannot be empty") + if not all(isinstance(x, NameAttribute) for x in attributes): + raise TypeError("attributes must be an iterable of NameAttribute") + + # Keep list and frozenset to preserve attribute order where it matters + self._attributes = attributes + self._attribute_set = frozenset(attributes) + + if len(self._attribute_set) != len(attributes): + raise ValueError("duplicate attributes are not allowed") + + def get_attributes_for_oid( + self, oid: ObjectIdentifier + ) -> typing.List[NameAttribute]: + return [i for i in self if i.oid == oid] + + def rfc4514_string( + self, attr_name_overrides: typing.Optional[_OidNameMap] = None + ) -> str: + """ + Format as RFC4514 Distinguished Name string. + + Within each RDN, attributes are joined by '+', although that is rarely + used in certificates. + """ + return "+".join( + attr.rfc4514_string(attr_name_overrides) + for attr in self._attributes + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, RelativeDistinguishedName): + return NotImplemented + + return self._attribute_set == other._attribute_set + + def __hash__(self) -> int: + return hash(self._attribute_set) + + def __iter__(self) -> typing.Iterator[NameAttribute]: + return iter(self._attributes) + + def __len__(self) -> int: + return len(self._attributes) + + def __repr__(self) -> str: + return f"" + + +class Name: + @typing.overload + def __init__(self, attributes: typing.Iterable[NameAttribute]) -> None: + ... + + @typing.overload + def __init__( + self, attributes: typing.Iterable[RelativeDistinguishedName] + ) -> None: + ... + + def __init__( + self, + attributes: typing.Iterable[ + typing.Union[NameAttribute, RelativeDistinguishedName] + ], + ) -> None: + attributes = list(attributes) + if all(isinstance(x, NameAttribute) for x in attributes): + self._attributes = [ + RelativeDistinguishedName([typing.cast(NameAttribute, x)]) + for x in attributes + ] + elif all(isinstance(x, RelativeDistinguishedName) for x in attributes): + self._attributes = typing.cast( + typing.List[RelativeDistinguishedName], attributes + ) + else: + raise TypeError( + "attributes must be a list of NameAttribute" + " or a list RelativeDistinguishedName" + ) + + @classmethod + def from_rfc4514_string( + cls, + data: str, + attr_name_overrides: typing.Optional[_NameOidMap] = None, + ) -> Name: + return _RFC4514NameParser(data, attr_name_overrides or {}).parse() + + def rfc4514_string( + self, attr_name_overrides: typing.Optional[_OidNameMap] = None + ) -> str: + """ + Format as RFC4514 Distinguished Name string. + For example 'CN=foobar.com,O=Foo Corp,C=US' + + An X.509 name is a two-level structure: a list of sets of attributes. + Each list element is separated by ',' and within each list element, set + elements are separated by '+'. The latter is almost never used in + real world certificates. According to RFC4514 section 2.1 the + RDNSequence must be reversed when converting to string representation. + """ + return ",".join( + attr.rfc4514_string(attr_name_overrides) + for attr in reversed(self._attributes) + ) + + def get_attributes_for_oid( + self, oid: ObjectIdentifier + ) -> typing.List[NameAttribute]: + return [i for i in self if i.oid == oid] + + @property + def rdns(self) -> typing.List[RelativeDistinguishedName]: + return self._attributes + + def public_bytes(self, backend: typing.Any = None) -> bytes: + return rust_x509.encode_name_bytes(self) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, Name): + return NotImplemented + + return self._attributes == other._attributes + + def __hash__(self) -> int: + # TODO: this is relatively expensive, if this looks like a bottleneck + # for you, consider optimizing! + return hash(tuple(self._attributes)) + + def __iter__(self) -> typing.Iterator[NameAttribute]: + for rdn in self._attributes: + for ava in rdn: + yield ava + + def __len__(self) -> int: + return sum(len(rdn) for rdn in self._attributes) + + def __repr__(self) -> str: + rdns = ",".join(attr.rfc4514_string() for attr in self._attributes) + return f"" + + +class _RFC4514NameParser: + _OID_RE = re.compile(r"(0|([1-9]\d*))(\.(0|([1-9]\d*)))+") + _DESCR_RE = re.compile(r"[a-zA-Z][a-zA-Z\d-]*") + + _PAIR = r"\\([\\ #=\"\+,;<>]|[\da-zA-Z]{2})" + _PAIR_RE = re.compile(_PAIR) + _LUTF1 = r"[\x01-\x1f\x21\x24-\x2A\x2D-\x3A\x3D\x3F-\x5B\x5D-\x7F]" + _SUTF1 = r"[\x01-\x21\x23-\x2A\x2D-\x3A\x3D\x3F-\x5B\x5D-\x7F]" + _TUTF1 = r"[\x01-\x1F\x21\x23-\x2A\x2D-\x3A\x3D\x3F-\x5B\x5D-\x7F]" + _UTFMB = rf"[\x80-{chr(sys.maxunicode)}]" + _LEADCHAR = rf"{_LUTF1}|{_UTFMB}" + _STRINGCHAR = rf"{_SUTF1}|{_UTFMB}" + _TRAILCHAR = rf"{_TUTF1}|{_UTFMB}" + _STRING_RE = re.compile( + rf""" + ( + ({_LEADCHAR}|{_PAIR}) + ( + ({_STRINGCHAR}|{_PAIR})* + ({_TRAILCHAR}|{_PAIR}) + )? + )? + """, + re.VERBOSE, + ) + _HEXSTRING_RE = re.compile(r"#([\da-zA-Z]{2})+") + + def __init__(self, data: str, attr_name_overrides: _NameOidMap) -> None: + self._data = data + self._idx = 0 + + self._attr_name_overrides = attr_name_overrides + + def _has_data(self) -> bool: + return self._idx < len(self._data) + + def _peek(self) -> typing.Optional[str]: + if self._has_data(): + return self._data[self._idx] + return None + + def _read_char(self, ch: str) -> None: + if self._peek() != ch: + raise ValueError + self._idx += 1 + + def _read_re(self, pat) -> str: + match = pat.match(self._data, pos=self._idx) + if match is None: + raise ValueError + val = match.group() + self._idx += len(val) + return val + + def parse(self) -> Name: + """ + Parses the `data` string and converts it to a Name. + + According to RFC4514 section 2.1 the RDNSequence must be + reversed when converting to string representation. So, when + we parse it, we need to reverse again to get the RDNs on the + correct order. + """ + rdns = [self._parse_rdn()] + + while self._has_data(): + self._read_char(",") + rdns.append(self._parse_rdn()) + + return Name(reversed(rdns)) + + def _parse_rdn(self) -> RelativeDistinguishedName: + nas = [self._parse_na()] + while self._peek() == "+": + self._read_char("+") + nas.append(self._parse_na()) + + return RelativeDistinguishedName(nas) + + def _parse_na(self) -> NameAttribute: + try: + oid_value = self._read_re(self._OID_RE) + except ValueError: + name = self._read_re(self._DESCR_RE) + oid = self._attr_name_overrides.get( + name, _NAME_TO_NAMEOID.get(name) + ) + if oid is None: + raise ValueError + else: + oid = ObjectIdentifier(oid_value) + + self._read_char("=") + if self._peek() == "#": + value = self._read_re(self._HEXSTRING_RE) + value = binascii.unhexlify(value[1:]).decode() + else: + raw_value = self._read_re(self._STRING_RE) + value = _unescape_dn_value(raw_value) + + return NameAttribute(oid, value) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/x509/ocsp.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/x509/ocsp.py new file mode 100644 index 0000000000000000000000000000000000000000..7054795fcda8d0c826506fc3861e11874829e4d2 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/x509/ocsp.py @@ -0,0 +1,622 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc +import datetime +import typing + +from cryptography import utils, x509 +from cryptography.hazmat.bindings._rust import ocsp +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric.types import ( + CertificateIssuerPrivateKeyTypes, +) +from cryptography.x509.base import ( + _EARLIEST_UTC_TIME, + _convert_to_naive_utc_time, + _reject_duplicate_extension, +) + + +class OCSPResponderEncoding(utils.Enum): + HASH = "By Hash" + NAME = "By Name" + + +class OCSPResponseStatus(utils.Enum): + SUCCESSFUL = 0 + MALFORMED_REQUEST = 1 + INTERNAL_ERROR = 2 + TRY_LATER = 3 + SIG_REQUIRED = 5 + UNAUTHORIZED = 6 + + +_ALLOWED_HASHES = ( + hashes.SHA1, + hashes.SHA224, + hashes.SHA256, + hashes.SHA384, + hashes.SHA512, +) + + +def _verify_algorithm(algorithm: hashes.HashAlgorithm) -> None: + if not isinstance(algorithm, _ALLOWED_HASHES): + raise ValueError( + "Algorithm must be SHA1, SHA224, SHA256, SHA384, or SHA512" + ) + + +class OCSPCertStatus(utils.Enum): + GOOD = 0 + REVOKED = 1 + UNKNOWN = 2 + + +class _SingleResponse: + def __init__( + self, + cert: x509.Certificate, + issuer: x509.Certificate, + algorithm: hashes.HashAlgorithm, + cert_status: OCSPCertStatus, + this_update: datetime.datetime, + next_update: typing.Optional[datetime.datetime], + revocation_time: typing.Optional[datetime.datetime], + revocation_reason: typing.Optional[x509.ReasonFlags], + ): + if not isinstance(cert, x509.Certificate) or not isinstance( + issuer, x509.Certificate + ): + raise TypeError("cert and issuer must be a Certificate") + + _verify_algorithm(algorithm) + if not isinstance(this_update, datetime.datetime): + raise TypeError("this_update must be a datetime object") + if next_update is not None and not isinstance( + next_update, datetime.datetime + ): + raise TypeError("next_update must be a datetime object or None") + + self._cert = cert + self._issuer = issuer + self._algorithm = algorithm + self._this_update = this_update + self._next_update = next_update + + if not isinstance(cert_status, OCSPCertStatus): + raise TypeError( + "cert_status must be an item from the OCSPCertStatus enum" + ) + if cert_status is not OCSPCertStatus.REVOKED: + if revocation_time is not None: + raise ValueError( + "revocation_time can only be provided if the certificate " + "is revoked" + ) + if revocation_reason is not None: + raise ValueError( + "revocation_reason can only be provided if the certificate" + " is revoked" + ) + else: + if not isinstance(revocation_time, datetime.datetime): + raise TypeError("revocation_time must be a datetime object") + + revocation_time = _convert_to_naive_utc_time(revocation_time) + if revocation_time < _EARLIEST_UTC_TIME: + raise ValueError( + "The revocation_time must be on or after" + " 1950 January 1." + ) + + if revocation_reason is not None and not isinstance( + revocation_reason, x509.ReasonFlags + ): + raise TypeError( + "revocation_reason must be an item from the ReasonFlags " + "enum or None" + ) + + self._cert_status = cert_status + self._revocation_time = revocation_time + self._revocation_reason = revocation_reason + + +class OCSPRequest(metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def issuer_key_hash(self) -> bytes: + """ + The hash of the issuer public key + """ + + @property + @abc.abstractmethod + def issuer_name_hash(self) -> bytes: + """ + The hash of the issuer name + """ + + @property + @abc.abstractmethod + def hash_algorithm(self) -> hashes.HashAlgorithm: + """ + The hash algorithm used in the issuer name and key hashes + """ + + @property + @abc.abstractmethod + def serial_number(self) -> int: + """ + The serial number of the cert whose status is being checked + """ + + @abc.abstractmethod + def public_bytes(self, encoding: serialization.Encoding) -> bytes: + """ + Serializes the request to DER + """ + + @property + @abc.abstractmethod + def extensions(self) -> x509.Extensions: + """ + The list of request extensions. Not single request extensions. + """ + + +class OCSPSingleResponse(metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def certificate_status(self) -> OCSPCertStatus: + """ + The status of the certificate (an element from the OCSPCertStatus enum) + """ + + @property + @abc.abstractmethod + def revocation_time(self) -> typing.Optional[datetime.datetime]: + """ + The date of when the certificate was revoked or None if not + revoked. + """ + + @property + @abc.abstractmethod + def revocation_reason(self) -> typing.Optional[x509.ReasonFlags]: + """ + The reason the certificate was revoked or None if not specified or + not revoked. + """ + + @property + @abc.abstractmethod + def this_update(self) -> datetime.datetime: + """ + The most recent time at which the status being indicated is known by + the responder to have been correct + """ + + @property + @abc.abstractmethod + def next_update(self) -> typing.Optional[datetime.datetime]: + """ + The time when newer information will be available + """ + + @property + @abc.abstractmethod + def issuer_key_hash(self) -> bytes: + """ + The hash of the issuer public key + """ + + @property + @abc.abstractmethod + def issuer_name_hash(self) -> bytes: + """ + The hash of the issuer name + """ + + @property + @abc.abstractmethod + def hash_algorithm(self) -> hashes.HashAlgorithm: + """ + The hash algorithm used in the issuer name and key hashes + """ + + @property + @abc.abstractmethod + def serial_number(self) -> int: + """ + The serial number of the cert whose status is being checked + """ + + +class OCSPResponse(metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def responses(self) -> typing.Iterator[OCSPSingleResponse]: + """ + An iterator over the individual SINGLERESP structures in the + response + """ + + @property + @abc.abstractmethod + def response_status(self) -> OCSPResponseStatus: + """ + The status of the response. This is a value from the OCSPResponseStatus + enumeration + """ + + @property + @abc.abstractmethod + def signature_algorithm_oid(self) -> x509.ObjectIdentifier: + """ + The ObjectIdentifier of the signature algorithm + """ + + @property + @abc.abstractmethod + def signature_hash_algorithm( + self, + ) -> typing.Optional[hashes.HashAlgorithm]: + """ + Returns a HashAlgorithm corresponding to the type of the digest signed + """ + + @property + @abc.abstractmethod + def signature(self) -> bytes: + """ + The signature bytes + """ + + @property + @abc.abstractmethod + def tbs_response_bytes(self) -> bytes: + """ + The tbsResponseData bytes + """ + + @property + @abc.abstractmethod + def certificates(self) -> typing.List[x509.Certificate]: + """ + A list of certificates used to help build a chain to verify the OCSP + response. This situation occurs when the OCSP responder uses a delegate + certificate. + """ + + @property + @abc.abstractmethod + def responder_key_hash(self) -> typing.Optional[bytes]: + """ + The responder's key hash or None + """ + + @property + @abc.abstractmethod + def responder_name(self) -> typing.Optional[x509.Name]: + """ + The responder's Name or None + """ + + @property + @abc.abstractmethod + def produced_at(self) -> datetime.datetime: + """ + The time the response was produced + """ + + @property + @abc.abstractmethod + def certificate_status(self) -> OCSPCertStatus: + """ + The status of the certificate (an element from the OCSPCertStatus enum) + """ + + @property + @abc.abstractmethod + def revocation_time(self) -> typing.Optional[datetime.datetime]: + """ + The date of when the certificate was revoked or None if not + revoked. + """ + + @property + @abc.abstractmethod + def revocation_reason(self) -> typing.Optional[x509.ReasonFlags]: + """ + The reason the certificate was revoked or None if not specified or + not revoked. + """ + + @property + @abc.abstractmethod + def this_update(self) -> datetime.datetime: + """ + The most recent time at which the status being indicated is known by + the responder to have been correct + """ + + @property + @abc.abstractmethod + def next_update(self) -> typing.Optional[datetime.datetime]: + """ + The time when newer information will be available + """ + + @property + @abc.abstractmethod + def issuer_key_hash(self) -> bytes: + """ + The hash of the issuer public key + """ + + @property + @abc.abstractmethod + def issuer_name_hash(self) -> bytes: + """ + The hash of the issuer name + """ + + @property + @abc.abstractmethod + def hash_algorithm(self) -> hashes.HashAlgorithm: + """ + The hash algorithm used in the issuer name and key hashes + """ + + @property + @abc.abstractmethod + def serial_number(self) -> int: + """ + The serial number of the cert whose status is being checked + """ + + @property + @abc.abstractmethod + def extensions(self) -> x509.Extensions: + """ + The list of response extensions. Not single response extensions. + """ + + @property + @abc.abstractmethod + def single_extensions(self) -> x509.Extensions: + """ + The list of single response extensions. Not response extensions. + """ + + @abc.abstractmethod + def public_bytes(self, encoding: serialization.Encoding) -> bytes: + """ + Serializes the response to DER + """ + + +class OCSPRequestBuilder: + def __init__( + self, + request: typing.Optional[ + typing.Tuple[ + x509.Certificate, x509.Certificate, hashes.HashAlgorithm + ] + ] = None, + request_hash: typing.Optional[ + typing.Tuple[bytes, bytes, int, hashes.HashAlgorithm] + ] = None, + extensions: typing.List[x509.Extension[x509.ExtensionType]] = [], + ) -> None: + self._request = request + self._request_hash = request_hash + self._extensions = extensions + + def add_certificate( + self, + cert: x509.Certificate, + issuer: x509.Certificate, + algorithm: hashes.HashAlgorithm, + ) -> OCSPRequestBuilder: + if self._request is not None or self._request_hash is not None: + raise ValueError("Only one certificate can be added to a request") + + _verify_algorithm(algorithm) + if not isinstance(cert, x509.Certificate) or not isinstance( + issuer, x509.Certificate + ): + raise TypeError("cert and issuer must be a Certificate") + + return OCSPRequestBuilder( + (cert, issuer, algorithm), self._request_hash, self._extensions + ) + + def add_certificate_by_hash( + self, + issuer_name_hash: bytes, + issuer_key_hash: bytes, + serial_number: int, + algorithm: hashes.HashAlgorithm, + ) -> OCSPRequestBuilder: + if self._request is not None or self._request_hash is not None: + raise ValueError("Only one certificate can be added to a request") + + if not isinstance(serial_number, int): + raise TypeError("serial_number must be an integer") + + _verify_algorithm(algorithm) + utils._check_bytes("issuer_name_hash", issuer_name_hash) + utils._check_bytes("issuer_key_hash", issuer_key_hash) + if algorithm.digest_size != len( + issuer_name_hash + ) or algorithm.digest_size != len(issuer_key_hash): + raise ValueError( + "issuer_name_hash and issuer_key_hash must be the same length " + "as the digest size of the algorithm" + ) + + return OCSPRequestBuilder( + self._request, + (issuer_name_hash, issuer_key_hash, serial_number, algorithm), + self._extensions, + ) + + def add_extension( + self, extval: x509.ExtensionType, critical: bool + ) -> OCSPRequestBuilder: + if not isinstance(extval, x509.ExtensionType): + raise TypeError("extension must be an ExtensionType") + + extension = x509.Extension(extval.oid, critical, extval) + _reject_duplicate_extension(extension, self._extensions) + + return OCSPRequestBuilder( + self._request, self._request_hash, self._extensions + [extension] + ) + + def build(self) -> OCSPRequest: + if self._request is None and self._request_hash is None: + raise ValueError("You must add a certificate before building") + + return ocsp.create_ocsp_request(self) + + +class OCSPResponseBuilder: + def __init__( + self, + response: typing.Optional[_SingleResponse] = None, + responder_id: typing.Optional[ + typing.Tuple[x509.Certificate, OCSPResponderEncoding] + ] = None, + certs: typing.Optional[typing.List[x509.Certificate]] = None, + extensions: typing.List[x509.Extension[x509.ExtensionType]] = [], + ): + self._response = response + self._responder_id = responder_id + self._certs = certs + self._extensions = extensions + + def add_response( + self, + cert: x509.Certificate, + issuer: x509.Certificate, + algorithm: hashes.HashAlgorithm, + cert_status: OCSPCertStatus, + this_update: datetime.datetime, + next_update: typing.Optional[datetime.datetime], + revocation_time: typing.Optional[datetime.datetime], + revocation_reason: typing.Optional[x509.ReasonFlags], + ) -> OCSPResponseBuilder: + if self._response is not None: + raise ValueError("Only one response per OCSPResponse.") + + singleresp = _SingleResponse( + cert, + issuer, + algorithm, + cert_status, + this_update, + next_update, + revocation_time, + revocation_reason, + ) + return OCSPResponseBuilder( + singleresp, + self._responder_id, + self._certs, + self._extensions, + ) + + def responder_id( + self, encoding: OCSPResponderEncoding, responder_cert: x509.Certificate + ) -> OCSPResponseBuilder: + if self._responder_id is not None: + raise ValueError("responder_id can only be set once") + if not isinstance(responder_cert, x509.Certificate): + raise TypeError("responder_cert must be a Certificate") + if not isinstance(encoding, OCSPResponderEncoding): + raise TypeError( + "encoding must be an element from OCSPResponderEncoding" + ) + + return OCSPResponseBuilder( + self._response, + (responder_cert, encoding), + self._certs, + self._extensions, + ) + + def certificates( + self, certs: typing.Iterable[x509.Certificate] + ) -> OCSPResponseBuilder: + if self._certs is not None: + raise ValueError("certificates may only be set once") + certs = list(certs) + if len(certs) == 0: + raise ValueError("certs must not be an empty list") + if not all(isinstance(x, x509.Certificate) for x in certs): + raise TypeError("certs must be a list of Certificates") + return OCSPResponseBuilder( + self._response, + self._responder_id, + certs, + self._extensions, + ) + + def add_extension( + self, extval: x509.ExtensionType, critical: bool + ) -> OCSPResponseBuilder: + if not isinstance(extval, x509.ExtensionType): + raise TypeError("extension must be an ExtensionType") + + extension = x509.Extension(extval.oid, critical, extval) + _reject_duplicate_extension(extension, self._extensions) + + return OCSPResponseBuilder( + self._response, + self._responder_id, + self._certs, + self._extensions + [extension], + ) + + def sign( + self, + private_key: CertificateIssuerPrivateKeyTypes, + algorithm: typing.Optional[hashes.HashAlgorithm], + ) -> OCSPResponse: + if self._response is None: + raise ValueError("You must add a response before signing") + if self._responder_id is None: + raise ValueError("You must add a responder_id before signing") + + return ocsp.create_ocsp_response( + OCSPResponseStatus.SUCCESSFUL, self, private_key, algorithm + ) + + @classmethod + def build_unsuccessful( + cls, response_status: OCSPResponseStatus + ) -> OCSPResponse: + if not isinstance(response_status, OCSPResponseStatus): + raise TypeError( + "response_status must be an item from OCSPResponseStatus" + ) + if response_status is OCSPResponseStatus.SUCCESSFUL: + raise ValueError("response_status cannot be SUCCESSFUL") + + return ocsp.create_ocsp_response(response_status, None, None, None) + + +def load_der_ocsp_request(data: bytes) -> OCSPRequest: + return ocsp.load_der_ocsp_request(data) + + +def load_der_ocsp_response(data: bytes) -> OCSPResponse: + return ocsp.load_der_ocsp_response(data) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/x509/oid.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/x509/oid.py new file mode 100644 index 0000000000000000000000000000000000000000..cda50cced5c418de1820f5acb25178a62a1ede4a --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/cryptography/x509/oid.py @@ -0,0 +1,33 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography.hazmat._oid import ( + AttributeOID, + AuthorityInformationAccessOID, + CertificatePoliciesOID, + CRLEntryExtensionOID, + ExtendedKeyUsageOID, + ExtensionOID, + NameOID, + ObjectIdentifier, + OCSPExtensionOID, + SignatureAlgorithmOID, + SubjectInformationAccessOID, +) + +__all__ = [ + "AttributeOID", + "AuthorityInformationAccessOID", + "CRLEntryExtensionOID", + "CertificatePoliciesOID", + "ExtendedKeyUsageOID", + "ExtensionOID", + "NameOID", + "OCSPExtensionOID", + "ObjectIdentifier", + "SignatureAlgorithmOID", + "SubjectInformationAccessOID", +] diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5ea585d8e37343b47846790236f09f1da5207a6f Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/_commit_api.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/_commit_api.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c964fca01b7c246ff94679f9f4b25b96c8fd1bb Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/_commit_api.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/_commit_scheduler.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/_commit_scheduler.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..012c5973cda7058acf5552ad8676c6c485b22550 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/_commit_scheduler.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/_inference_endpoints.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/_inference_endpoints.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a6c0f56f9b60c9ba09899182e891ccd55779087a Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/_inference_endpoints.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/_login.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/_login.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a9512fbabb2f56a84218b354722e3acad2e1fcab Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/_login.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/_multi_commits.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/_multi_commits.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f8cba09c7a2332c88c9f43c1a43961e90dda8e7c Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/_multi_commits.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/_snapshot_download.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/_snapshot_download.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef40f12508c506adf2984da214c01909b94c7a02 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/_snapshot_download.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/_space_api.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/_space_api.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4a30400b3bc2d3be41a51acb960608028b4508b0 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/_space_api.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/_tensorboard_logger.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/_tensorboard_logger.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5baf0f6f172f8880883dd1899f1a897316a2c670 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/_tensorboard_logger.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/_webhooks_payload.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/_webhooks_payload.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..22fbfb79166673173610082e21ef79aedd4227a7 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/_webhooks_payload.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/_webhooks_server.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/_webhooks_server.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b7058b051ec2f7708a57e781e58962ca5822d339 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/_webhooks_server.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/community.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/community.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2fee49c75db36e59b9922134cc0abf832da533e3 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/community.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/constants.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/constants.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..34606fd7c77033f7b99f992523a65331e4eeed2b Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/constants.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/fastai_utils.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/fastai_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..062286d96b9e4bdc4a2a9533aaaec6fd2c39669f Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/fastai_utils.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/file_download.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/file_download.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e3768f1cbd6c6e70a611cbaac3b4c5d806b52f1c Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/file_download.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/hf_api.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/hf_api.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ab6eb28d6d0b91040816ab4a30b9e9a08edbdd39 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/hf_api.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d543a07fd83b8e27be26c40656eb61f5d28424c28735cd847501e473b125a0c9 +size 359932 diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/hf_file_system.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/hf_file_system.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8396f51d72a399d88a072a9e56b6c87f4f349780 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/hf_file_system.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/hub_mixin.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/hub_mixin.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2c47a1d4a660deeaba179a66de6efadd18777d1d Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/hub_mixin.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/inference_api.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/inference_api.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..70429e54f808f0d1ba2fa070023b2fdd45ad3d24 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/inference_api.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/keras_mixin.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/keras_mixin.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1632f15c6f4f6d263c92a208466fb0865bf929aa Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/keras_mixin.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/lfs.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/lfs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..644aa2b445a346569f0cde3ce971c06ab8c2ad3e Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/lfs.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/repocard.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/repocard.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4f1c5f4b5af9a42dfa44744aac291582396f507b Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/repocard.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/repocard_data.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/repocard_data.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e0c4a58a66532798831fbd9bbc2974134eebd05a Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/repocard_data.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/repository.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/repository.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d835a8de6e7e1223549ed8b2b67c5ee444189ad Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/__pycache__/repository.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/commands/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/commands/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..08bc49acb32836ee2d392523cead6bd191507bb6 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/commands/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/commands/__pycache__/_cli_utils.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/commands/__pycache__/_cli_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..447d1a52836613c065818515d7e089bb1ef604b0 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/commands/__pycache__/_cli_utils.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/commands/__pycache__/delete_cache.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/commands/__pycache__/delete_cache.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9caec8e7b1b90211e893c5256dc60a512f591988 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/commands/__pycache__/delete_cache.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/commands/__pycache__/download.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/commands/__pycache__/download.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..09a70e81189e42d795136e0e3acbd30ab6322662 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/commands/__pycache__/download.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/commands/__pycache__/env.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/commands/__pycache__/env.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..68682e22e8ede129cc96ab46b9fec3e4b88fff1a Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/commands/__pycache__/env.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/commands/__pycache__/huggingface_cli.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/commands/__pycache__/huggingface_cli.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b78d820692b37c6c1b231b59cef9ee63c10b27ce Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/commands/__pycache__/huggingface_cli.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/commands/__pycache__/lfs.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/commands/__pycache__/lfs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fd75f7d271a11b911069fb8e893f8742f0d02a9d Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/commands/__pycache__/lfs.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/commands/__pycache__/scan_cache.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/commands/__pycache__/scan_cache.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..640660058bc77bceb7d98cd8ec1812642892cc5a Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/commands/__pycache__/scan_cache.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/commands/__pycache__/upload.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/commands/__pycache__/upload.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..600aa4a137e8f31bef95e9488eac3d0dd0af4b8c Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/commands/__pycache__/upload.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/commands/__pycache__/user.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/commands/__pycache__/user.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e2eb2ac7866bdd649075c6309b53f7adcf1a6450 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/commands/__pycache__/user.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/commands/huggingface_cli.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/commands/huggingface_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..39b6dfe49ab681f80dea6751e473843e5f685ff3 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/commands/huggingface_cli.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python +# Copyright 2020 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from argparse import ArgumentParser + +from huggingface_hub.commands.delete_cache import DeleteCacheCommand +from huggingface_hub.commands.download import DownloadCommand +from huggingface_hub.commands.env import EnvironmentCommand +from huggingface_hub.commands.lfs import LfsCommands +from huggingface_hub.commands.scan_cache import ScanCacheCommand +from huggingface_hub.commands.upload import UploadCommand +from huggingface_hub.commands.user import UserCommands + + +def main(): + parser = ArgumentParser("huggingface-cli", usage="huggingface-cli []") + commands_parser = parser.add_subparsers(help="huggingface-cli command helpers") + + # Register commands + EnvironmentCommand.register_subcommand(commands_parser) + UserCommands.register_subcommand(commands_parser) + UploadCommand.register_subcommand(commands_parser) + DownloadCommand.register_subcommand(commands_parser) + LfsCommands.register_subcommand(commands_parser) + ScanCacheCommand.register_subcommand(commands_parser) + DeleteCacheCommand.register_subcommand(commands_parser) + + # Let's go + args = parser.parse_args() + + if not hasattr(args, "func"): + parser.print_help() + exit(1) + + # Run + service = args.func(args) + service.run() + + +if __name__ == "__main__": + main() diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/commands/lfs.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/commands/lfs.py new file mode 100644 index 0000000000000000000000000000000000000000..4dbf3cf55c67beebf4e6959ef180b30e29341a7c --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/commands/lfs.py @@ -0,0 +1,199 @@ +""" +Implementation of a custom transfer agent for the transfer type "multipart" for +git-lfs. + +Inspired by: +github.com/cbartz/git-lfs-swift-transfer-agent/blob/master/git_lfs_swift_transfer.py + +Spec is: github.com/git-lfs/git-lfs/blob/master/docs/custom-transfers.md + + +To launch debugger while developing: + +``` [lfs "customtransfer.multipart"] +path = /path/to/huggingface_hub/.env/bin/python args = -m debugpy --listen 5678 +--wait-for-client +/path/to/huggingface_hub/src/huggingface_hub/commands/huggingface_cli.py +lfs-multipart-upload ```""" + +import json +import os +import subprocess +import sys +from argparse import _SubParsersAction +from typing import Dict, List, Optional + +from huggingface_hub.commands import BaseHuggingfaceCLICommand +from huggingface_hub.lfs import LFS_MULTIPART_UPLOAD_COMMAND, SliceFileObj + +from ..utils import get_session, hf_raise_for_status, logging + + +logger = logging.get_logger(__name__) + + +class LfsCommands(BaseHuggingfaceCLICommand): + """ + Implementation of a custom transfer agent for the transfer type "multipart" + for git-lfs. This lets users upload large files >5GB 🔥. Spec for LFS custom + transfer agent is: + https://github.com/git-lfs/git-lfs/blob/master/docs/custom-transfers.md + + This introduces two commands to the CLI: + + 1. $ huggingface-cli lfs-enable-largefiles + + This should be executed once for each model repo that contains a model file + >5GB. It's documented in the error message you get if you just try to git + push a 5GB file without having enabled it before. + + 2. $ huggingface-cli lfs-multipart-upload + + This command is called by lfs directly and is not meant to be called by the + user. + """ + + @staticmethod + def register_subcommand(parser: _SubParsersAction): + enable_parser = parser.add_parser( + "lfs-enable-largefiles", help="Configure your repository to enable upload of files > 5GB." + ) + enable_parser.add_argument("path", type=str, help="Local path to repository you want to configure.") + enable_parser.set_defaults(func=lambda args: LfsEnableCommand(args)) + + # Command will get called by git-lfs, do not call it directly. + upload_parser = parser.add_parser(LFS_MULTIPART_UPLOAD_COMMAND, add_help=False) + upload_parser.set_defaults(func=lambda args: LfsUploadCommand(args)) + + +class LfsEnableCommand: + def __init__(self, args): + self.args = args + + def run(self): + local_path = os.path.abspath(self.args.path) + if not os.path.isdir(local_path): + print("This does not look like a valid git repo.") + exit(1) + subprocess.run( + "git config lfs.customtransfer.multipart.path huggingface-cli".split(), + check=True, + cwd=local_path, + ) + subprocess.run( + f"git config lfs.customtransfer.multipart.args {LFS_MULTIPART_UPLOAD_COMMAND}".split(), + check=True, + cwd=local_path, + ) + print("Local repo set up for largefiles") + + +def write_msg(msg: Dict): + """Write out the message in Line delimited JSON.""" + msg_str = json.dumps(msg) + "\n" + sys.stdout.write(msg_str) + sys.stdout.flush() + + +def read_msg() -> Optional[Dict]: + """Read Line delimited JSON from stdin.""" + msg = json.loads(sys.stdin.readline().strip()) + + if "terminate" in (msg.get("type"), msg.get("event")): + # terminate message received + return None + + if msg.get("event") not in ("download", "upload"): + logger.critical("Received unexpected message") + sys.exit(1) + + return msg + + +class LfsUploadCommand: + def __init__(self, args) -> None: + self.args = args + + def run(self) -> None: + # Immediately after invoking a custom transfer process, git-lfs + # sends initiation data to the process over stdin. + # This tells the process useful information about the configuration. + init_msg = json.loads(sys.stdin.readline().strip()) + if not (init_msg.get("event") == "init" and init_msg.get("operation") == "upload"): + write_msg({"error": {"code": 32, "message": "Wrong lfs init operation"}}) + sys.exit(1) + + # The transfer process should use the information it needs from the + # initiation structure, and also perform any one-off setup tasks it + # needs to do. It should then respond on stdout with a simple empty + # confirmation structure, as follows: + write_msg({}) + + # After the initiation exchange, git-lfs will send any number of + # transfer requests to the stdin of the transfer process, in a serial sequence. + while True: + msg = read_msg() + if msg is None: + # When all transfers have been processed, git-lfs will send + # a terminate event to the stdin of the transfer process. + # On receiving this message the transfer process should + # clean up and terminate. No response is expected. + sys.exit(0) + + oid = msg["oid"] + filepath = msg["path"] + completion_url = msg["action"]["href"] + header = msg["action"]["header"] + chunk_size = int(header.pop("chunk_size")) + presigned_urls: List[str] = list(header.values()) + + # Send a "started" progress event to allow other workers to start. + # Otherwise they're delayed until first "progress" event is reported, + # i.e. after the first 5GB by default (!) + write_msg( + { + "event": "progress", + "oid": oid, + "bytesSoFar": 1, + "bytesSinceLast": 0, + } + ) + + parts = [] + with open(filepath, "rb") as file: + for i, presigned_url in enumerate(presigned_urls): + with SliceFileObj( + file, + seek_from=i * chunk_size, + read_limit=chunk_size, + ) as data: + r = get_session().put(presigned_url, data=data) + hf_raise_for_status(r) + parts.append( + { + "etag": r.headers.get("etag"), + "partNumber": i + 1, + } + ) + # In order to support progress reporting while data is uploading / downloading, + # the transfer process should post messages to stdout + write_msg( + { + "event": "progress", + "oid": oid, + "bytesSoFar": (i + 1) * chunk_size, + "bytesSinceLast": chunk_size, + } + ) + # Not precise but that's ok. + + r = get_session().post( + completion_url, + json={ + "oid": oid, + "parts": parts, + }, + ) + hf_raise_for_status(r) + + write_msg({"event": "complete", "oid": oid}) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/commands/scan_cache.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/commands/scan_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..392bec966e11aa9c8a3a80f60c760c54329b403c --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/commands/scan_cache.py @@ -0,0 +1,138 @@ +# coding=utf-8 +# Copyright 2022-present, the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Contains command to scan the HF cache directory. + +Usage: + huggingface-cli scan-cache + huggingface-cli scan-cache -v + huggingface-cli scan-cache -vvv + huggingface-cli scan-cache --dir ~/.cache/huggingface/hub +""" +import time +from argparse import Namespace, _SubParsersAction +from typing import Optional + +from ..utils import CacheNotFound, HFCacheInfo, scan_cache_dir +from . import BaseHuggingfaceCLICommand +from ._cli_utils import ANSI, tabulate + + +class ScanCacheCommand(BaseHuggingfaceCLICommand): + @staticmethod + def register_subcommand(parser: _SubParsersAction): + scan_cache_parser = parser.add_parser("scan-cache", help="Scan cache directory.") + + scan_cache_parser.add_argument( + "--dir", + type=str, + default=None, + help="cache directory to scan (optional). Default to the default HuggingFace cache.", + ) + scan_cache_parser.add_argument( + "-v", + "--verbose", + action="count", + default=0, + help="show a more verbose output", + ) + scan_cache_parser.set_defaults(func=ScanCacheCommand) + + def __init__(self, args: Namespace) -> None: + self.verbosity: int = args.verbose + self.cache_dir: Optional[str] = args.dir + + def run(self): + try: + t0 = time.time() + hf_cache_info = scan_cache_dir(self.cache_dir) + t1 = time.time() + except CacheNotFound as exc: + cache_dir = exc.cache_dir + print(f"Cache directory not found: {cache_dir}") + return + + self._print_hf_cache_info_as_table(hf_cache_info) + + print( + f"\nDone in {round(t1-t0,1)}s. Scanned {len(hf_cache_info.repos)} repo(s)" + f" for a total of {ANSI.red(hf_cache_info.size_on_disk_str)}." + ) + if len(hf_cache_info.warnings) > 0: + message = f"Got {len(hf_cache_info.warnings)} warning(s) while scanning." + if self.verbosity >= 3: + print(ANSI.gray(message)) + for warning in hf_cache_info.warnings: + print(ANSI.gray(warning)) + else: + print(ANSI.gray(message + " Use -vvv to print details.")) + + def _print_hf_cache_info_as_table(self, hf_cache_info: HFCacheInfo) -> None: + if self.verbosity == 0: + print( + tabulate( + rows=[ + [ + repo.repo_id, + repo.repo_type, + "{:>12}".format(repo.size_on_disk_str), + repo.nb_files, + repo.last_accessed_str, + repo.last_modified_str, + ", ".join(sorted(repo.refs)), + str(repo.repo_path), + ] + for repo in sorted(hf_cache_info.repos, key=lambda repo: repo.repo_path) + ], + headers=[ + "REPO ID", + "REPO TYPE", + "SIZE ON DISK", + "NB FILES", + "LAST_ACCESSED", + "LAST_MODIFIED", + "REFS", + "LOCAL PATH", + ], + ) + ) + else: + print( + tabulate( + rows=[ + [ + repo.repo_id, + repo.repo_type, + revision.commit_hash, + "{:>12}".format(revision.size_on_disk_str), + revision.nb_files, + revision.last_modified_str, + ", ".join(sorted(revision.refs)), + str(revision.snapshot_path), + ] + for repo in sorted(hf_cache_info.repos, key=lambda repo: repo.repo_path) + for revision in sorted(repo.revisions, key=lambda revision: revision.commit_hash) + ], + headers=[ + "REPO ID", + "REPO TYPE", + "REVISION", + "SIZE ON DISK", + "NB FILES", + "LAST_MODIFIED", + "REFS", + "LOCAL PATH", + ], + ) + ) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/commands/upload.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/commands/upload.py new file mode 100644 index 0000000000000000000000000000000000000000..703eed5a47fb1648efe99a41b31715f42dcd394b --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/commands/upload.py @@ -0,0 +1,297 @@ +# coding=utf-8 +# Copyright 2023-present, the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Contains command to upload a repo or file with the CLI. + +Usage: + # Upload file (implicit) + huggingface-cli upload my-cool-model ./my-cool-model.safetensors + + # Upload file (explicit) + huggingface-cli upload my-cool-model ./my-cool-model.safetensors model.safetensors + + # Upload directory (implicit). If `my-cool-model/` is a directory it will be uploaded, otherwise an exception is raised. + huggingface-cli upload my-cool-model + + # Upload directory (explicit) + huggingface-cli upload my-cool-model ./models/my-cool-model . + + # Upload filtered directory (example: tensorboard logs except for the last run) + huggingface-cli upload my-cool-model ./model/training /logs --include "*.tfevents.*" --exclude "*20230905*" + + # Upload private dataset + huggingface-cli upload Wauplin/my-cool-dataset ./data . --repo-type=dataset --private + + # Upload with token + huggingface-cli upload Wauplin/my-cool-model --token=hf_**** + + # Sync local Space with Hub (upload new files, delete removed files) + huggingface-cli upload Wauplin/space-example --repo-type=space --exclude="/logs/*" --delete="*" --commit-message="Sync local Space with Hub" + + # Schedule commits every 30 minutes + huggingface-cli upload Wauplin/my-cool-model --every=30 +""" +import os +import time +import warnings +from argparse import Namespace, _SubParsersAction +from typing import List, Optional + +from huggingface_hub import logging +from huggingface_hub._commit_scheduler import CommitScheduler +from huggingface_hub.commands import BaseHuggingfaceCLICommand +from huggingface_hub.constants import HF_HUB_ENABLE_HF_TRANSFER +from huggingface_hub.hf_api import HfApi +from huggingface_hub.utils import RevisionNotFoundError, disable_progress_bars, enable_progress_bars + + +logger = logging.get_logger(__name__) + + +class UploadCommand(BaseHuggingfaceCLICommand): + @staticmethod + def register_subcommand(parser: _SubParsersAction): + upload_parser = parser.add_parser("upload", help="Upload a file or a folder to a repo on the Hub") + upload_parser.add_argument( + "repo_id", type=str, help="The ID of the repo to upload to (e.g. `username/repo-name`)." + ) + upload_parser.add_argument( + "local_path", nargs="?", help="Local path to the file or folder to upload. Defaults to current directory." + ) + upload_parser.add_argument( + "path_in_repo", + nargs="?", + help="Path of the file or folder in the repo. Defaults to the relative path of the file or folder.", + ) + upload_parser.add_argument( + "--repo-type", + choices=["model", "dataset", "space"], + default="model", + help="Type of the repo to upload to (e.g. `dataset`).", + ) + upload_parser.add_argument( + "--revision", + type=str, + help=( + "An optional Git revision to push to. It can be a branch name or a PR reference. If revision does not" + " exist and `--create-pr` is not set, a branch will be automatically created." + ), + ) + upload_parser.add_argument( + "--private", + action="store_true", + help=( + "Whether to create a private repo if repo doesn't exist on the Hub. Ignored if the repo already" + " exists." + ), + ) + upload_parser.add_argument("--include", nargs="*", type=str, help="Glob patterns to match files to upload.") + upload_parser.add_argument( + "--exclude", nargs="*", type=str, help="Glob patterns to exclude from files to upload." + ) + upload_parser.add_argument( + "--delete", + nargs="*", + type=str, + help="Glob patterns for file to be deleted from the repo while committing.", + ) + upload_parser.add_argument( + "--commit-message", type=str, help="The summary / title / first line of the generated commit." + ) + upload_parser.add_argument("--commit-description", type=str, help="The description of the generated commit.") + upload_parser.add_argument( + "--create-pr", action="store_true", help="Whether to upload content as a new Pull Request." + ) + upload_parser.add_argument( + "--every", + type=float, + help="If set, a background job is scheduled to create commits every `every` minutes.", + ) + upload_parser.add_argument( + "--token", type=str, help="A User Access Token generated from https://huggingface.co/settings/tokens" + ) + upload_parser.add_argument( + "--quiet", + action="store_true", + help="If True, progress bars are disabled and only the path to the uploaded files is printed.", + ) + upload_parser.set_defaults(func=UploadCommand) + + def __init__(self, args: Namespace) -> None: + self.repo_id: str = args.repo_id + self.repo_type: Optional[str] = args.repo_type + self.revision: Optional[str] = args.revision + self.private: bool = args.private + + self.include: Optional[List[str]] = args.include + self.exclude: Optional[List[str]] = args.exclude + self.delete: Optional[List[str]] = args.delete + + self.commit_message: Optional[str] = args.commit_message + self.commit_description: Optional[str] = args.commit_description + self.create_pr: bool = args.create_pr + self.api: HfApi = HfApi(token=args.token, library_name="huggingface-cli") + self.quiet: bool = args.quiet # disable warnings and progress bars + + # Check `--every` is valid + if args.every is not None and args.every <= 0: + raise ValueError(f"`every` must be a positive value (got '{args.every}')") + self.every: Optional[float] = args.every + + # Resolve `local_path` and `path_in_repo` + repo_name: str = args.repo_id.split("/")[-1] # e.g. "Wauplin/my-cool-model" => "my-cool-model" + self.local_path: str + self.path_in_repo: str + if args.local_path is None and os.path.isfile(repo_name): + # Implicit case 1: user provided only a repo_id which happen to be a local file as well => upload it with same name + self.local_path = repo_name + self.path_in_repo = repo_name + elif args.local_path is None and os.path.isdir(repo_name): + # Implicit case 2: user provided only a repo_id which happen to be a local folder as well => upload it at root + self.local_path = repo_name + self.path_in_repo = "." + elif args.local_path is None: + # Implicit case 3: user provided only a repo_id that does not match a local file or folder + # => the user must explicitly provide a local_path => raise exception + raise ValueError(f"'{repo_name}' is not a local file or folder. Please set `local_path` explicitly.") + elif args.path_in_repo is None and os.path.isfile(args.local_path): + # Explicit local path to file, no path in repo => upload it at root with same name + self.local_path = args.local_path + self.path_in_repo = os.path.basename(args.local_path) + elif args.path_in_repo is None: + # Explicit local path to folder, no path in repo => upload at root + self.local_path = args.local_path + self.path_in_repo = "." + else: + # Finally, if both paths are explicit + self.local_path = args.local_path + self.path_in_repo = args.path_in_repo + + def run(self) -> None: + if self.quiet: + disable_progress_bars() + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + print(self._upload()) + enable_progress_bars() + else: + logging.set_verbosity_info() + print(self._upload()) + logging.set_verbosity_warning() + + def _upload(self) -> str: + if os.path.isfile(self.local_path): + if self.include is not None and len(self.include) > 0: + warnings.warn("Ignoring `--include` since a single file is uploaded.") + if self.exclude is not None and len(self.exclude) > 0: + warnings.warn("Ignoring `--exclude` since a single file is uploaded.") + if self.delete is not None and len(self.delete) > 0: + warnings.warn("Ignoring `--delete` since a single file is uploaded.") + + if not HF_HUB_ENABLE_HF_TRANSFER: + logger.info( + "Consider using `hf_transfer` for faster uploads. This solution comes with some limitations. See" + " https://huggingface.co/docs/huggingface_hub/hf_transfer for more details." + ) + + # Schedule commits if `every` is set + if self.every is not None: + if os.path.isfile(self.local_path): + # If file => watch entire folder + use allow_patterns + folder_path = os.path.dirname(self.local_path) + path_in_repo = ( + self.path_in_repo[: -len(self.local_path)] # remove filename from path_in_repo + if self.path_in_repo.endswith(self.local_path) + else self.path_in_repo + ) + allow_patterns = [self.local_path] + ignore_patterns = [] + else: + folder_path = self.local_path + path_in_repo = self.path_in_repo + allow_patterns = self.include or [] + ignore_patterns = self.exclude or [] + if self.delete is not None and len(self.delete) > 0: + warnings.warn("Ignoring `--delete` when uploading with scheduled commits.") + + scheduler = CommitScheduler( + folder_path=folder_path, + repo_id=self.repo_id, + repo_type=self.repo_type, + revision=self.revision, + allow_patterns=allow_patterns, + ignore_patterns=ignore_patterns, + path_in_repo=path_in_repo, + private=self.private, + every=self.every, + hf_api=self.api, + ) + print(f"Scheduling commits every {self.every} minutes to {scheduler.repo_id}.") + try: # Block main thread until KeyboardInterrupt + while True: + time.sleep(100) + except KeyboardInterrupt: + scheduler.stop() + return "Stopped scheduled commits." + + # Otherwise, create repo and proceed with the upload + if not os.path.isfile(self.local_path) and not os.path.isdir(self.local_path): + raise FileNotFoundError(f"No such file or directory: '{self.local_path}'.") + repo_id = self.api.create_repo( + repo_id=self.repo_id, + repo_type=self.repo_type, + exist_ok=True, + private=self.private, + space_sdk="gradio" if self.repo_type == "space" else None, + # ^ We don't want it to fail when uploading to a Space => let's set Gradio by default. + # ^ I'd rather not add CLI args to set it explicitly as we already have `huggingface-cli repo create` for that. + ).repo_id + + # Check if branch already exists and if not, create it + if self.revision is not None and not self.create_pr: + try: + self.api.repo_info(repo_id=repo_id, repo_type=self.repo_type, revision=self.revision) + except RevisionNotFoundError: + logger.info(f"Branch '{self.revision}' not found. Creating it...") + self.api.create_branch(repo_id=repo_id, repo_type=self.repo_type, branch=self.revision, exist_ok=True) + # ^ `exist_ok=True` to avoid race concurrency issues + + # File-based upload + if os.path.isfile(self.local_path): + return self.api.upload_file( + path_or_fileobj=self.local_path, + path_in_repo=self.path_in_repo, + repo_id=repo_id, + repo_type=self.repo_type, + revision=self.revision, + commit_message=self.commit_message, + commit_description=self.commit_description, + create_pr=self.create_pr, + ) + + # Folder-based upload + else: + return self.api.upload_folder( + folder_path=self.local_path, + path_in_repo=self.path_in_repo, + repo_id=repo_id, + repo_type=self.repo_type, + revision=self.revision, + commit_message=self.commit_message, + commit_description=self.commit_description, + create_pr=self.create_pr, + allow_patterns=self.include, + ignore_patterns=self.exclude, + delete_patterns=self.delete, + ) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/commands/user.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/commands/user.py new file mode 100644 index 0000000000000000000000000000000000000000..8cde3ac04c8a0773cad0a767a8d14b36dce4ee2e --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/commands/user.py @@ -0,0 +1,188 @@ +# Copyright 2020 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import subprocess +from argparse import _SubParsersAction + +from requests.exceptions import HTTPError + +from huggingface_hub.commands import BaseHuggingfaceCLICommand +from huggingface_hub.constants import ( + ENDPOINT, + REPO_TYPES, + REPO_TYPES_URL_PREFIXES, + SPACES_SDK_TYPES, +) +from huggingface_hub.hf_api import HfApi + +from .._login import ( # noqa: F401 # for backward compatibility # noqa: F401 # for backward compatibility + NOTEBOOK_LOGIN_PASSWORD_HTML, + NOTEBOOK_LOGIN_TOKEN_HTML_END, + NOTEBOOK_LOGIN_TOKEN_HTML_START, + login, + logout, + notebook_login, +) +from ..utils import get_token +from ._cli_utils import ANSI + + +class UserCommands(BaseHuggingfaceCLICommand): + @staticmethod + def register_subcommand(parser: _SubParsersAction): + login_parser = parser.add_parser("login", help="Log in using a token from huggingface.co/settings/tokens") + login_parser.add_argument( + "--token", + type=str, + help="Token generated from https://huggingface.co/settings/tokens", + ) + login_parser.add_argument( + "--add-to-git-credential", + action="store_true", + help="Optional: Save token to git credential helper.", + ) + login_parser.set_defaults(func=lambda args: LoginCommand(args)) + whoami_parser = parser.add_parser("whoami", help="Find out which huggingface.co account you are logged in as.") + whoami_parser.set_defaults(func=lambda args: WhoamiCommand(args)) + logout_parser = parser.add_parser("logout", help="Log out") + logout_parser.set_defaults(func=lambda args: LogoutCommand(args)) + + # new system: git-based repo system + repo_parser = parser.add_parser("repo", help="{create} Commands to interact with your huggingface.co repos.") + repo_subparsers = repo_parser.add_subparsers(help="huggingface.co repos related commands") + repo_create_parser = repo_subparsers.add_parser("create", help="Create a new repo on huggingface.co") + repo_create_parser.add_argument( + "name", + type=str, + help="Name for your repo. Will be namespaced under your username to build the repo id.", + ) + repo_create_parser.add_argument( + "--type", + type=str, + help='Optional: repo_type: set to "dataset" or "space" if creating a dataset or space, default is model.', + ) + repo_create_parser.add_argument("--organization", type=str, help="Optional: organization namespace.") + repo_create_parser.add_argument( + "--space_sdk", + type=str, + help='Optional: Hugging Face Spaces SDK type. Required when --type is set to "space".', + choices=SPACES_SDK_TYPES, + ) + repo_create_parser.add_argument( + "-y", + "--yes", + action="store_true", + help="Optional: answer Yes to the prompt", + ) + repo_create_parser.set_defaults(func=lambda args: RepoCreateCommand(args)) + + +class BaseUserCommand: + def __init__(self, args): + self.args = args + self._api = HfApi() + + +class LoginCommand(BaseUserCommand): + def run(self): + login(token=self.args.token, add_to_git_credential=self.args.add_to_git_credential) + + +class LogoutCommand(BaseUserCommand): + def run(self): + logout() + + +class WhoamiCommand(BaseUserCommand): + def run(self): + token = get_token() + if token is None: + print("Not logged in") + exit() + try: + info = self._api.whoami(token) + print(info["name"]) + orgs = [org["name"] for org in info["orgs"]] + if orgs: + print(ANSI.bold("orgs: "), ",".join(orgs)) + + if ENDPOINT != "https://huggingface.co": + print(f"Authenticated through private endpoint: {ENDPOINT}") + except HTTPError as e: + print(e) + print(ANSI.red(e.response.text)) + exit(1) + + +class RepoCreateCommand(BaseUserCommand): + def run(self): + token = get_token() + if token is None: + print("Not logged in") + exit(1) + try: + stdout = subprocess.check_output(["git", "--version"]).decode("utf-8") + print(ANSI.gray(stdout.strip())) + except FileNotFoundError: + print("Looks like you do not have git installed, please install.") + + try: + stdout = subprocess.check_output(["git-lfs", "--version"]).decode("utf-8") + print(ANSI.gray(stdout.strip())) + except FileNotFoundError: + print( + ANSI.red( + "Looks like you do not have git-lfs installed, please install." + " You can install from https://git-lfs.github.com/." + " Then run `git lfs install` (you only have to do this once)." + ) + ) + print("") + + user = self._api.whoami(token)["name"] + namespace = self.args.organization if self.args.organization is not None else user + + repo_id = f"{namespace}/{self.args.name}" + + if self.args.type not in REPO_TYPES: + print("Invalid repo --type") + exit(1) + + if self.args.type in REPO_TYPES_URL_PREFIXES: + prefixed_repo_id = REPO_TYPES_URL_PREFIXES[self.args.type] + repo_id + else: + prefixed_repo_id = repo_id + + print(f"You are about to create {ANSI.bold(prefixed_repo_id)}") + + if not self.args.yes: + choice = input("Proceed? [Y/n] ").lower() + if not (choice == "" or choice == "y" or choice == "yes"): + print("Abort") + exit() + try: + url = self._api.create_repo( + repo_id=repo_id, + token=token, + repo_type=self.args.type, + space_sdk=self.args.space_sdk, + ) + except HTTPError as e: + print(e) + print(ANSI.red(e.response.text)) + exit(1) + print("\nYour repo now lives at:") + print(f" {ANSI.bold(url)}") + print("\nYou can clone it locally with the command below, and commit/push as usual.") + print(f"\n git clone {url}") + print("") diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/inference/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/inference/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/inference/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/inference/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2132dc0327a7b4bc8490efed699c386bd0df09fa Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/inference/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/inference/__pycache__/_client.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/inference/__pycache__/_client.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b4fde83f71ce2f0b6886e6644f66f0dd356cf3c9 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/inference/__pycache__/_client.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/inference/__pycache__/_common.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/inference/__pycache__/_common.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..343454a1b5fb50b8b3e7714a4ccb16d6020d96c9 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/inference/__pycache__/_common.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/inference/__pycache__/_text_generation.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/inference/__pycache__/_text_generation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d17aede8b3212457efb9c5bb97afc613b3eec408 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/inference/__pycache__/_text_generation.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/inference/__pycache__/_types.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/inference/__pycache__/_types.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f0489a52ea3b2c76fa83e80c546f6c7c7bc6e714 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/inference/__pycache__/_types.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/inference/_client.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/inference/_client.py new file mode 100644 index 0000000000000000000000000000000000000000..3a76f5ad152d6866dde3f88053816d98fda4901b --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/inference/_client.py @@ -0,0 +1,1990 @@ +# coding=utf-8 +# Copyright 2023-present, the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Related resources: +# https://huggingface.co/tasks +# https://huggingface.co/docs/huggingface.js/inference/README +# https://github.com/huggingface/huggingface.js/tree/main/packages/inference/src +# https://github.com/huggingface/text-generation-inference/tree/main/clients/python +# https://github.com/huggingface/text-generation-inference/blob/main/clients/python/text_generation/client.py +# https://huggingface.slack.com/archives/C03E4DQ9LAJ/p1680169099087869 +# https://github.com/huggingface/unity-api#tasks +# +# Some TODO: +# - validate inputs/options/parameters? with Pydantic for instance? or only optionally? +# - add all tasks +# +# NOTE: the philosophy of this client is "let's make it as easy as possible to use it, even if less optimized". Some +# examples of how it translates: +# - Timeout / Server unavailable is handled by the client in a single "timeout" parameter. +# - Files can be provided as bytes, file paths, or URLs and the client will try to "guess" the type. +# - Images are parsed as PIL.Image for easier manipulation. +# - Provides a "recommended model" for each task => suboptimal but user-wise quicker to get a first script running. +# - Only the main parameters are publicly exposed. Power users can always read the docs for more options. +import logging +import time +import warnings +from dataclasses import asdict +from typing import ( + TYPE_CHECKING, + Any, + Dict, + Iterable, + List, + Literal, + Optional, + Union, + overload, +) + +from requests import HTTPError +from requests.structures import CaseInsensitiveDict + +from huggingface_hub.constants import ALL_INFERENCE_API_FRAMEWORKS, INFERENCE_ENDPOINT, MAIN_INFERENCE_API_FRAMEWORKS +from huggingface_hub.inference._common import ( + TASKS_EXPECTING_IMAGES, + ContentT, + InferenceTimeoutError, + ModelStatus, + _b64_encode, + _b64_to_image, + _bytes_to_dict, + _bytes_to_image, + _bytes_to_list, + _fetch_recommended_models, + _import_numpy, + _is_tgi_server, + _open_as_binary, + _set_as_non_tgi, + _stream_text_generation_response, +) +from huggingface_hub.inference._text_generation import ( + TextGenerationParameters, + TextGenerationRequest, + TextGenerationResponse, + TextGenerationStreamResponse, + raise_text_generation_error, +) +from huggingface_hub.inference._types import ( + ClassificationOutput, + ConversationalOutput, + FillMaskOutput, + ImageSegmentationOutput, + ObjectDetectionOutput, + QuestionAnsweringOutput, + TableQuestionAnsweringOutput, + TokenClassificationOutput, +) +from huggingface_hub.utils import ( + BadRequestError, + build_hf_headers, + get_session, + hf_raise_for_status, +) + + +if TYPE_CHECKING: + import numpy as np + from PIL import Image + +logger = logging.getLogger(__name__) + + +class InferenceClient: + """ + Initialize a new Inference Client. + + [`InferenceClient`] aims to provide a unified experience to perform inference. The client can be used + seamlessly with either the (free) Inference API or self-hosted Inference Endpoints. + + Args: + model (`str`, `optional`): + The model to run inference with. Can be a model id hosted on the Hugging Face Hub, e.g. `bigcode/starcoder` + or a URL to a deployed Inference Endpoint. Defaults to None, in which case a recommended model is + automatically selected for the task. + token (`str`, *optional*): + Hugging Face token. Will default to the locally saved token. Pass `token=False` if you don't want to send + your token to the server. + timeout (`float`, `optional`): + The maximum number of seconds to wait for a response from the server. Loading a new model in Inference + API can take up to several minutes. Defaults to None, meaning it will loop until the server is available. + headers (`Dict[str, str]`, `optional`): + Additional headers to send to the server. By default only the authorization and user-agent headers are sent. + Values in this dictionary will override the default values. + cookies (`Dict[str, str]`, `optional`): + Additional cookies to send to the server. + """ + + def __init__( + self, + model: Optional[str] = None, + token: Union[str, bool, None] = None, + timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + cookies: Optional[Dict[str, str]] = None, + ) -> None: + self.model: Optional[str] = model + self.headers = CaseInsensitiveDict(build_hf_headers(token=token)) # contains 'authorization' + 'user-agent' + if headers is not None: + self.headers.update(headers) + self.cookies = cookies + self.timeout = timeout + + def __repr__(self): + return f"" + + @overload + def post( # type: ignore[misc] + self, + *, + json: Optional[Union[str, Dict, List]] = None, + data: Optional[ContentT] = None, + model: Optional[str] = None, + task: Optional[str] = None, + stream: Literal[False] = ..., + ) -> bytes: + pass + + @overload + def post( + self, + *, + json: Optional[Union[str, Dict, List]] = None, + data: Optional[ContentT] = None, + model: Optional[str] = None, + task: Optional[str] = None, + stream: Literal[True] = ..., + ) -> Iterable[bytes]: + pass + + def post( + self, + *, + json: Optional[Union[str, Dict, List]] = None, + data: Optional[ContentT] = None, + model: Optional[str] = None, + task: Optional[str] = None, + stream: bool = False, + ) -> Union[bytes, Iterable[bytes]]: + """ + Make a POST request to the inference server. + + Args: + json (`Union[str, Dict, List]`, *optional*): + The JSON data to send in the request body, specific to each task. Defaults to None. + data (`Union[str, Path, bytes, BinaryIO]`, *optional*): + The content to send in the request body, specific to each task. + It can be raw bytes, a pointer to an opened file, a local file path, + or a URL to an online resource (image, audio file,...). If both `json` and `data` are passed, + `data` will take precedence. At least `json` or `data` must be provided. Defaults to None. + model (`str`, *optional*): + The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed + Inference Endpoint. Will override the model defined at the instance level. Defaults to None. + task (`str`, *optional*): + The task to perform on the inference. All available tasks can be found + [here](https://huggingface.co/tasks). Used only to default to a recommended model if `model` is not + provided. At least `model` or `task` must be provided. Defaults to None. + stream (`bool`, *optional*): + Whether to iterate over streaming APIs. + + Returns: + bytes: The raw bytes returned by the server. + + Raises: + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `HTTPError`: + If the request fails with an HTTP error status code other than HTTP 503. + """ + url = self._resolve_url(model, task) + + if data is not None and json is not None: + warnings.warn("Ignoring `json` as `data` is passed as binary.") + + # Set Accept header if relevant + headers = self.headers.copy() + if task in TASKS_EXPECTING_IMAGES and "Accept" not in headers: + headers["Accept"] = "image/png" + + t0 = time.time() + timeout = self.timeout + while True: + with _open_as_binary(data) as data_as_binary: + try: + response = get_session().post( + url, + json=json, + data=data_as_binary, + headers=headers, + cookies=self.cookies, + timeout=self.timeout, + stream=stream, + ) + except TimeoutError as error: + # Convert any `TimeoutError` to a `InferenceTimeoutError` + raise InferenceTimeoutError(f"Inference call timed out: {url}") from error # type: ignore + + try: + hf_raise_for_status(response) + return response.iter_lines() if stream else response.content + except HTTPError as error: + if error.response.status_code == 422 and task is not None: + error.args = ( + f"{error.args[0]}\nMake sure '{task}' task is supported by the model.", + ) + error.args[1:] + if error.response.status_code == 503: + # If Model is unavailable, either raise a TimeoutError... + if timeout is not None and time.time() - t0 > timeout: + raise InferenceTimeoutError( + f"Model not loaded on the server: {url}. Please retry with a higher timeout (current:" + f" {self.timeout}).", + request=error.request, + response=error.response, + ) from error + # ...or wait 1s and retry + logger.info(f"Waiting for model to be loaded on the server: {error}") + time.sleep(1) + if timeout is not None: + timeout = max(self.timeout - (time.time() - t0), 1) # type: ignore + continue + raise + + def audio_classification( + self, + audio: ContentT, + *, + model: Optional[str] = None, + ) -> List[ClassificationOutput]: + """ + Perform audio classification on the provided audio content. + + Args: + audio (Union[str, Path, bytes, BinaryIO]): + The audio content to classify. It can be raw audio bytes, a local audio file, or a URL pointing to an + audio file. + model (`str`, *optional*): + The model to use for audio classification. Can be a model ID hosted on the Hugging Face Hub + or a URL to a deployed Inference Endpoint. If not provided, the default recommended model for + audio classification will be used. + + Returns: + `List[Dict]`: The classification output containing the predicted label and its confidence. + + Raises: + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `HTTPError`: + If the request fails with an HTTP error status code other than HTTP 503. + + Example: + ```py + >>> from huggingface_hub import InferenceClient + >>> client = InferenceClient() + >>> client.audio_classification("audio.flac") + [{'score': 0.4976358711719513, 'label': 'hap'}, {'score': 0.3677836060523987, 'label': 'neu'},...] + ``` + """ + response = self.post(data=audio, model=model, task="audio-classification") + return _bytes_to_list(response) + + def automatic_speech_recognition( + self, + audio: ContentT, + *, + model: Optional[str] = None, + ) -> str: + """ + Perform automatic speech recognition (ASR or audio-to-text) on the given audio content. + + Args: + audio (Union[str, Path, bytes, BinaryIO]): + The content to transcribe. It can be raw audio bytes, local audio file, or a URL to an audio file. + model (`str`, *optional*): + The model to use for ASR. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed + Inference Endpoint. If not provided, the default recommended model for ASR will be used. + + Returns: + str: The transcribed text. + + Raises: + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `HTTPError`: + If the request fails with an HTTP error status code other than HTTP 503. + + Example: + ```py + >>> from huggingface_hub import InferenceClient + >>> client = InferenceClient() + >>> client.automatic_speech_recognition("hello_world.flac") + "hello world" + ``` + """ + response = self.post(data=audio, model=model, task="automatic-speech-recognition") + return _bytes_to_dict(response)["text"] + + def conversational( + self, + text: str, + generated_responses: Optional[List[str]] = None, + past_user_inputs: Optional[List[str]] = None, + *, + parameters: Optional[Dict[str, Any]] = None, + model: Optional[str] = None, + ) -> ConversationalOutput: + """ + Generate conversational responses based on the given input text (i.e. chat with the API). + + Args: + text (`str`): + The last input from the user in the conversation. + generated_responses (`List[str]`, *optional*): + A list of strings corresponding to the earlier replies from the model. Defaults to None. + past_user_inputs (`List[str]`, *optional*): + A list of strings corresponding to the earlier replies from the user. Should be the same length as + `generated_responses`. Defaults to None. + parameters (`Dict[str, Any]`, *optional*): + Additional parameters for the conversational task. Defaults to None. For more details about the available + parameters, please refer to [this page](https://huggingface.co/docs/api-inference/detailed_parameters#conversational-task) + model (`str`, *optional*): + The model to use for the conversational task. Can be a model ID hosted on the Hugging Face Hub or a URL to + a deployed Inference Endpoint. If not provided, the default recommended conversational model will be used. + Defaults to None. + + Returns: + `Dict`: The generated conversational output. + + Raises: + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `HTTPError`: + If the request fails with an HTTP error status code other than HTTP 503. + + Example: + ```py + >>> from huggingface_hub import InferenceClient + >>> client = InferenceClient() + >>> output = client.conversational("Hi, who are you?") + >>> output + {'generated_text': 'I am the one who knocks.', 'conversation': {'generated_responses': ['I am the one who knocks.'], 'past_user_inputs': ['Hi, who are you?']}, 'warnings': ['Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation.']} + >>> client.conversational( + ... "Wow, that's scary!", + ... generated_responses=output["conversation"]["generated_responses"], + ... past_user_inputs=output["conversation"]["past_user_inputs"], + ... ) + ``` + """ + payload: Dict[str, Any] = {"inputs": {"text": text}} + if generated_responses is not None: + payload["inputs"]["generated_responses"] = generated_responses + if past_user_inputs is not None: + payload["inputs"]["past_user_inputs"] = past_user_inputs + if parameters is not None: + payload["parameters"] = parameters + response = self.post(json=payload, model=model, task="conversational") + return _bytes_to_dict(response) # type: ignore + + def visual_question_answering( + self, + image: ContentT, + question: str, + *, + model: Optional[str] = None, + ) -> List[str]: + """ + Answering open-ended questions based on an image. + + Args: + image (`Union[str, Path, bytes, BinaryIO]`): + The input image for the context. It can be raw bytes, an image file, or a URL to an online image. + question (`str`): + Question to be answered. + model (`str`, *optional*): + The model to use for the visual question answering task. Can be a model ID hosted on the Hugging Face Hub or a URL to + a deployed Inference Endpoint. If not provided, the default recommended visual question answering model will be used. + Defaults to None. + + Returns: + `List[Dict]`: a list of dictionaries containing the predicted label and associated probability. + + Raises: + `InferenceTimeoutError`: + If the model is unavailable or the request times out. + `HTTPError`: + If the request fails with an HTTP error status code other than HTTP 503. + + Example: + ```py + >>> from huggingface_hub import InferenceClient + >>> client = InferenceClient() + >>> client.visual_question_answering( + ... image="https://huggingface.co/datasets/mishig/sample_images/resolve/main/tiger.jpg", + ... question="What is the animal doing?" + ... ) + [{'score': 0.778609573841095, 'answer': 'laying down'},{'score': 0.6957435607910156, 'answer': 'sitting'}, ...] + ``` + """ + payload: Dict[str, Any] = {"question": question, "image": _b64_encode(image)} + response = self.post(json=payload, model=model, task="visual-question-answering") + return _bytes_to_list(response) + + def document_question_answering( + self, + image: ContentT, + question: str, + *, + model: Optional[str] = None, + ) -> List[QuestionAnsweringOutput]: + """ + Answer questions on document images. + + Args: + image (`Union[str, Path, bytes, BinaryIO]`): + The input image for the context. It can be raw bytes, an image file, or a URL to an online image. + question (`str`): + Question to be answered. + model (`str`, *optional*): + The model to use for the document question answering task. Can be a model ID hosted on the Hugging Face Hub or a URL to + a deployed Inference Endpoint. If not provided, the default recommended document question answering model will be used. + Defaults to None. + + Returns: + `List[Dict]`: a list of dictionaries containing the predicted label, associated probability, word ids, and page number. + + Raises: + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `HTTPError`: + If the request fails with an HTTP error status code other than HTTP 503. + + Example: + ```py + >>> from huggingface_hub import InferenceClient + >>> client = InferenceClient() + >>> client.document_question_answering(image="https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png", question="What is the invoice number?") + [{'score': 0.42515629529953003, 'answer': 'us-001', 'start': 16, 'end': 16}] + ``` + """ + payload: Dict[str, Any] = {"question": question, "image": _b64_encode(image)} + response = self.post(json=payload, model=model, task="document-question-answering") + return _bytes_to_list(response) + + def feature_extraction(self, text: str, *, model: Optional[str] = None) -> "np.ndarray": + """ + Generate embeddings for a given text. + + Args: + text (`str`): + The text to embed. + model (`str`, *optional*): + The model to use for the conversational task. Can be a model ID hosted on the Hugging Face Hub or a URL to + a deployed Inference Endpoint. If not provided, the default recommended conversational model will be used. + Defaults to None. + + Returns: + `np.ndarray`: The embedding representing the input text as a float32 numpy array. + + Raises: + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `HTTPError`: + If the request fails with an HTTP error status code other than HTTP 503. + + Example: + ```py + >>> from huggingface_hub import InferenceClient + >>> client = InferenceClient() + >>> client.feature_extraction("Hi, who are you?") + array([[ 2.424802 , 2.93384 , 1.1750331 , ..., 1.240499, -0.13776633, -0.7889173 ], + [-0.42943227, -0.6364878 , -1.693462 , ..., 0.41978157, -2.4336355 , 0.6162071 ], + ..., + [ 0.28552425, -0.928395 , -1.2077185 , ..., 0.76810825, -2.1069427 , 0.6236161 ]], dtype=float32) + ``` + """ + response = self.post(json={"inputs": text}, model=model, task="feature-extraction") + np = _import_numpy() + return np.array(_bytes_to_dict(response), dtype="float32") + + def fill_mask(self, text: str, *, model: Optional[str] = None) -> List[FillMaskOutput]: + """ + Fill in a hole with a missing word (token to be precise). + + Args: + text (`str`): + a string to be filled from, must contain the [MASK] token (check model card for exact name of the mask). + model (`str`, *optional*): + The model to use for the fill mask task. Can be a model ID hosted on the Hugging Face Hub or a URL to + a deployed Inference Endpoint. If not provided, the default recommended fill mask model will be used. + Defaults to None. + + Returns: + `List[Dict]`: a list of fill mask output dictionaries containing the predicted label, associated + probability, token reference, and completed text. + + Raises: + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `HTTPError`: + If the request fails with an HTTP error status code other than HTTP 503. + + Example: + ```py + >>> from huggingface_hub import InferenceClient + >>> client = InferenceClient() + >>> client.fill_mask("The goal of life is .") + [{'score': 0.06897063553333282, + 'token': 11098, + 'token_str': ' happiness', + 'sequence': 'The goal of life is happiness.'}, + {'score': 0.06554922461509705, + 'token': 45075, + 'token_str': ' immortality', + 'sequence': 'The goal of life is immortality.'}] + ``` + """ + response = self.post(json={"inputs": text}, model=model, task="fill-mask") + return _bytes_to_list(response) + + def image_classification( + self, + image: ContentT, + *, + model: Optional[str] = None, + ) -> List[ClassificationOutput]: + """ + Perform image classification on the given image using the specified model. + + Args: + image (`Union[str, Path, bytes, BinaryIO]`): + The image to classify. It can be raw bytes, an image file, or a URL to an online image. + model (`str`, *optional*): + The model to use for image classification. Can be a model ID hosted on the Hugging Face Hub or a URL to a + deployed Inference Endpoint. If not provided, the default recommended model for image classification will be used. + + Returns: + `List[Dict]`: a list of dictionaries containing the predicted label and associated probability. + + Raises: + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `HTTPError`: + If the request fails with an HTTP error status code other than HTTP 503. + + Example: + ```py + >>> from huggingface_hub import InferenceClient + >>> client = InferenceClient() + >>> client.image_classification("https://upload.wikimedia.org/wikipedia/commons/thumb/4/43/Cute_dog.jpg/320px-Cute_dog.jpg") + [{'score': 0.9779096841812134, 'label': 'Blenheim spaniel'}, ...] + ``` + """ + response = self.post(data=image, model=model, task="image-classification") + return _bytes_to_list(response) + + def image_segmentation( + self, + image: ContentT, + *, + model: Optional[str] = None, + ) -> List[ImageSegmentationOutput]: + """ + Perform image segmentation on the given image using the specified model. + + + + You must have `PIL` installed if you want to work with images (`pip install Pillow`). + + + + Args: + image (`Union[str, Path, bytes, BinaryIO]`): + The image to segment. It can be raw bytes, an image file, or a URL to an online image. + model (`str`, *optional*): + The model to use for image segmentation. Can be a model ID hosted on the Hugging Face Hub or a URL to a + deployed Inference Endpoint. If not provided, the default recommended model for image segmentation will be used. + + Returns: + `List[Dict]`: A list of dictionaries containing the segmented masks and associated attributes. + + Raises: + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `HTTPError`: + If the request fails with an HTTP error status code other than HTTP 503. + + Example: + ```py + >>> from huggingface_hub import InferenceClient + >>> client = InferenceClient() + >>> client.image_segmentation("cat.jpg"): + [{'score': 0.989008, 'label': 'LABEL_184', 'mask': }, ...] + ``` + """ + + # Segment + response = self.post(data=image, model=model, task="image-segmentation") + output = _bytes_to_dict(response) + + # Parse masks as PIL Image + if not isinstance(output, list): + raise ValueError(f"Server output must be a list. Got {type(output)}: {str(output)[:200]}...") + for item in output: + item["mask"] = _b64_to_image(item["mask"]) + return output + + def image_to_image( + self, + image: ContentT, + prompt: Optional[str] = None, + *, + negative_prompt: Optional[str] = None, + height: Optional[int] = None, + width: Optional[int] = None, + num_inference_steps: Optional[int] = None, + guidance_scale: Optional[float] = None, + model: Optional[str] = None, + **kwargs, + ) -> "Image": + """ + Perform image-to-image translation using a specified model. + + + + You must have `PIL` installed if you want to work with images (`pip install Pillow`). + + + + Args: + image (`Union[str, Path, bytes, BinaryIO]`): + The input image for translation. It can be raw bytes, an image file, or a URL to an online image. + prompt (`str`, *optional*): + The text prompt to guide the image generation. + negative_prompt (`str`, *optional*): + A negative prompt to guide the translation process. + height (`int`, *optional*): + The height in pixels of the generated image. + width (`int`, *optional*): + The width in pixels of the generated image. + num_inference_steps (`int`, *optional*): + The number of denoising steps. More denoising steps usually lead to a higher quality image at the + expense of slower inference. + guidance_scale (`float`, *optional*): + Higher guidance scale encourages to generate images that are closely linked to the text `prompt`, + usually at the expense of lower image quality. + model (`str`, *optional*): + The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed + Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None. + + Returns: + `Image`: The translated image. + + Raises: + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `HTTPError`: + If the request fails with an HTTP error status code other than HTTP 503. + + Example: + ```py + >>> from huggingface_hub import InferenceClient + >>> client = InferenceClient() + >>> image = client.image_to_image("cat.jpg", prompt="turn the cat into a tiger") + >>> image.save("tiger.jpg") + ``` + """ + parameters = { + "prompt": prompt, + "negative_prompt": negative_prompt, + "height": height, + "width": width, + "num_inference_steps": num_inference_steps, + "guidance_scale": guidance_scale, + **kwargs, + } + if all(parameter is None for parameter in parameters.values()): + # Either only an image to send => send as raw bytes + data = image + payload: Optional[Dict[str, Any]] = None + else: + # Or an image + some parameters => use base64 encoding + data = None + payload = {"inputs": _b64_encode(image)} + for key, value in parameters.items(): + if value is not None: + payload.setdefault("parameters", {})[key] = value + + response = self.post(json=payload, data=data, model=model, task="image-to-image") + return _bytes_to_image(response) + + def image_to_text(self, image: ContentT, *, model: Optional[str] = None) -> str: + """ + Takes an input image and return text. + + Models can have very different outputs depending on your use case (image captioning, optical character recognition + (OCR), Pix2Struct, etc). Please have a look to the model card to learn more about a model's specificities. + + Args: + image (`Union[str, Path, bytes, BinaryIO]`): + The input image to caption. It can be raw bytes, an image file, or a URL to an online image.. + model (`str`, *optional*): + The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed + Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None. + + Returns: + `str`: The generated text. + + Raises: + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `HTTPError`: + If the request fails with an HTTP error status code other than HTTP 503. + + Example: + ```py + >>> from huggingface_hub import InferenceClient + >>> client = InferenceClient() + >>> client.image_to_text("cat.jpg") + 'a cat standing in a grassy field ' + >>> client.image_to_text("https://upload.wikimedia.org/wikipedia/commons/thumb/4/43/Cute_dog.jpg/320px-Cute_dog.jpg") + 'a dog laying on the grass next to a flower pot ' + ``` + """ + response = self.post(data=image, model=model, task="image-to-text") + return _bytes_to_dict(response)[0]["generated_text"] + + def list_deployed_models( + self, frameworks: Union[None, str, Literal["all"], List[str]] = None + ) -> Dict[str, List[str]]: + """ + List models currently deployed on the Inference API service. + + This helper checks deployed models framework by framework. By default, it will check the 4 main frameworks that + are supported and account for 95% of the hosted models. However, if you want a complete list of models you can + specify `frameworks="all"` as input. Alternatively, if you know before-hand which framework you are interested + in, you can also restrict to search to this one (e.g. `frameworks="text-generation-inference"`). The more + frameworks are checked, the more time it will take. + + + + This endpoint is mostly useful for discoverability. If you already know which model you want to use and want to + check its availability, you can directly use [`~InferenceClient.get_model_status`]. + + + + Args: + frameworks (`Literal["all"]` or `List[str]` or `str`, *optional*): + The frameworks to filter on. By default only a subset of the available frameworks are tested. If set to + "all", all available frameworks will be tested. It is also possible to provide a single framework or a + custom set of frameworks to check. + + Returns: + `Dict[str, List[str]]`: A dictionary mapping task names to a sorted list of model IDs. + + Example: + ```python + >>> from huggingface_hub import InferenceClient + >>> client = InferenceClient() + + # Discover zero-shot-classification models currently deployed + >>> models = client.list_deployed_models() + >>> models["zero-shot-classification"] + ['Narsil/deberta-large-mnli-zero-cls', 'facebook/bart-large-mnli', ...] + + # List from only 1 framework + >>> client.list_deployed_models("text-generation-inference") + {'text-generation': ['bigcode/starcoder', 'meta-llama/Llama-2-70b-chat-hf', ...], ...} + ``` + """ + # Resolve which frameworks to check + if frameworks is None: + frameworks = MAIN_INFERENCE_API_FRAMEWORKS + elif frameworks == "all": + frameworks = ALL_INFERENCE_API_FRAMEWORKS + elif isinstance(frameworks, str): + frameworks = [frameworks] + frameworks = list(set(frameworks)) + + # Fetch them iteratively + models_by_task: Dict[str, List[str]] = {} + + def _unpack_response(framework: str, items: List[Dict]) -> None: + for model in items: + if framework == "sentence-transformers": + # Model running with the `sentence-transformers` framework can work with both tasks even if not + # branded as such in the API response + models_by_task.setdefault("feature-extraction", []).append(model["model_id"]) + models_by_task.setdefault("sentence-similarity", []).append(model["model_id"]) + else: + models_by_task.setdefault(model["task"], []).append(model["model_id"]) + + for framework in frameworks: + response = get_session().get(f"{INFERENCE_ENDPOINT}/framework/{framework}", headers=self.headers) + hf_raise_for_status(response) + _unpack_response(framework, response.json()) + + # Sort alphabetically for discoverability and return + for task, models in models_by_task.items(): + models_by_task[task] = sorted(set(models), key=lambda x: x.lower()) + return models_by_task + + def object_detection( + self, + image: ContentT, + *, + model: Optional[str] = None, + ) -> List[ObjectDetectionOutput]: + """ + Perform object detection on the given image using the specified model. + + + + You must have `PIL` installed if you want to work with images (`pip install Pillow`). + + + + Args: + image (`Union[str, Path, bytes, BinaryIO]`): + The image to detect objects on. It can be raw bytes, an image file, or a URL to an online image. + model (`str`, *optional*): + The model to use for object detection. Can be a model ID hosted on the Hugging Face Hub or a URL to a + deployed Inference Endpoint. If not provided, the default recommended model for object detection (DETR) will be used. + + Returns: + `List[ObjectDetectionOutput]`: A list of dictionaries containing the bounding boxes and associated attributes. + + Raises: + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `HTTPError`: + If the request fails with an HTTP error status code other than HTTP 503. + `ValueError`: + If the request output is not a List. + + Example: + ```py + >>> from huggingface_hub import InferenceClient + >>> client = InferenceClient() + >>> client.object_detection("people.jpg"): + [{"score":0.9486683011054993,"label":"person","box":{"xmin":59,"ymin":39,"xmax":420,"ymax":510}}, ... ] + ``` + """ + # detect objects + response = self.post(data=image, model=model, task="object-detection") + output = _bytes_to_dict(response) + if not isinstance(output, list): + raise ValueError(f"Server output must be a list. Got {type(output)}: {str(output)[:200]}...") + return output + + def question_answering( + self, question: str, context: str, *, model: Optional[str] = None + ) -> QuestionAnsweringOutput: + """ + Retrieve the answer to a question from a given text. + + Args: + question (`str`): + Question to be answered. + context (`str`): + The context of the question. + model (`str`): + The model to use for the question answering task. Can be a model ID hosted on the Hugging Face Hub or a URL to + a deployed Inference Endpoint. + + Returns: + `Dict`: a dictionary of question answering output containing the score, start index, end index, and answer. + + Raises: + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `HTTPError`: + If the request fails with an HTTP error status code other than HTTP 503. + + Example: + ```py + >>> from huggingface_hub import InferenceClient + >>> client = InferenceClient() + >>> client.question_answering(question="What's my name?", context="My name is Clara and I live in Berkeley.") + {'score': 0.9326562285423279, 'start': 11, 'end': 16, 'answer': 'Clara'} + ``` + """ + + payload: Dict[str, Any] = {"question": question, "context": context} + response = self.post( + json=payload, + model=model, + task="question-answering", + ) + return _bytes_to_dict(response) # type: ignore + + def sentence_similarity( + self, sentence: str, other_sentences: List[str], *, model: Optional[str] = None + ) -> List[float]: + """ + Compute the semantic similarity between a sentence and a list of other sentences by comparing their embeddings. + + Args: + sentence (`str`): + The main sentence to compare to others. + other_sentences (`List[str]`): + The list of sentences to compare to. + model (`str`, *optional*): + The model to use for the conversational task. Can be a model ID hosted on the Hugging Face Hub or a URL to + a deployed Inference Endpoint. If not provided, the default recommended conversational model will be used. + Defaults to None. + + Returns: + `List[float]`: The embedding representing the input text. + + Raises: + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `HTTPError`: + If the request fails with an HTTP error status code other than HTTP 503. + + Example: + ```py + >>> from huggingface_hub import InferenceClient + >>> client = InferenceClient() + >>> client.sentence_similarity( + ... "Machine learning is so easy.", + ... other_sentences=[ + ... "Deep learning is so straightforward.", + ... "This is so difficult, like rocket science.", + ... "I can't believe how much I struggled with this.", + ... ], + ... ) + [0.7785726189613342, 0.45876261591911316, 0.2906220555305481] + ``` + """ + response = self.post( + json={"inputs": {"source_sentence": sentence, "sentences": other_sentences}}, + model=model, + task="sentence-similarity", + ) + return _bytes_to_list(response) + + def summarization( + self, + text: str, + *, + parameters: Optional[Dict[str, Any]] = None, + model: Optional[str] = None, + ) -> str: + """ + Generate a summary of a given text using a specified model. + + Args: + text (`str`): + The input text to summarize. + parameters (`Dict[str, Any]`, *optional*): + Additional parameters for summarization. Check out this [page](https://huggingface.co/docs/api-inference/detailed_parameters#summarization-task) + for more details. + model (`str`, *optional*): + The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed + Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None. + + Returns: + `str`: The generated summary text. + + Raises: + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `HTTPError`: + If the request fails with an HTTP error status code other than HTTP 503. + + Example: + ```py + >>> from huggingface_hub import InferenceClient + >>> client = InferenceClient() + >>> client.summarization("The Eiffel tower...") + 'The Eiffel tower is one of the most famous landmarks in the world....' + ``` + """ + payload: Dict[str, Any] = {"inputs": text} + if parameters is not None: + payload["parameters"] = parameters + response = self.post(json=payload, model=model, task="summarization") + return _bytes_to_dict(response)[0]["summary_text"] + + def table_question_answering( + self, table: Dict[str, Any], query: str, *, model: Optional[str] = None + ) -> TableQuestionAnsweringOutput: + """ + Retrieve the answer to a question from information given in a table. + + Args: + table (`str`): + A table of data represented as a dict of lists where entries are headers and the lists are all the + values, all lists must have the same size. + query (`str`): + The query in plain text that you want to ask the table. + model (`str`): + The model to use for the table-question-answering task. Can be a model ID hosted on the Hugging Face + Hub or a URL to a deployed Inference Endpoint. + + Returns: + `Dict`: a dictionary of table question answering output containing the answer, coordinates, cells and the aggregator used. + + Raises: + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `HTTPError`: + If the request fails with an HTTP error status code other than HTTP 503. + + Example: + ```py + >>> from huggingface_hub import InferenceClient + >>> client = InferenceClient() + >>> query = "How many stars does the transformers repository have?" + >>> table = {"Repository": ["Transformers", "Datasets", "Tokenizers"], "Stars": ["36542", "4512", "3934"]} + >>> client.table_question_answering(table, query, model="google/tapas-base-finetuned-wtq") + {'answer': 'AVERAGE > 36542', 'coordinates': [[0, 1]], 'cells': ['36542'], 'aggregator': 'AVERAGE'} + ``` + """ + response = self.post( + json={ + "query": query, + "table": table, + }, + model=model, + task="table-question-answering", + ) + return _bytes_to_dict(response) # type: ignore + + def tabular_classification(self, table: Dict[str, Any], *, model: str) -> List[str]: + """ + Classifying a target category (a group) based on a set of attributes. + + Args: + table (`Dict[str, Any]`): + Set of attributes to classify. + model (`str`): + The model to use for the tabular-classification task. Can be a model ID hosted on the Hugging Face Hub or a URL to + a deployed Inference Endpoint. + + Returns: + `List`: a list of labels, one per row in the initial table. + + Raises: + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `HTTPError`: + If the request fails with an HTTP error status code other than HTTP 503. + + Example: + ```py + >>> from huggingface_hub import InferenceClient + >>> client = InferenceClient() + >>> table = { + ... "fixed_acidity": ["7.4", "7.8", "10.3"], + ... "volatile_acidity": ["0.7", "0.88", "0.32"], + ... "citric_acid": ["0", "0", "0.45"], + ... "residual_sugar": ["1.9", "2.6", "6.4"], + ... "chlorides": ["0.076", "0.098", "0.073"], + ... "free_sulfur_dioxide": ["11", "25", "5"], + ... "total_sulfur_dioxide": ["34", "67", "13"], + ... "density": ["0.9978", "0.9968", "0.9976"], + ... "pH": ["3.51", "3.2", "3.23"], + ... "sulphates": ["0.56", "0.68", "0.82"], + ... "alcohol": ["9.4", "9.8", "12.6"], + ... } + >>> client.tabular_classification(table=table, model="julien-c/wine-quality") + ["5", "5", "5"] + ``` + """ + response = self.post(json={"table": table}, model=model, task="tabular-classification") + return _bytes_to_list(response) + + def tabular_regression(self, table: Dict[str, Any], *, model: str) -> List[float]: + """ + Predicting a numerical target value given a set of attributes/features in a table. + + Args: + table (`Dict[str, Any]`): + Set of attributes stored in a table. The attributes used to predict the target can be both numerical and categorical. + model (`str`): + The model to use for the tabular-regression task. Can be a model ID hosted on the Hugging Face Hub or a URL to + a deployed Inference Endpoint. + + Returns: + `List`: a list of predicted numerical target values. + + Raises: + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `HTTPError`: + If the request fails with an HTTP error status code other than HTTP 503. + + Example: + ```py + >>> from huggingface_hub import InferenceClient + >>> client = InferenceClient() + >>> table = { + ... "Height": ["11.52", "12.48", "12.3778"], + ... "Length1": ["23.2", "24", "23.9"], + ... "Length2": ["25.4", "26.3", "26.5"], + ... "Length3": ["30", "31.2", "31.1"], + ... "Species": ["Bream", "Bream", "Bream"], + ... "Width": ["4.02", "4.3056", "4.6961"], + ... } + >>> client.tabular_regression(table, model="scikit-learn/Fish-Weight") + [110, 120, 130] + ``` + """ + response = self.post(json={"table": table}, model=model, task="tabular-regression") + return _bytes_to_list(response) + + def text_classification(self, text: str, *, model: Optional[str] = None) -> List[ClassificationOutput]: + """ + Perform text classification (e.g. sentiment-analysis) on the given text. + + Args: + text (`str`): + A string to be classified. + model (`str`, *optional*): + The model to use for the text classification task. Can be a model ID hosted on the Hugging Face Hub or a URL to + a deployed Inference Endpoint. If not provided, the default recommended text classification model will be used. + Defaults to None. + + Returns: + `List[Dict]`: a list of dictionaries containing the predicted label and associated probability. + + Raises: + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `HTTPError`: + If the request fails with an HTTP error status code other than HTTP 503. + + Example: + ```py + >>> from huggingface_hub import InferenceClient + >>> client = InferenceClient() + >>> client.text_classification("I like you") + [{'label': 'POSITIVE', 'score': 0.9998695850372314}, {'label': 'NEGATIVE', 'score': 0.0001304351753788069}] + ``` + """ + response = self.post(json={"inputs": text}, model=model, task="text-classification") + return _bytes_to_list(response)[0] + + @overload + def text_generation( # type: ignore + self, + prompt: str, + *, + details: Literal[False] = ..., + stream: Literal[False] = ..., + model: Optional[str] = None, + do_sample: bool = False, + max_new_tokens: int = 20, + best_of: Optional[int] = None, + repetition_penalty: Optional[float] = None, + return_full_text: bool = False, + seed: Optional[int] = None, + stop_sequences: Optional[List[str]] = None, + temperature: Optional[float] = None, + top_k: Optional[int] = None, + top_p: Optional[float] = None, + truncate: Optional[int] = None, + typical_p: Optional[float] = None, + watermark: bool = False, + ) -> str: + ... + + @overload + def text_generation( # type: ignore + self, + prompt: str, + *, + details: Literal[True] = ..., + stream: Literal[False] = ..., + model: Optional[str] = None, + do_sample: bool = False, + max_new_tokens: int = 20, + best_of: Optional[int] = None, + repetition_penalty: Optional[float] = None, + return_full_text: bool = False, + seed: Optional[int] = None, + stop_sequences: Optional[List[str]] = None, + temperature: Optional[float] = None, + top_k: Optional[int] = None, + top_p: Optional[float] = None, + truncate: Optional[int] = None, + typical_p: Optional[float] = None, + watermark: bool = False, + ) -> TextGenerationResponse: + ... + + @overload + def text_generation( # type: ignore + self, + prompt: str, + *, + details: Literal[False] = ..., + stream: Literal[True] = ..., + model: Optional[str] = None, + do_sample: bool = False, + max_new_tokens: int = 20, + best_of: Optional[int] = None, + repetition_penalty: Optional[float] = None, + return_full_text: bool = False, + seed: Optional[int] = None, + stop_sequences: Optional[List[str]] = None, + temperature: Optional[float] = None, + top_k: Optional[int] = None, + top_p: Optional[float] = None, + truncate: Optional[int] = None, + typical_p: Optional[float] = None, + watermark: bool = False, + ) -> Iterable[str]: + ... + + @overload + def text_generation( + self, + prompt: str, + *, + details: Literal[True] = ..., + stream: Literal[True] = ..., + model: Optional[str] = None, + do_sample: bool = False, + max_new_tokens: int = 20, + best_of: Optional[int] = None, + repetition_penalty: Optional[float] = None, + return_full_text: bool = False, + seed: Optional[int] = None, + stop_sequences: Optional[List[str]] = None, + temperature: Optional[float] = None, + top_k: Optional[int] = None, + top_p: Optional[float] = None, + truncate: Optional[int] = None, + typical_p: Optional[float] = None, + watermark: bool = False, + ) -> Iterable[TextGenerationStreamResponse]: + ... + + def text_generation( + self, + prompt: str, + *, + details: bool = False, + stream: bool = False, + model: Optional[str] = None, + do_sample: bool = False, + max_new_tokens: int = 20, + best_of: Optional[int] = None, + repetition_penalty: Optional[float] = None, + return_full_text: bool = False, + seed: Optional[int] = None, + stop_sequences: Optional[List[str]] = None, + temperature: Optional[float] = None, + top_k: Optional[int] = None, + top_p: Optional[float] = None, + truncate: Optional[int] = None, + typical_p: Optional[float] = None, + watermark: bool = False, + decoder_input_details: bool = False, + ) -> Union[str, TextGenerationResponse, Iterable[str], Iterable[TextGenerationStreamResponse]]: + """ + Given a prompt, generate the following text. + + It is recommended to have Pydantic installed in order to get inputs validated. This is preferable as it allow + early failures. + + API endpoint is supposed to run with the `text-generation-inference` backend (TGI). This backend is the + go-to solution to run large language models at scale. However, for some smaller models (e.g. "gpt2") the + default `transformers` + `api-inference` solution is still in use. Both approaches have very similar APIs, but + not exactly the same. This method is compatible with both approaches but some parameters are only available for + `text-generation-inference`. If some parameters are ignored, a warning message is triggered but the process + continues correctly. + + To learn more about the TGI project, please refer to https://github.com/huggingface/text-generation-inference. + + Args: + prompt (`str`): + Input text. + details (`bool`, *optional*): + By default, text_generation returns a string. Pass `details=True` if you want a detailed output (tokens, + probabilities, seed, finish reason, etc.). Only available for models running on with the + `text-generation-inference` backend. + stream (`bool`, *optional*): + By default, text_generation returns the full generated text. Pass `stream=True` if you want a stream of + tokens to be returned. Only available for models running on with the `text-generation-inference` + backend. + model (`str`, *optional*): + The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed + Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None. + do_sample (`bool`): + Activate logits sampling + max_new_tokens (`int`): + Maximum number of generated tokens + best_of (`int`): + Generate best_of sequences and return the one if the highest token logprobs + repetition_penalty (`float`): + The parameter for repetition penalty. 1.0 means no penalty. See [this + paper](https://arxiv.org/pdf/1909.05858.pdf) for more details. + return_full_text (`bool`): + Whether to prepend the prompt to the generated text + seed (`int`): + Random sampling seed + stop_sequences (`List[str]`): + Stop generating tokens if a member of `stop_sequences` is generated + temperature (`float`): + The value used to module the logits distribution. + top_k (`int`): + The number of highest probability vocabulary tokens to keep for top-k-filtering. + top_p (`float`): + If set to < 1, only the smallest set of most probable tokens with probabilities that add up to `top_p` or + higher are kept for generation. + truncate (`int`): + Truncate inputs tokens to the given size + typical_p (`float`): + Typical Decoding mass + See [Typical Decoding for Natural Language Generation](https://arxiv.org/abs/2202.00666) for more information + watermark (`bool`): + Watermarking with [A Watermark for Large Language Models](https://arxiv.org/abs/2301.10226) + decoder_input_details (`bool`): + Return the decoder input token logprobs and ids. You must set `details=True` as well for it to be taken + into account. Defaults to `False`. + + Returns: + `Union[str, TextGenerationResponse, Iterable[str], Iterable[TextGenerationStreamResponse]]`: + Generated text returned from the server: + - if `stream=False` and `details=False`, the generated text is returned as a `str` (default) + - if `stream=True` and `details=False`, the generated text is returned token by token as a `Iterable[str]` + - if `stream=False` and `details=True`, the generated text is returned with more details as a [`~huggingface_hub.inference._text_generation.TextGenerationResponse`] + - if `details=True` and `stream=True`, the generated text is returned token by token as a iterable of [`~huggingface_hub.inference._text_generation.TextGenerationStreamResponse`] + + Raises: + `ValidationError`: + If input values are not valid. No HTTP call is made to the server. + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `HTTPError`: + If the request fails with an HTTP error status code other than HTTP 503. + + Example: + ```py + >>> from huggingface_hub import InferenceClient + >>> client = InferenceClient() + + # Case 1: generate text + >>> client.text_generation("The huggingface_hub library is ", max_new_tokens=12) + '100% open source and built to be easy to use.' + + # Case 2: iterate over the generated tokens. Useful for large generation. + >>> for token in client.text_generation("The huggingface_hub library is ", max_new_tokens=12, stream=True): + ... print(token) + 100 + % + open + source + and + built + to + be + easy + to + use + . + + # Case 3: get more details about the generation process. + >>> client.text_generation("The huggingface_hub library is ", max_new_tokens=12, details=True) + TextGenerationResponse( + generated_text='100% open source and built to be easy to use.', + details=Details( + finish_reason=, + generated_tokens=12, + seed=None, + prefill=[ + InputToken(id=487, text='The', logprob=None), + InputToken(id=53789, text=' hugging', logprob=-13.171875), + (...) + InputToken(id=204, text=' ', logprob=-7.0390625) + ], + tokens=[ + Token(id=1425, text='100', logprob=-1.0175781, special=False), + Token(id=16, text='%', logprob=-0.0463562, special=False), + (...) + Token(id=25, text='.', logprob=-0.5703125, special=False) + ], + best_of_sequences=None + ) + ) + + # Case 4: iterate over the generated tokens with more details. + # Last object is more complete, containing the full generated text and the finish reason. + >>> for details in client.text_generation("The huggingface_hub library is ", max_new_tokens=12, details=True, stream=True): + ... print(details) + ... + TextGenerationStreamResponse(token=Token(id=1425, text='100', logprob=-1.0175781, special=False), generated_text=None, details=None) + TextGenerationStreamResponse(token=Token(id=16, text='%', logprob=-0.0463562, special=False), generated_text=None, details=None) + TextGenerationStreamResponse(token=Token(id=1314, text=' open', logprob=-1.3359375, special=False), generated_text=None, details=None) + TextGenerationStreamResponse(token=Token(id=3178, text=' source', logprob=-0.28100586, special=False), generated_text=None, details=None) + TextGenerationStreamResponse(token=Token(id=273, text=' and', logprob=-0.5961914, special=False), generated_text=None, details=None) + TextGenerationStreamResponse(token=Token(id=3426, text=' built', logprob=-1.9423828, special=False), generated_text=None, details=None) + TextGenerationStreamResponse(token=Token(id=271, text=' to', logprob=-1.4121094, special=False), generated_text=None, details=None) + TextGenerationStreamResponse(token=Token(id=314, text=' be', logprob=-1.5224609, special=False), generated_text=None, details=None) + TextGenerationStreamResponse(token=Token(id=1833, text=' easy', logprob=-2.1132812, special=False), generated_text=None, details=None) + TextGenerationStreamResponse(token=Token(id=271, text=' to', logprob=-0.08520508, special=False), generated_text=None, details=None) + TextGenerationStreamResponse(token=Token(id=745, text=' use', logprob=-0.39453125, special=False), generated_text=None, details=None) + TextGenerationStreamResponse(token=Token( + id=25, + text='.', + logprob=-0.5703125, + special=False), + generated_text='100% open source and built to be easy to use.', + details=StreamDetails(finish_reason=, generated_tokens=12, seed=None) + ) + ``` + """ + # NOTE: Text-generation integration is taken from the text-generation-inference project. It has more features + # like input/output validation (if Pydantic is installed). See `_text_generation.py` header for more details. + + if decoder_input_details and not details: + warnings.warn( + "`decoder_input_details=True` has been passed to the server but `details=False` is set meaning that" + " the output from the server will be truncated." + ) + decoder_input_details = False + + # Validate parameters + parameters = TextGenerationParameters( + best_of=best_of, + details=details, + do_sample=do_sample, + max_new_tokens=max_new_tokens, + repetition_penalty=repetition_penalty, + return_full_text=return_full_text, + seed=seed, + stop=stop_sequences if stop_sequences is not None else [], + temperature=temperature, + top_k=top_k, + top_p=top_p, + truncate=truncate, + typical_p=typical_p, + watermark=watermark, + decoder_input_details=decoder_input_details, + ) + request = TextGenerationRequest(inputs=prompt, stream=stream, parameters=parameters) + payload = asdict(request) + + # Remove some parameters if not a TGI server + if not _is_tgi_server(model): + ignored_parameters = [] + for key in "watermark", "stop", "details", "decoder_input_details": + if payload["parameters"][key] is not None: + ignored_parameters.append(key) + del payload["parameters"][key] + if len(ignored_parameters) > 0: + warnings.warn( + "API endpoint/model for text-generation is not served via TGI. Ignoring parameters" + f" {ignored_parameters}.", + UserWarning, + ) + if details: + warnings.warn( + "API endpoint/model for text-generation is not served via TGI. Parameter `details=True` will" + " be ignored meaning only the generated text will be returned.", + UserWarning, + ) + details = False + if stream: + raise ValueError( + "API endpoint/model for text-generation is not served via TGI. Cannot return output as a stream." + " Please pass `stream=False` as input." + ) + + # Handle errors separately for more precise error messages + try: + bytes_output = self.post(json=payload, model=model, task="text-generation", stream=stream) # type: ignore + except HTTPError as e: + if isinstance(e, BadRequestError) and "The following `model_kwargs` are not used by the model" in str(e): + _set_as_non_tgi(model) + return self.text_generation( # type: ignore + prompt=prompt, + details=details, + stream=stream, + model=model, + do_sample=do_sample, + max_new_tokens=max_new_tokens, + best_of=best_of, + repetition_penalty=repetition_penalty, + return_full_text=return_full_text, + seed=seed, + stop_sequences=stop_sequences, + temperature=temperature, + top_k=top_k, + top_p=top_p, + truncate=truncate, + typical_p=typical_p, + watermark=watermark, + decoder_input_details=decoder_input_details, + ) + raise_text_generation_error(e) + + # Parse output + if stream: + return _stream_text_generation_response(bytes_output, details) # type: ignore + + data = _bytes_to_dict(bytes_output)[0] + return TextGenerationResponse(**data) if details else data["generated_text"] + + def text_to_image( + self, + prompt: str, + *, + negative_prompt: Optional[str] = None, + height: Optional[float] = None, + width: Optional[float] = None, + num_inference_steps: Optional[float] = None, + guidance_scale: Optional[float] = None, + model: Optional[str] = None, + **kwargs, + ) -> "Image": + """ + Generate an image based on a given text using a specified model. + + + + You must have `PIL` installed if you want to work with images (`pip install Pillow`). + + + + Args: + prompt (`str`): + The prompt to generate an image from. + negative_prompt (`str`, *optional*): + An optional negative prompt for the image generation. + height (`float`, *optional*): + The height in pixels of the image to generate. + width (`float`, *optional*): + The width in pixels of the image to generate. + num_inference_steps (`int`, *optional*): + The number of denoising steps. More denoising steps usually lead to a higher quality image at the + expense of slower inference. + guidance_scale (`float`, *optional*): + Higher guidance scale encourages to generate images that are closely linked to the text `prompt`, + usually at the expense of lower image quality. + model (`str`, *optional*): + The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed + Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None. + + Returns: + `Image`: The generated image. + + Raises: + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `HTTPError`: + If the request fails with an HTTP error status code other than HTTP 503. + + Example: + ```py + >>> from huggingface_hub import InferenceClient + >>> client = InferenceClient() + + >>> image = client.text_to_image("An astronaut riding a horse on the moon.") + >>> image.save("astronaut.png") + + >>> image = client.text_to_image( + ... "An astronaut riding a horse on the moon.", + ... negative_prompt="low resolution, blurry", + ... model="stabilityai/stable-diffusion-2-1", + ... ) + >>> image.save("better_astronaut.png") + ``` + """ + payload = {"inputs": prompt} + parameters = { + "negative_prompt": negative_prompt, + "height": height, + "width": width, + "num_inference_steps": num_inference_steps, + "guidance_scale": guidance_scale, + **kwargs, + } + for key, value in parameters.items(): + if value is not None: + payload.setdefault("parameters", {})[key] = value # type: ignore + response = self.post(json=payload, model=model, task="text-to-image") + return _bytes_to_image(response) + + def text_to_speech(self, text: str, *, model: Optional[str] = None) -> bytes: + """ + Synthesize an audio of a voice pronouncing a given text. + + Args: + text (`str`): + The text to synthesize. + model (`str`, *optional*): + The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed + Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None. + + Returns: + `bytes`: The generated audio. + + Raises: + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `HTTPError`: + If the request fails with an HTTP error status code other than HTTP 503. + + Example: + ```py + >>> from pathlib import Path + >>> from huggingface_hub import InferenceClient + >>> client = InferenceClient() + + >>> audio = client.text_to_speech("Hello world") + >>> Path("hello_world.flac").write_bytes(audio) + ``` + """ + return self.post(json={"inputs": text}, model=model, task="text-to-speech") + + def token_classification(self, text: str, *, model: Optional[str] = None) -> List[TokenClassificationOutput]: + """ + Perform token classification on the given text. + Usually used for sentence parsing, either grammatical, or Named Entity Recognition (NER) to understand keywords contained within text. + + Args: + text (`str`): + A string to be classified. + model (`str`, *optional*): + The model to use for the token classification task. Can be a model ID hosted on the Hugging Face Hub or a URL to + a deployed Inference Endpoint. If not provided, the default recommended token classification model will be used. + Defaults to None. + + Returns: + `List[Dict]`: List of token classification outputs containing the entity group, confidence score, word, start and end index. + + Raises: + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `HTTPError`: + If the request fails with an HTTP error status code other than HTTP 503. + + Example: + ```py + >>> from huggingface_hub import InferenceClient + >>> client = InferenceClient() + >>> client.token_classification("My name is Sarah Jessica Parker but you can call me Jessica") + [{'entity_group': 'PER', + 'score': 0.9971321225166321, + 'word': 'Sarah Jessica Parker', + 'start': 11, + 'end': 31}, + {'entity_group': 'PER', + 'score': 0.9773476123809814, + 'word': 'Jessica', + 'start': 52, + 'end': 59}] + ``` + """ + payload: Dict[str, Any] = {"inputs": text} + response = self.post( + json=payload, + model=model, + task="token-classification", + ) + return _bytes_to_list(response) + + def translation( + self, text: str, *, model: Optional[str] = None, src_lang: Optional[str] = None, tgt_lang: Optional[str] = None + ) -> str: + """ + Convert text from one language to another. + + Check out https://huggingface.co/tasks/translation for more information on how to choose the best model for + your specific use case. Source and target languages usually depend on the model. + However, it is possible to specify source and target languages for certain models. If you are working with one of these models, + you can use `src_lang` and `tgt_lang` arguments to pass the relevant information. + You can find this information in the model card. + + Args: + text (`str`): + A string to be translated. + model (`str`, *optional*): + The model to use for the translation task. Can be a model ID hosted on the Hugging Face Hub or a URL to + a deployed Inference Endpoint. If not provided, the default recommended translation model will be used. + Defaults to None. + src_lang (`str`, *optional*): + Source language of the translation task, i.e. input language. Cannot be passed without `tgt_lang`. + tgt_lang (`str`, *optional*): + Target language of the translation task, i.e. output language. Cannot be passed without `src_lang`. + + Returns: + `str`: The generated translated text. + + Raises: + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `HTTPError`: + If the request fails with an HTTP error status code other than HTTP 503. + `ValueError`: + If only one of the `src_lang` and `tgt_lang` arguments are provided. + + Example: + ```py + >>> from huggingface_hub import InferenceClient + >>> client = InferenceClient() + >>> client.translation("My name is Wolfgang and I live in Berlin") + 'Mein Name ist Wolfgang und ich lebe in Berlin.' + >>> client.translation("My name is Wolfgang and I live in Berlin", model="Helsinki-NLP/opus-mt-en-fr") + "Je m'appelle Wolfgang et je vis à Berlin." + ``` + + Specifying languages: + ```py + >>> client.translation("My name is Sarah Jessica Parker but you can call me Jessica", model="facebook/mbart-large-50-many-to-many-mmt", src_lang="en_XX", tgt_lang="fr_XX") + "Mon nom est Sarah Jessica Parker mais vous pouvez m\'appeler Jessica" + ``` + """ + # Throw error if only one of `src_lang` and `tgt_lang` was given + if src_lang is not None and tgt_lang is None: + raise ValueError("You cannot specify `src_lang` without specifying `tgt_lang`.") + + if src_lang is None and tgt_lang is not None: + raise ValueError("You cannot specify `tgt_lang` without specifying `src_lang`.") + + # If both `src_lang` and `tgt_lang` are given, pass them to the request body + payload: Dict = {"inputs": text} + if src_lang and tgt_lang: + payload["parameters"] = {"src_lang": src_lang, "tgt_lang": tgt_lang} + response = self.post(json=payload, model=model, task="translation") + return _bytes_to_dict(response)[0]["translation_text"] + + def zero_shot_classification( + self, text: str, labels: List[str], *, multi_label: bool = False, model: Optional[str] = None + ) -> List[ClassificationOutput]: + """ + Provide as input a text and a set of candidate labels to classify the input text. + + Args: + text (`str`): + The input text to classify. + labels (`List[str]`): + List of string possible labels. There must be at least 2 labels. + multi_label (`bool`): + Boolean that is set to True if classes can overlap. + model (`str`, *optional*): + The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed + Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None. + + Returns: + `List[Dict]`: List of classification outputs containing the predicted labels and their confidence. + + Raises: + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `HTTPError`: + If the request fails with an HTTP error status code other than HTTP 503. + + Example: + ```py + >>> from huggingface_hub import InferenceClient + >>> client = InferenceClient() + >>> text = ( + ... "A new model offers an explanation for how the Galilean satellites formed around the solar system's" + ... "largest world. Konstantin Batygin did not set out to solve one of the solar system's most puzzling" + ... " mysteries when he went for a run up a hill in Nice, France." + ... ) + >>> labels = ["space & cosmos", "scientific discovery", "microbiology", "robots", "archeology"] + >>> client.zero_shot_classification(text, labels) + [ + {"label": "scientific discovery", "score": 0.7961668968200684}, + {"label": "space & cosmos", "score": 0.18570658564567566}, + {"label": "microbiology", "score": 0.00730885099619627}, + {"label": "archeology", "score": 0.006258360575884581}, + {"label": "robots", "score": 0.004559356719255447}, + ] + >>> client.zero_shot_classification(text, labels, multi_label=True) + [ + {"label": "scientific discovery", "score": 0.9829297661781311}, + {"label": "space & cosmos", "score": 0.755190908908844}, + {"label": "microbiology", "score": 0.0005462635890580714}, + {"label": "archeology", "score": 0.00047131875180639327}, + {"label": "robots", "score": 0.00030448526376858354}, + ] + ``` + """ + # Raise ValueError if input is less than 2 labels + if len(labels) < 2: + raise ValueError("You must specify at least 2 classes to compare.") + + response = self.post( + json={ + "inputs": text, + "parameters": { + "candidate_labels": ",".join(labels), + "multi_label": multi_label, + }, + }, + model=model, + task="zero-shot-classification", + ) + output = _bytes_to_dict(response) + return [{"label": label, "score": score} for label, score in zip(output["labels"], output["scores"])] + + def zero_shot_image_classification( + self, image: ContentT, labels: List[str], *, model: Optional[str] = None + ) -> List[ClassificationOutput]: + """ + Provide input image and text labels to predict text labels for the image. + + Args: + image (`Union[str, Path, bytes, BinaryIO]`): + The input image to caption. It can be raw bytes, an image file, or a URL to an online image. + labels (`List[str]`): + List of string possible labels. There must be at least 2 labels. + model (`str`, *optional*): + The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed + Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None. + + Returns: + `List[Dict]`: List of classification outputs containing the predicted labels and their confidence. + + Raises: + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `HTTPError`: + If the request fails with an HTTP error status code other than HTTP 503. + + Example: + ```py + >>> from huggingface_hub import InferenceClient + >>> client = InferenceClient() + + >>> client.zero_shot_image_classification( + ... "https://upload.wikimedia.org/wikipedia/commons/thumb/4/43/Cute_dog.jpg/320px-Cute_dog.jpg", + ... labels=["dog", "cat", "horse"], + ... ) + [{"label": "dog", "score": 0.956}, ...] + ``` + """ + # Raise ValueError if input is less than 2 labels + if len(labels) < 2: + raise ValueError("You must specify at least 2 classes to compare.") + + response = self.post( + json={"image": _b64_encode(image), "parameters": {"candidate_labels": ",".join(labels)}}, + model=model, + task="zero-shot-image-classification", + ) + return _bytes_to_list(response) + + def _resolve_url(self, model: Optional[str] = None, task: Optional[str] = None) -> str: + model = model or self.model + + # If model is already a URL, ignore `task` and return directly + if model is not None and (model.startswith("http://") or model.startswith("https://")): + return model + + # # If no model but task is set => fetch the recommended one for this task + if model is None: + if task is None: + raise ValueError( + "You must specify at least a model (repo_id or URL) or a task, either when instantiating" + " `InferenceClient` or when making a request." + ) + model = self.get_recommended_model(task) + logger.info( + f"Using recommended model {model} for task {task}. Note that it is" + f" encouraged to explicitly set `model='{model}'` as the recommended" + " models list might get updated without prior notice." + ) + + # Compute InferenceAPI url + return ( + # Feature-extraction and sentence-similarity are the only cases where we handle models with several tasks. + f"{INFERENCE_ENDPOINT}/pipeline/{task}/{model}" + if task in ("feature-extraction", "sentence-similarity") + # Otherwise, we use the default endpoint + else f"{INFERENCE_ENDPOINT}/models/{model}" + ) + + @staticmethod + def get_recommended_model(task: str) -> str: + """ + Get the model Hugging Face recommends for the input task. + + Args: + task (`str`): + The Hugging Face task to get which model Hugging Face recommends. + All available tasks can be found [here](https://huggingface.co/tasks). + + Returns: + `str`: Name of the model recommended for the input task. + + Raises: + `ValueError`: If Hugging Face has no recommendation for the input task. + """ + model = _fetch_recommended_models().get(task) + if model is None: + raise ValueError( + f"Task {task} has no recommended model. Please specify a model" + " explicitly. Visit https://huggingface.co/tasks for more info." + ) + return model + + def get_model_status(self, model: Optional[str] = None) -> ModelStatus: + """ + Get the status of a model hosted on the Inference API. + + + + This endpoint is mostly useful when you already know which model you want to use and want to check its + availability. If you want to discover already deployed models, you should rather use [`~InferenceClient.list_deployed_models`]. + + + + Args: + model (`str`, *optional*): + Identifier of the model for witch the status gonna be checked. If model is not provided, + the model associated with this instance of [`InferenceClient`] will be used. Only InferenceAPI service can be checked so the + identifier cannot be a URL. + + + Returns: + [`ModelStatus`]: An instance of ModelStatus dataclass, containing information, + about the state of the model: load, state, compute type and framework. + + Example: + ```py + >>> from huggingface_hub import InferenceClient + >>> client = InferenceClient() + >>> client.get_model_status("bigcode/starcoder") + ModelStatus(loaded=True, state='Loaded', compute_type='gpu', framework='text-generation-inference') + ``` + """ + model = model or self.model + if model is None: + raise ValueError("Model id not provided.") + if model.startswith("https://"): + raise NotImplementedError("Model status is only available for Inference API endpoints.") + url = f"{INFERENCE_ENDPOINT}/status/{model}" + + response = get_session().get(url, headers=self.headers) + hf_raise_for_status(response) + response_data = response.json() + + if "error" in response_data: + raise ValueError(response_data["error"]) + + return ModelStatus( + loaded=response_data["loaded"], + state=response_data["state"], + compute_type=response_data["compute_type"], + framework=response_data["framework"], + ) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/inference/_common.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/inference/_common.py new file mode 100644 index 0000000000000000000000000000000000000000..9e147a5c13bf1de0da8f1dd0f176334f4d2d2323 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/inference/_common.py @@ -0,0 +1,327 @@ +# coding=utf-8 +# Copyright 2023-present, the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Contains utilities used by both the sync and async inference clients.""" +import base64 +import io +import json +import logging +from contextlib import contextmanager +from dataclasses import dataclass +from pathlib import Path +from typing import ( + TYPE_CHECKING, + Any, + AsyncIterable, + BinaryIO, + ContextManager, + Dict, + Generator, + Iterable, + List, + Literal, + Optional, + Set, + Union, + overload, +) + +from requests import HTTPError + +from ..constants import ENDPOINT +from ..utils import ( + build_hf_headers, + get_session, + hf_raise_for_status, + is_aiohttp_available, + is_numpy_available, + is_pillow_available, +) +from ._text_generation import TextGenerationStreamResponse, _parse_text_generation_error + + +if TYPE_CHECKING: + from aiohttp import ClientResponse, ClientSession + from PIL import Image + +# TYPES +UrlT = str +PathT = Union[str, Path] +BinaryT = Union[bytes, BinaryIO] +ContentT = Union[BinaryT, PathT, UrlT] + +# Use to set a Accept: image/png header +TASKS_EXPECTING_IMAGES = {"text-to-image", "image-to-image"} + +logger = logging.getLogger(__name__) + + +# Add dataclass for ModelStatus. We use this dataclass in get_model_status function. +@dataclass +class ModelStatus: + """ + This Dataclass represents the the model status in the Hugging Face Inference API. + + Args: + loaded (`bool`): + If the model is currently loaded into Hugging Face's InferenceAPI. Models + are loaded on-demand, leading to the user's first request taking longer. + If a model is loaded, you can be assured that it is in a healthy state. + state (`str`): + The current state of the model. This can be 'Loaded', 'Loadable', 'TooBig'. + If a model's state is 'Loadable', it's not too big and has a supported + backend. Loadable models are automatically loaded when the user first + requests inference on the endpoint. This means it is transparent for the + user to load a model, except that the first call takes longer to complete. + compute_type (`str`): + The type of compute resource the model is using or will use, such as 'gpu' or 'cpu'. + framework (`str`): + The name of the framework that the model was built with, such as 'transformers' + or 'text-generation-inference'. + """ + + loaded: bool + state: str + compute_type: str + framework: str + + +class InferenceTimeoutError(HTTPError, TimeoutError): + """Error raised when a model is unavailable or the request times out.""" + + +## IMPORT UTILS + + +def _import_aiohttp(): + # Make sure `aiohttp` is installed on the machine. + if not is_aiohttp_available(): + raise ImportError("Please install aiohttp to use `AsyncInferenceClient` (`pip install aiohttp`).") + import aiohttp + + return aiohttp + + +def _import_numpy(): + """Make sure `numpy` is installed on the machine.""" + if not is_numpy_available(): + raise ImportError("Please install numpy to use deal with embeddings (`pip install numpy`).") + import numpy + + return numpy + + +def _import_pil_image(): + """Make sure `PIL` is installed on the machine.""" + if not is_pillow_available(): + raise ImportError( + "Please install Pillow to use deal with images (`pip install Pillow`). If you don't want the image to be" + " post-processed, use `client.post(...)` and get the raw response from the server." + ) + from PIL import Image + + return Image + + +## RECOMMENDED MODELS + +# Will be globally fetched only once (see '_fetch_recommended_models') +_RECOMMENDED_MODELS: Optional[Dict[str, Optional[str]]] = None + + +def _fetch_recommended_models() -> Dict[str, Optional[str]]: + global _RECOMMENDED_MODELS + if _RECOMMENDED_MODELS is None: + response = get_session().get(f"{ENDPOINT}/api/tasks", headers=build_hf_headers()) + hf_raise_for_status(response) + _RECOMMENDED_MODELS = { + task: _first_or_none(details["widgetModels"]) for task, details in response.json().items() + } + return _RECOMMENDED_MODELS + + +def _first_or_none(items: List[Any]) -> Optional[Any]: + try: + return items[0] or None + except IndexError: + return None + + +## ENCODING / DECODING UTILS + + +@overload +def _open_as_binary(content: ContentT) -> ContextManager[BinaryT]: + ... # means "if input is not None, output is not None" + + +@overload +def _open_as_binary(content: Literal[None]) -> ContextManager[Literal[None]]: + ... # means "if input is None, output is None" + + +@contextmanager # type: ignore +def _open_as_binary(content: Optional[ContentT]) -> Generator[Optional[BinaryT], None, None]: + """Open `content` as a binary file, either from a URL, a local path, or raw bytes. + + Do nothing if `content` is None, + + TODO: handle a PIL.Image as input + TODO: handle base64 as input + """ + # If content is a string => must be either a URL or a path + if isinstance(content, str): + if content.startswith("https://") or content.startswith("http://"): + logger.debug(f"Downloading content from {content}") + yield get_session().get(content).content # TODO: retrieve as stream and pipe to post request ? + return + content = Path(content) + if not content.exists(): + raise FileNotFoundError( + f"File not found at {content}. If `data` is a string, it must either be a URL or a path to a local" + " file. To pass raw content, please encode it as bytes first." + ) + + # If content is a Path => open it + if isinstance(content, Path): + logger.debug(f"Opening content from {content}") + with content.open("rb") as f: + yield f + else: + # Otherwise: already a file-like object or None + yield content + + +def _b64_encode(content: ContentT) -> str: + """Encode a raw file (image, audio) into base64. Can be byes, an opened file, a path or a URL.""" + with _open_as_binary(content) as data: + data_as_bytes = data if isinstance(data, bytes) else data.read() + return base64.b64encode(data_as_bytes).decode() + + +def _b64_to_image(encoded_image: str) -> "Image": + """Parse a base64-encoded string into a PIL Image.""" + Image = _import_pil_image() + return Image.open(io.BytesIO(base64.b64decode(encoded_image))) + + +def _bytes_to_list(content: bytes) -> List: + """Parse bytes from a Response object into a Python list. + + Expects the response body to be JSON-encoded data. + + NOTE: This is exactly the same implementation as `_bytes_to_dict` and will not complain if the returned data is a + dictionary. The only advantage of having both is to help the user (and mypy) understand what kind of data to expect. + """ + return json.loads(content.decode()) + + +def _bytes_to_dict(content: bytes) -> Dict: + """Parse bytes from a Response object into a Python dictionary. + + Expects the response body to be JSON-encoded data. + + NOTE: This is exactly the same implementation as `_bytes_to_list` and will not complain if the returned data is a + list. The only advantage of having both is to help the user (and mypy) understand what kind of data to expect. + """ + return json.loads(content.decode()) + + +def _bytes_to_image(content: bytes) -> "Image": + """Parse bytes from a Response object into a PIL Image. + + Expects the response body to be raw bytes. To deal with b64 encoded images, use `_b64_to_image` instead. + """ + Image = _import_pil_image() + return Image.open(io.BytesIO(content)) + + +## STREAMING UTILS + + +def _stream_text_generation_response( + bytes_output_as_lines: Iterable[bytes], details: bool +) -> Union[Iterable[str], Iterable[TextGenerationStreamResponse]]: + # Parse ServerSentEvents + for byte_payload in bytes_output_as_lines: + # Skip line + if byte_payload == b"\n": + continue + + payload = byte_payload.decode("utf-8") + + # Event data + if payload.startswith("data:"): + # Decode payload + json_payload = json.loads(payload.lstrip("data:").rstrip("/n")) + # Either an error as being returned + if json_payload.get("error") is not None: + raise _parse_text_generation_error(json_payload["error"], json_payload.get("error_type")) + # Or parse token payload + output = TextGenerationStreamResponse(**json_payload) + yield output.token.text if not details else output + + +async def _async_stream_text_generation_response( + bytes_output_as_lines: AsyncIterable[bytes], details: bool +) -> Union[AsyncIterable[str], AsyncIterable[TextGenerationStreamResponse]]: + # Parse ServerSentEvents + async for byte_payload in bytes_output_as_lines: + # Skip line + if byte_payload == b"\n": + continue + + payload = byte_payload.decode("utf-8") + + # Event data + if payload.startswith("data:"): + # Decode payload + json_payload = json.loads(payload.lstrip("data:").rstrip("/n")) + # Either an error as being returned + if json_payload.get("error") is not None: + raise _parse_text_generation_error(json_payload["error"], json_payload.get("error_type")) + # Or parse token payload + output = TextGenerationStreamResponse(**json_payload) + yield output.token.text if not details else output + + +async def _async_yield_from(client: "ClientSession", response: "ClientResponse") -> AsyncIterable[bytes]: + async for byte_payload in response.content: + yield byte_payload + await client.close() + + +# "TGI servers" are servers running with the `text-generation-inference` backend. +# This backend is the go-to solution to run large language models at scale. However, +# for some smaller models (e.g. "gpt2") the default `transformers` + `api-inference` +# solution is still in use. +# +# Both approaches have very similar APIs, but not exactly the same. What we do first in +# the `text_generation` method is to assume the model is served via TGI. If we realize +# it's not the case (i.e. we receive an HTTP 400 Bad Request), we fallback to the +# default API with a warning message. We remember for each model if it's a TGI server +# or not using `_NON_TGI_SERVERS` global variable. +# +# For more details, see https://github.com/huggingface/text-generation-inference and +# https://huggingface.co/docs/api-inference/detailed_parameters#text-generation-task. + +_NON_TGI_SERVERS: Set[Optional[str]] = set() + + +def _set_as_non_tgi(model: Optional[str]) -> None: + _NON_TGI_SERVERS.add(model) + + +def _is_tgi_server(model: Optional[str]) -> bool: + return model not in _NON_TGI_SERVERS diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/inference/_generated/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/inference/_generated/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/inference/_generated/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/inference/_generated/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..58f98f5143cac88235a6a1ce4e131c72fa36780b Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/inference/_generated/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/inference/_generated/__pycache__/_async_client.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/inference/_generated/__pycache__/_async_client.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b0f4b52b04683726bbe11e992048f529cca03b0e Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/inference/_generated/__pycache__/_async_client.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/inference/_generated/_async_client.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/inference/_generated/_async_client.py new file mode 100644 index 0000000000000000000000000000000000000000..67a6128b8161a075866619e7a4c225dfb31ae7c2 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/inference/_generated/_async_client.py @@ -0,0 +1,2020 @@ +# coding=utf-8 +# Copyright 2023-present, the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# WARNING +# This entire file has been adapted from the sync-client code in `src/huggingface_hub/inference/_client.py`. +# Any change in InferenceClient will be automatically reflected in AsyncInferenceClient. +# To re-generate the code, run `make style` or `python ./utils/generate_async_inference_client.py --update`. +# WARNING +import asyncio +import logging +import time +import warnings +from dataclasses import asdict +from typing import ( + TYPE_CHECKING, + Any, + AsyncIterable, + Dict, + List, + Literal, + Optional, + Union, + overload, +) + +from requests.structures import CaseInsensitiveDict + +from huggingface_hub.constants import ALL_INFERENCE_API_FRAMEWORKS, INFERENCE_ENDPOINT, MAIN_INFERENCE_API_FRAMEWORKS +from huggingface_hub.inference._common import ( + TASKS_EXPECTING_IMAGES, + ContentT, + InferenceTimeoutError, + ModelStatus, + _async_stream_text_generation_response, + _b64_encode, + _b64_to_image, + _bytes_to_dict, + _bytes_to_image, + _bytes_to_list, + _fetch_recommended_models, + _import_numpy, + _is_tgi_server, + _open_as_binary, + _set_as_non_tgi, +) +from huggingface_hub.inference._text_generation import ( + TextGenerationParameters, + TextGenerationRequest, + TextGenerationResponse, + TextGenerationStreamResponse, + raise_text_generation_error, +) +from huggingface_hub.inference._types import ( + ClassificationOutput, + ConversationalOutput, + FillMaskOutput, + ImageSegmentationOutput, + ObjectDetectionOutput, + QuestionAnsweringOutput, + TableQuestionAnsweringOutput, + TokenClassificationOutput, +) +from huggingface_hub.utils import ( + build_hf_headers, +) + +from .._common import _async_yield_from, _import_aiohttp + + +if TYPE_CHECKING: + import numpy as np + from PIL import Image + +logger = logging.getLogger(__name__) + + +class AsyncInferenceClient: + """ + Initialize a new Inference Client. + + [`InferenceClient`] aims to provide a unified experience to perform inference. The client can be used + seamlessly with either the (free) Inference API or self-hosted Inference Endpoints. + + Args: + model (`str`, `optional`): + The model to run inference with. Can be a model id hosted on the Hugging Face Hub, e.g. `bigcode/starcoder` + or a URL to a deployed Inference Endpoint. Defaults to None, in which case a recommended model is + automatically selected for the task. + token (`str`, *optional*): + Hugging Face token. Will default to the locally saved token. Pass `token=False` if you don't want to send + your token to the server. + timeout (`float`, `optional`): + The maximum number of seconds to wait for a response from the server. Loading a new model in Inference + API can take up to several minutes. Defaults to None, meaning it will loop until the server is available. + headers (`Dict[str, str]`, `optional`): + Additional headers to send to the server. By default only the authorization and user-agent headers are sent. + Values in this dictionary will override the default values. + cookies (`Dict[str, str]`, `optional`): + Additional cookies to send to the server. + """ + + def __init__( + self, + model: Optional[str] = None, + token: Union[str, bool, None] = None, + timeout: Optional[float] = None, + headers: Optional[Dict[str, str]] = None, + cookies: Optional[Dict[str, str]] = None, + ) -> None: + self.model: Optional[str] = model + self.headers = CaseInsensitiveDict(build_hf_headers(token=token)) # contains 'authorization' + 'user-agent' + if headers is not None: + self.headers.update(headers) + self.cookies = cookies + self.timeout = timeout + + def __repr__(self): + return f"" + + @overload + async def post( # type: ignore[misc] + self, + *, + json: Optional[Union[str, Dict, List]] = None, + data: Optional[ContentT] = None, + model: Optional[str] = None, + task: Optional[str] = None, + stream: Literal[False] = ..., + ) -> bytes: + pass + + @overload + async def post( + self, + *, + json: Optional[Union[str, Dict, List]] = None, + data: Optional[ContentT] = None, + model: Optional[str] = None, + task: Optional[str] = None, + stream: Literal[True] = ..., + ) -> AsyncIterable[bytes]: + pass + + async def post( + self, + *, + json: Optional[Union[str, Dict, List]] = None, + data: Optional[ContentT] = None, + model: Optional[str] = None, + task: Optional[str] = None, + stream: bool = False, + ) -> Union[bytes, AsyncIterable[bytes]]: + """ + Make a POST request to the inference server. + + Args: + json (`Union[str, Dict, List]`, *optional*): + The JSON data to send in the request body, specific to each task. Defaults to None. + data (`Union[str, Path, bytes, BinaryIO]`, *optional*): + The content to send in the request body, specific to each task. + It can be raw bytes, a pointer to an opened file, a local file path, + or a URL to an online resource (image, audio file,...). If both `json` and `data` are passed, + `data` will take precedence. At least `json` or `data` must be provided. Defaults to None. + model (`str`, *optional*): + The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed + Inference Endpoint. Will override the model defined at the instance level. Defaults to None. + task (`str`, *optional*): + The task to perform on the inference. All available tasks can be found + [here](https://huggingface.co/tasks). Used only to default to a recommended model if `model` is not + provided. At least `model` or `task` must be provided. Defaults to None. + stream (`bool`, *optional*): + Whether to iterate over streaming APIs. + + Returns: + bytes: The raw bytes returned by the server. + + Raises: + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `aiohttp.ClientResponseError`: + If the request fails with an HTTP error status code other than HTTP 503. + """ + + aiohttp = _import_aiohttp() + + url = self._resolve_url(model, task) + + if data is not None and json is not None: + warnings.warn("Ignoring `json` as `data` is passed as binary.") + + # Set Accept header if relevant + headers = self.headers.copy() + if task in TASKS_EXPECTING_IMAGES and "Accept" not in headers: + headers["Accept"] = "image/png" + + t0 = time.time() + timeout = self.timeout + while True: + with _open_as_binary(data) as data_as_binary: + # Do not use context manager as we don't want to close the connection immediately when returning + # a stream + client = aiohttp.ClientSession( + headers=headers, cookies=self.cookies, timeout=aiohttp.ClientTimeout(self.timeout) + ) + + try: + response = await client.post(url, json=json, data=data_as_binary) + response_error_payload = None + if response.status != 200: + try: + response_error_payload = await response.json() # get payload before connection closed + except Exception: + pass + response.raise_for_status() + if stream: + return _async_yield_from(client, response) + else: + content = await response.read() + await client.close() + return content + except asyncio.TimeoutError as error: + await client.close() + # Convert any `TimeoutError` to a `InferenceTimeoutError` + raise InferenceTimeoutError(f"Inference call timed out: {url}") from error # type: ignore + except aiohttp.ClientResponseError as error: + error.response_error_payload = response_error_payload + await client.close() + if response.status == 422 and task is not None: + error.message += f". Make sure '{task}' task is supported by the model." + if response.status == 503: + # If Model is unavailable, either raise a TimeoutError... + if timeout is not None and time.time() - t0 > timeout: + raise InferenceTimeoutError( + f"Model not loaded on the server: {url}. Please retry with a higher timeout" + f" (current: {self.timeout}).", + request=error.request, + response=error.response, + ) from error + # ...or wait 1s and retry + logger.info(f"Waiting for model to be loaded on the server: {error}") + time.sleep(1) + if timeout is not None: + timeout = max(self.timeout - (time.time() - t0), 1) # type: ignore + continue + raise error + + async def audio_classification( + self, + audio: ContentT, + *, + model: Optional[str] = None, + ) -> List[ClassificationOutput]: + """ + Perform audio classification on the provided audio content. + + Args: + audio (Union[str, Path, bytes, BinaryIO]): + The audio content to classify. It can be raw audio bytes, a local audio file, or a URL pointing to an + audio file. + model (`str`, *optional*): + The model to use for audio classification. Can be a model ID hosted on the Hugging Face Hub + or a URL to a deployed Inference Endpoint. If not provided, the default recommended model for + audio classification will be used. + + Returns: + `List[Dict]`: The classification output containing the predicted label and its confidence. + + Raises: + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `aiohttp.ClientResponseError`: + If the request fails with an HTTP error status code other than HTTP 503. + + Example: + ```py + # Must be run in an async context + >>> from huggingface_hub import AsyncInferenceClient + >>> client = AsyncInferenceClient() + >>> await client.audio_classification("audio.flac") + [{'score': 0.4976358711719513, 'label': 'hap'}, {'score': 0.3677836060523987, 'label': 'neu'},...] + ``` + """ + response = await self.post(data=audio, model=model, task="audio-classification") + return _bytes_to_list(response) + + async def automatic_speech_recognition( + self, + audio: ContentT, + *, + model: Optional[str] = None, + ) -> str: + """ + Perform automatic speech recognition (ASR or audio-to-text) on the given audio content. + + Args: + audio (Union[str, Path, bytes, BinaryIO]): + The content to transcribe. It can be raw audio bytes, local audio file, or a URL to an audio file. + model (`str`, *optional*): + The model to use for ASR. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed + Inference Endpoint. If not provided, the default recommended model for ASR will be used. + + Returns: + str: The transcribed text. + + Raises: + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `aiohttp.ClientResponseError`: + If the request fails with an HTTP error status code other than HTTP 503. + + Example: + ```py + # Must be run in an async context + >>> from huggingface_hub import AsyncInferenceClient + >>> client = AsyncInferenceClient() + >>> await client.automatic_speech_recognition("hello_world.flac") + "hello world" + ``` + """ + response = await self.post(data=audio, model=model, task="automatic-speech-recognition") + return _bytes_to_dict(response)["text"] + + async def conversational( + self, + text: str, + generated_responses: Optional[List[str]] = None, + past_user_inputs: Optional[List[str]] = None, + *, + parameters: Optional[Dict[str, Any]] = None, + model: Optional[str] = None, + ) -> ConversationalOutput: + """ + Generate conversational responses based on the given input text (i.e. chat with the API). + + Args: + text (`str`): + The last input from the user in the conversation. + generated_responses (`List[str]`, *optional*): + A list of strings corresponding to the earlier replies from the model. Defaults to None. + past_user_inputs (`List[str]`, *optional*): + A list of strings corresponding to the earlier replies from the user. Should be the same length as + `generated_responses`. Defaults to None. + parameters (`Dict[str, Any]`, *optional*): + Additional parameters for the conversational task. Defaults to None. For more details about the available + parameters, please refer to [this page](https://huggingface.co/docs/api-inference/detailed_parameters#conversational-task) + model (`str`, *optional*): + The model to use for the conversational task. Can be a model ID hosted on the Hugging Face Hub or a URL to + a deployed Inference Endpoint. If not provided, the default recommended conversational model will be used. + Defaults to None. + + Returns: + `Dict`: The generated conversational output. + + Raises: + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `aiohttp.ClientResponseError`: + If the request fails with an HTTP error status code other than HTTP 503. + + Example: + ```py + # Must be run in an async context + >>> from huggingface_hub import AsyncInferenceClient + >>> client = AsyncInferenceClient() + >>> output = await client.conversational("Hi, who are you?") + >>> output + {'generated_text': 'I am the one who knocks.', 'conversation': {'generated_responses': ['I am the one who knocks.'], 'past_user_inputs': ['Hi, who are you?']}, 'warnings': ['Setting `pad_token_id` to `eos_token_id`:50256 async for open-end generation.']} + >>> await client.conversational( + ... "Wow, that's scary!", + ... generated_responses=output["conversation"]["generated_responses"], + ... past_user_inputs=output["conversation"]["past_user_inputs"], + ... ) + ``` + """ + payload: Dict[str, Any] = {"inputs": {"text": text}} + if generated_responses is not None: + payload["inputs"]["generated_responses"] = generated_responses + if past_user_inputs is not None: + payload["inputs"]["past_user_inputs"] = past_user_inputs + if parameters is not None: + payload["parameters"] = parameters + response = await self.post(json=payload, model=model, task="conversational") + return _bytes_to_dict(response) # type: ignore + + async def visual_question_answering( + self, + image: ContentT, + question: str, + *, + model: Optional[str] = None, + ) -> List[str]: + """ + Answering open-ended questions based on an image. + + Args: + image (`Union[str, Path, bytes, BinaryIO]`): + The input image for the context. It can be raw bytes, an image file, or a URL to an online image. + question (`str`): + Question to be answered. + model (`str`, *optional*): + The model to use for the visual question answering task. Can be a model ID hosted on the Hugging Face Hub or a URL to + a deployed Inference Endpoint. If not provided, the default recommended visual question answering model will be used. + Defaults to None. + + Returns: + `List[Dict]`: a list of dictionaries containing the predicted label and associated probability. + + Raises: + `InferenceTimeoutError`: + If the model is unavailable or the request times out. + `aiohttp.ClientResponseError`: + If the request fails with an HTTP error status code other than HTTP 503. + + Example: + ```py + # Must be run in an async context + >>> from huggingface_hub import AsyncInferenceClient + >>> client = AsyncInferenceClient() + >>> await client.visual_question_answering( + ... image="https://huggingface.co/datasets/mishig/sample_images/resolve/main/tiger.jpg", + ... question="What is the animal doing?" + ... ) + [{'score': 0.778609573841095, 'answer': 'laying down'},{'score': 0.6957435607910156, 'answer': 'sitting'}, ...] + ``` + """ + payload: Dict[str, Any] = {"question": question, "image": _b64_encode(image)} + response = await self.post(json=payload, model=model, task="visual-question-answering") + return _bytes_to_list(response) + + async def document_question_answering( + self, + image: ContentT, + question: str, + *, + model: Optional[str] = None, + ) -> List[QuestionAnsweringOutput]: + """ + Answer questions on document images. + + Args: + image (`Union[str, Path, bytes, BinaryIO]`): + The input image for the context. It can be raw bytes, an image file, or a URL to an online image. + question (`str`): + Question to be answered. + model (`str`, *optional*): + The model to use for the document question answering task. Can be a model ID hosted on the Hugging Face Hub or a URL to + a deployed Inference Endpoint. If not provided, the default recommended document question answering model will be used. + Defaults to None. + + Returns: + `List[Dict]`: a list of dictionaries containing the predicted label, associated probability, word ids, and page number. + + Raises: + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `aiohttp.ClientResponseError`: + If the request fails with an HTTP error status code other than HTTP 503. + + Example: + ```py + # Must be run in an async context + >>> from huggingface_hub import AsyncInferenceClient + >>> client = AsyncInferenceClient() + >>> await client.document_question_answering(image="https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png", question="What is the invoice number?") + [{'score': 0.42515629529953003, 'answer': 'us-001', 'start': 16, 'end': 16}] + ``` + """ + payload: Dict[str, Any] = {"question": question, "image": _b64_encode(image)} + response = await self.post(json=payload, model=model, task="document-question-answering") + return _bytes_to_list(response) + + async def feature_extraction(self, text: str, *, model: Optional[str] = None) -> "np.ndarray": + """ + Generate embeddings for a given text. + + Args: + text (`str`): + The text to embed. + model (`str`, *optional*): + The model to use for the conversational task. Can be a model ID hosted on the Hugging Face Hub or a URL to + a deployed Inference Endpoint. If not provided, the default recommended conversational model will be used. + Defaults to None. + + Returns: + `np.ndarray`: The embedding representing the input text as a float32 numpy array. + + Raises: + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `aiohttp.ClientResponseError`: + If the request fails with an HTTP error status code other than HTTP 503. + + Example: + ```py + # Must be run in an async context + >>> from huggingface_hub import AsyncInferenceClient + >>> client = AsyncInferenceClient() + >>> await client.feature_extraction("Hi, who are you?") + array([[ 2.424802 , 2.93384 , 1.1750331 , ..., 1.240499, -0.13776633, -0.7889173 ], + [-0.42943227, -0.6364878 , -1.693462 , ..., 0.41978157, -2.4336355 , 0.6162071 ], + ..., + [ 0.28552425, -0.928395 , -1.2077185 , ..., 0.76810825, -2.1069427 , 0.6236161 ]], dtype=float32) + ``` + """ + response = await self.post(json={"inputs": text}, model=model, task="feature-extraction") + np = _import_numpy() + return np.array(_bytes_to_dict(response), dtype="float32") + + async def fill_mask(self, text: str, *, model: Optional[str] = None) -> List[FillMaskOutput]: + """ + Fill in a hole with a missing word (token to be precise). + + Args: + text (`str`): + a string to be filled from, must contain the [MASK] token (check model card for exact name of the mask). + model (`str`, *optional*): + The model to use for the fill mask task. Can be a model ID hosted on the Hugging Face Hub or a URL to + a deployed Inference Endpoint. If not provided, the default recommended fill mask model will be used. + Defaults to None. + + Returns: + `List[Dict]`: a list of fill mask output dictionaries containing the predicted label, associated + probability, token reference, and completed text. + + Raises: + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `aiohttp.ClientResponseError`: + If the request fails with an HTTP error status code other than HTTP 503. + + Example: + ```py + # Must be run in an async context + >>> from huggingface_hub import AsyncInferenceClient + >>> client = AsyncInferenceClient() + >>> await client.fill_mask("The goal of life is .") + [{'score': 0.06897063553333282, + 'token': 11098, + 'token_str': ' happiness', + 'sequence': 'The goal of life is happiness.'}, + {'score': 0.06554922461509705, + 'token': 45075, + 'token_str': ' immortality', + 'sequence': 'The goal of life is immortality.'}] + ``` + """ + response = await self.post(json={"inputs": text}, model=model, task="fill-mask") + return _bytes_to_list(response) + + async def image_classification( + self, + image: ContentT, + *, + model: Optional[str] = None, + ) -> List[ClassificationOutput]: + """ + Perform image classification on the given image using the specified model. + + Args: + image (`Union[str, Path, bytes, BinaryIO]`): + The image to classify. It can be raw bytes, an image file, or a URL to an online image. + model (`str`, *optional*): + The model to use for image classification. Can be a model ID hosted on the Hugging Face Hub or a URL to a + deployed Inference Endpoint. If not provided, the default recommended model for image classification will be used. + + Returns: + `List[Dict]`: a list of dictionaries containing the predicted label and associated probability. + + Raises: + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `aiohttp.ClientResponseError`: + If the request fails with an HTTP error status code other than HTTP 503. + + Example: + ```py + # Must be run in an async context + >>> from huggingface_hub import AsyncInferenceClient + >>> client = AsyncInferenceClient() + >>> await client.image_classification("https://upload.wikimedia.org/wikipedia/commons/thumb/4/43/Cute_dog.jpg/320px-Cute_dog.jpg") + [{'score': 0.9779096841812134, 'label': 'Blenheim spaniel'}, ...] + ``` + """ + response = await self.post(data=image, model=model, task="image-classification") + return _bytes_to_list(response) + + async def image_segmentation( + self, + image: ContentT, + *, + model: Optional[str] = None, + ) -> List[ImageSegmentationOutput]: + """ + Perform image segmentation on the given image using the specified model. + + + + You must have `PIL` installed if you want to work with images (`pip install Pillow`). + + + + Args: + image (`Union[str, Path, bytes, BinaryIO]`): + The image to segment. It can be raw bytes, an image file, or a URL to an online image. + model (`str`, *optional*): + The model to use for image segmentation. Can be a model ID hosted on the Hugging Face Hub or a URL to a + deployed Inference Endpoint. If not provided, the default recommended model for image segmentation will be used. + + Returns: + `List[Dict]`: A list of dictionaries containing the segmented masks and associated attributes. + + Raises: + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `aiohttp.ClientResponseError`: + If the request fails with an HTTP error status code other than HTTP 503. + + Example: + ```py + # Must be run in an async context + >>> from huggingface_hub import AsyncInferenceClient + >>> client = AsyncInferenceClient() + >>> await client.image_segmentation("cat.jpg"): + [{'score': 0.989008, 'label': 'LABEL_184', 'mask': }, ...] + ``` + """ + + # Segment + response = await self.post(data=image, model=model, task="image-segmentation") + output = _bytes_to_dict(response) + + # Parse masks as PIL Image + if not isinstance(output, list): + raise ValueError(f"Server output must be a list. Got {type(output)}: {str(output)[:200]}...") + for item in output: + item["mask"] = _b64_to_image(item["mask"]) + return output + + async def image_to_image( + self, + image: ContentT, + prompt: Optional[str] = None, + *, + negative_prompt: Optional[str] = None, + height: Optional[int] = None, + width: Optional[int] = None, + num_inference_steps: Optional[int] = None, + guidance_scale: Optional[float] = None, + model: Optional[str] = None, + **kwargs, + ) -> "Image": + """ + Perform image-to-image translation using a specified model. + + + + You must have `PIL` installed if you want to work with images (`pip install Pillow`). + + + + Args: + image (`Union[str, Path, bytes, BinaryIO]`): + The input image for translation. It can be raw bytes, an image file, or a URL to an online image. + prompt (`str`, *optional*): + The text prompt to guide the image generation. + negative_prompt (`str`, *optional*): + A negative prompt to guide the translation process. + height (`int`, *optional*): + The height in pixels of the generated image. + width (`int`, *optional*): + The width in pixels of the generated image. + num_inference_steps (`int`, *optional*): + The number of denoising steps. More denoising steps usually lead to a higher quality image at the + expense of slower inference. + guidance_scale (`float`, *optional*): + Higher guidance scale encourages to generate images that are closely linked to the text `prompt`, + usually at the expense of lower image quality. + model (`str`, *optional*): + The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed + Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None. + + Returns: + `Image`: The translated image. + + Raises: + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `aiohttp.ClientResponseError`: + If the request fails with an HTTP error status code other than HTTP 503. + + Example: + ```py + # Must be run in an async context + >>> from huggingface_hub import AsyncInferenceClient + >>> client = AsyncInferenceClient() + >>> image = await client.image_to_image("cat.jpg", prompt="turn the cat into a tiger") + >>> image.save("tiger.jpg") + ``` + """ + parameters = { + "prompt": prompt, + "negative_prompt": negative_prompt, + "height": height, + "width": width, + "num_inference_steps": num_inference_steps, + "guidance_scale": guidance_scale, + **kwargs, + } + if all(parameter is None for parameter in parameters.values()): + # Either only an image to send => send as raw bytes + data = image + payload: Optional[Dict[str, Any]] = None + else: + # Or an image + some parameters => use base64 encoding + data = None + payload = {"inputs": _b64_encode(image)} + for key, value in parameters.items(): + if value is not None: + payload.setdefault("parameters", {})[key] = value + + response = await self.post(json=payload, data=data, model=model, task="image-to-image") + return _bytes_to_image(response) + + async def image_to_text(self, image: ContentT, *, model: Optional[str] = None) -> str: + """ + Takes an input image and return text. + + Models can have very different outputs depending on your use case (image captioning, optical character recognition + (OCR), Pix2Struct, etc). Please have a look to the model card to learn more about a model's specificities. + + Args: + image (`Union[str, Path, bytes, BinaryIO]`): + The input image to caption. It can be raw bytes, an image file, or a URL to an online image.. + model (`str`, *optional*): + The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed + Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None. + + Returns: + `str`: The generated text. + + Raises: + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `aiohttp.ClientResponseError`: + If the request fails with an HTTP error status code other than HTTP 503. + + Example: + ```py + # Must be run in an async context + >>> from huggingface_hub import AsyncInferenceClient + >>> client = AsyncInferenceClient() + >>> await client.image_to_text("cat.jpg") + 'a cat standing in a grassy field ' + >>> await client.image_to_text("https://upload.wikimedia.org/wikipedia/commons/thumb/4/43/Cute_dog.jpg/320px-Cute_dog.jpg") + 'a dog laying on the grass next to a flower pot ' + ``` + """ + response = await self.post(data=image, model=model, task="image-to-text") + return _bytes_to_dict(response)[0]["generated_text"] + + async def list_deployed_models( + self, frameworks: Union[None, str, Literal["all"], List[str]] = None + ) -> Dict[str, List[str]]: + """ + List models currently deployed on the Inference API service. + + This helper checks deployed models framework by framework. By default, it will check the 4 main frameworks that + are supported and account for 95% of the hosted models. However, if you want a complete list of models you can + specify `frameworks="all"` as input. Alternatively, if you know before-hand which framework you are interested + in, you can also restrict to search to this one (e.g. `frameworks="text-generation-inference"`). The more + frameworks are checked, the more time it will take. + + + + This endpoint is mostly useful for discoverability. If you already know which model you want to use and want to + check its availability, you can directly use [`~InferenceClient.get_model_status`]. + + + + Args: + frameworks (`Literal["all"]` or `List[str]` or `str`, *optional*): + The frameworks to filter on. By default only a subset of the available frameworks are tested. If set to + "all", all available frameworks will be tested. It is also possible to provide a single framework or a + custom set of frameworks to check. + + Returns: + `Dict[str, List[str]]`: A dictionary mapping task names to a sorted list of model IDs. + + Example: + ```py + # Must be run in an async contextthon + >>> from huggingface_hub import AsyncInferenceClient + >>> client = AsyncInferenceClient() + + # Discover zero-shot-classification models currently deployed + >>> models = await client.list_deployed_models() + >>> models["zero-shot-classification"] + ['Narsil/deberta-large-mnli-zero-cls', 'facebook/bart-large-mnli', ...] + + # List from only 1 framework + >>> await client.list_deployed_models("text-generation-inference") + {'text-generation': ['bigcode/starcoder', 'meta-llama/Llama-2-70b-chat-hf', ...], ...} + ``` + """ + # Resolve which frameworks to check + if frameworks is None: + frameworks = MAIN_INFERENCE_API_FRAMEWORKS + elif frameworks == "all": + frameworks = ALL_INFERENCE_API_FRAMEWORKS + elif isinstance(frameworks, str): + frameworks = [frameworks] + frameworks = list(set(frameworks)) + + # Fetch them iteratively + models_by_task: Dict[str, List[str]] = {} + + def _unpack_response(framework: str, items: List[Dict]) -> None: + for model in items: + if framework == "sentence-transformers": + # Model running with the `sentence-transformers` framework can work with both tasks even if not + # branded as such in the API response + models_by_task.setdefault("feature-extraction", []).append(model["model_id"]) + models_by_task.setdefault("sentence-similarity", []).append(model["model_id"]) + else: + models_by_task.setdefault(model["task"], []).append(model["model_id"]) + + async def _fetch_framework(framework: str) -> None: + async with _import_aiohttp().ClientSession(headers=self.headers) as client: + response = await client.get(f"{INFERENCE_ENDPOINT}/framework/{framework}") + response.raise_for_status() + _unpack_response(framework, await response.json()) + + import asyncio + + await asyncio.gather(*[_fetch_framework(framework) for framework in frameworks]) + + # Sort alphabetically for discoverability and return + for task, models in models_by_task.items(): + models_by_task[task] = sorted(set(models), key=lambda x: x.lower()) + return models_by_task + + async def object_detection( + self, + image: ContentT, + *, + model: Optional[str] = None, + ) -> List[ObjectDetectionOutput]: + """ + Perform object detection on the given image using the specified model. + + + + You must have `PIL` installed if you want to work with images (`pip install Pillow`). + + + + Args: + image (`Union[str, Path, bytes, BinaryIO]`): + The image to detect objects on. It can be raw bytes, an image file, or a URL to an online image. + model (`str`, *optional*): + The model to use for object detection. Can be a model ID hosted on the Hugging Face Hub or a URL to a + deployed Inference Endpoint. If not provided, the default recommended model for object detection (DETR) will be used. + + Returns: + `List[ObjectDetectionOutput]`: A list of dictionaries containing the bounding boxes and associated attributes. + + Raises: + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `aiohttp.ClientResponseError`: + If the request fails with an HTTP error status code other than HTTP 503. + `ValueError`: + If the request output is not a List. + + Example: + ```py + # Must be run in an async context + >>> from huggingface_hub import AsyncInferenceClient + >>> client = AsyncInferenceClient() + >>> await client.object_detection("people.jpg"): + [{"score":0.9486683011054993,"label":"person","box":{"xmin":59,"ymin":39,"xmax":420,"ymax":510}}, ... ] + ``` + """ + # detect objects + response = await self.post(data=image, model=model, task="object-detection") + output = _bytes_to_dict(response) + if not isinstance(output, list): + raise ValueError(f"Server output must be a list. Got {type(output)}: {str(output)[:200]}...") + return output + + async def question_answering( + self, question: str, context: str, *, model: Optional[str] = None + ) -> QuestionAnsweringOutput: + """ + Retrieve the answer to a question from a given text. + + Args: + question (`str`): + Question to be answered. + context (`str`): + The context of the question. + model (`str`): + The model to use for the question answering task. Can be a model ID hosted on the Hugging Face Hub or a URL to + a deployed Inference Endpoint. + + Returns: + `Dict`: a dictionary of question answering output containing the score, start index, end index, and answer. + + Raises: + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `aiohttp.ClientResponseError`: + If the request fails with an HTTP error status code other than HTTP 503. + + Example: + ```py + # Must be run in an async context + >>> from huggingface_hub import AsyncInferenceClient + >>> client = AsyncInferenceClient() + >>> await client.question_answering(question="What's my name?", context="My name is Clara and I live in Berkeley.") + {'score': 0.9326562285423279, 'start': 11, 'end': 16, 'answer': 'Clara'} + ``` + """ + + payload: Dict[str, Any] = {"question": question, "context": context} + response = await self.post( + json=payload, + model=model, + task="question-answering", + ) + return _bytes_to_dict(response) # type: ignore + + async def sentence_similarity( + self, sentence: str, other_sentences: List[str], *, model: Optional[str] = None + ) -> List[float]: + """ + Compute the semantic similarity between a sentence and a list of other sentences by comparing their embeddings. + + Args: + sentence (`str`): + The main sentence to compare to others. + other_sentences (`List[str]`): + The list of sentences to compare to. + model (`str`, *optional*): + The model to use for the conversational task. Can be a model ID hosted on the Hugging Face Hub or a URL to + a deployed Inference Endpoint. If not provided, the default recommended conversational model will be used. + Defaults to None. + + Returns: + `List[float]`: The embedding representing the input text. + + Raises: + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `aiohttp.ClientResponseError`: + If the request fails with an HTTP error status code other than HTTP 503. + + Example: + ```py + # Must be run in an async context + >>> from huggingface_hub import AsyncInferenceClient + >>> client = AsyncInferenceClient() + >>> await client.sentence_similarity( + ... "Machine learning is so easy.", + ... other_sentences=[ + ... "Deep learning is so straightforward.", + ... "This is so difficult, like rocket science.", + ... "I can't believe how much I struggled with this.", + ... ], + ... ) + [0.7785726189613342, 0.45876261591911316, 0.2906220555305481] + ``` + """ + response = await self.post( + json={"inputs": {"source_sentence": sentence, "sentences": other_sentences}}, + model=model, + task="sentence-similarity", + ) + return _bytes_to_list(response) + + async def summarization( + self, + text: str, + *, + parameters: Optional[Dict[str, Any]] = None, + model: Optional[str] = None, + ) -> str: + """ + Generate a summary of a given text using a specified model. + + Args: + text (`str`): + The input text to summarize. + parameters (`Dict[str, Any]`, *optional*): + Additional parameters for summarization. Check out this [page](https://huggingface.co/docs/api-inference/detailed_parameters#summarization-task) + for more details. + model (`str`, *optional*): + The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed + Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None. + + Returns: + `str`: The generated summary text. + + Raises: + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `aiohttp.ClientResponseError`: + If the request fails with an HTTP error status code other than HTTP 503. + + Example: + ```py + # Must be run in an async context + >>> from huggingface_hub import AsyncInferenceClient + >>> client = AsyncInferenceClient() + >>> await client.summarization("The Eiffel tower...") + 'The Eiffel tower is one of the most famous landmarks in the world....' + ``` + """ + payload: Dict[str, Any] = {"inputs": text} + if parameters is not None: + payload["parameters"] = parameters + response = await self.post(json=payload, model=model, task="summarization") + return _bytes_to_dict(response)[0]["summary_text"] + + async def table_question_answering( + self, table: Dict[str, Any], query: str, *, model: Optional[str] = None + ) -> TableQuestionAnsweringOutput: + """ + Retrieve the answer to a question from information given in a table. + + Args: + table (`str`): + A table of data represented as a dict of lists where entries are headers and the lists are all the + values, all lists must have the same size. + query (`str`): + The query in plain text that you want to ask the table. + model (`str`): + The model to use for the table-question-answering task. Can be a model ID hosted on the Hugging Face + Hub or a URL to a deployed Inference Endpoint. + + Returns: + `Dict`: a dictionary of table question answering output containing the answer, coordinates, cells and the aggregator used. + + Raises: + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `aiohttp.ClientResponseError`: + If the request fails with an HTTP error status code other than HTTP 503. + + Example: + ```py + # Must be run in an async context + >>> from huggingface_hub import AsyncInferenceClient + >>> client = AsyncInferenceClient() + >>> query = "How many stars does the transformers repository have?" + >>> table = {"Repository": ["Transformers", "Datasets", "Tokenizers"], "Stars": ["36542", "4512", "3934"]} + >>> await client.table_question_answering(table, query, model="google/tapas-base-finetuned-wtq") + {'answer': 'AVERAGE > 36542', 'coordinates': [[0, 1]], 'cells': ['36542'], 'aggregator': 'AVERAGE'} + ``` + """ + response = await self.post( + json={ + "query": query, + "table": table, + }, + model=model, + task="table-question-answering", + ) + return _bytes_to_dict(response) # type: ignore + + async def tabular_classification(self, table: Dict[str, Any], *, model: str) -> List[str]: + """ + Classifying a target category (a group) based on a set of attributes. + + Args: + table (`Dict[str, Any]`): + Set of attributes to classify. + model (`str`): + The model to use for the tabular-classification task. Can be a model ID hosted on the Hugging Face Hub or a URL to + a deployed Inference Endpoint. + + Returns: + `List`: a list of labels, one per row in the initial table. + + Raises: + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `aiohttp.ClientResponseError`: + If the request fails with an HTTP error status code other than HTTP 503. + + Example: + ```py + # Must be run in an async context + >>> from huggingface_hub import AsyncInferenceClient + >>> client = AsyncInferenceClient() + >>> table = { + ... "fixed_acidity": ["7.4", "7.8", "10.3"], + ... "volatile_acidity": ["0.7", "0.88", "0.32"], + ... "citric_acid": ["0", "0", "0.45"], + ... "residual_sugar": ["1.9", "2.6", "6.4"], + ... "chlorides": ["0.076", "0.098", "0.073"], + ... "free_sulfur_dioxide": ["11", "25", "5"], + ... "total_sulfur_dioxide": ["34", "67", "13"], + ... "density": ["0.9978", "0.9968", "0.9976"], + ... "pH": ["3.51", "3.2", "3.23"], + ... "sulphates": ["0.56", "0.68", "0.82"], + ... "alcohol": ["9.4", "9.8", "12.6"], + ... } + >>> await client.tabular_classification(table=table, model="julien-c/wine-quality") + ["5", "5", "5"] + ``` + """ + response = await self.post(json={"table": table}, model=model, task="tabular-classification") + return _bytes_to_list(response) + + async def tabular_regression(self, table: Dict[str, Any], *, model: str) -> List[float]: + """ + Predicting a numerical target value given a set of attributes/features in a table. + + Args: + table (`Dict[str, Any]`): + Set of attributes stored in a table. The attributes used to predict the target can be both numerical and categorical. + model (`str`): + The model to use for the tabular-regression task. Can be a model ID hosted on the Hugging Face Hub or a URL to + a deployed Inference Endpoint. + + Returns: + `List`: a list of predicted numerical target values. + + Raises: + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `aiohttp.ClientResponseError`: + If the request fails with an HTTP error status code other than HTTP 503. + + Example: + ```py + # Must be run in an async context + >>> from huggingface_hub import AsyncInferenceClient + >>> client = AsyncInferenceClient() + >>> table = { + ... "Height": ["11.52", "12.48", "12.3778"], + ... "Length1": ["23.2", "24", "23.9"], + ... "Length2": ["25.4", "26.3", "26.5"], + ... "Length3": ["30", "31.2", "31.1"], + ... "Species": ["Bream", "Bream", "Bream"], + ... "Width": ["4.02", "4.3056", "4.6961"], + ... } + >>> await client.tabular_regression(table, model="scikit-learn/Fish-Weight") + [110, 120, 130] + ``` + """ + response = await self.post(json={"table": table}, model=model, task="tabular-regression") + return _bytes_to_list(response) + + async def text_classification(self, text: str, *, model: Optional[str] = None) -> List[ClassificationOutput]: + """ + Perform text classification (e.g. sentiment-analysis) on the given text. + + Args: + text (`str`): + A string to be classified. + model (`str`, *optional*): + The model to use for the text classification task. Can be a model ID hosted on the Hugging Face Hub or a URL to + a deployed Inference Endpoint. If not provided, the default recommended text classification model will be used. + Defaults to None. + + Returns: + `List[Dict]`: a list of dictionaries containing the predicted label and associated probability. + + Raises: + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `aiohttp.ClientResponseError`: + If the request fails with an HTTP error status code other than HTTP 503. + + Example: + ```py + # Must be run in an async context + >>> from huggingface_hub import AsyncInferenceClient + >>> client = AsyncInferenceClient() + >>> await client.text_classification("I like you") + [{'label': 'POSITIVE', 'score': 0.9998695850372314}, {'label': 'NEGATIVE', 'score': 0.0001304351753788069}] + ``` + """ + response = await self.post(json={"inputs": text}, model=model, task="text-classification") + return _bytes_to_list(response)[0] + + @overload + async def text_generation( # type: ignore + self, + prompt: str, + *, + details: Literal[False] = ..., + stream: Literal[False] = ..., + model: Optional[str] = None, + do_sample: bool = False, + max_new_tokens: int = 20, + best_of: Optional[int] = None, + repetition_penalty: Optional[float] = None, + return_full_text: bool = False, + seed: Optional[int] = None, + stop_sequences: Optional[List[str]] = None, + temperature: Optional[float] = None, + top_k: Optional[int] = None, + top_p: Optional[float] = None, + truncate: Optional[int] = None, + typical_p: Optional[float] = None, + watermark: bool = False, + ) -> str: + ... + + @overload + async def text_generation( # type: ignore + self, + prompt: str, + *, + details: Literal[True] = ..., + stream: Literal[False] = ..., + model: Optional[str] = None, + do_sample: bool = False, + max_new_tokens: int = 20, + best_of: Optional[int] = None, + repetition_penalty: Optional[float] = None, + return_full_text: bool = False, + seed: Optional[int] = None, + stop_sequences: Optional[List[str]] = None, + temperature: Optional[float] = None, + top_k: Optional[int] = None, + top_p: Optional[float] = None, + truncate: Optional[int] = None, + typical_p: Optional[float] = None, + watermark: bool = False, + ) -> TextGenerationResponse: + ... + + @overload + async def text_generation( # type: ignore + self, + prompt: str, + *, + details: Literal[False] = ..., + stream: Literal[True] = ..., + model: Optional[str] = None, + do_sample: bool = False, + max_new_tokens: int = 20, + best_of: Optional[int] = None, + repetition_penalty: Optional[float] = None, + return_full_text: bool = False, + seed: Optional[int] = None, + stop_sequences: Optional[List[str]] = None, + temperature: Optional[float] = None, + top_k: Optional[int] = None, + top_p: Optional[float] = None, + truncate: Optional[int] = None, + typical_p: Optional[float] = None, + watermark: bool = False, + ) -> AsyncIterable[str]: + ... + + @overload + async def text_generation( + self, + prompt: str, + *, + details: Literal[True] = ..., + stream: Literal[True] = ..., + model: Optional[str] = None, + do_sample: bool = False, + max_new_tokens: int = 20, + best_of: Optional[int] = None, + repetition_penalty: Optional[float] = None, + return_full_text: bool = False, + seed: Optional[int] = None, + stop_sequences: Optional[List[str]] = None, + temperature: Optional[float] = None, + top_k: Optional[int] = None, + top_p: Optional[float] = None, + truncate: Optional[int] = None, + typical_p: Optional[float] = None, + watermark: bool = False, + ) -> AsyncIterable[TextGenerationStreamResponse]: + ... + + async def text_generation( + self, + prompt: str, + *, + details: bool = False, + stream: bool = False, + model: Optional[str] = None, + do_sample: bool = False, + max_new_tokens: int = 20, + best_of: Optional[int] = None, + repetition_penalty: Optional[float] = None, + return_full_text: bool = False, + seed: Optional[int] = None, + stop_sequences: Optional[List[str]] = None, + temperature: Optional[float] = None, + top_k: Optional[int] = None, + top_p: Optional[float] = None, + truncate: Optional[int] = None, + typical_p: Optional[float] = None, + watermark: bool = False, + decoder_input_details: bool = False, + ) -> Union[str, TextGenerationResponse, AsyncIterable[str], AsyncIterable[TextGenerationStreamResponse]]: + """ + Given a prompt, generate the following text. + + It is recommended to have Pydantic installed in order to get inputs validated. This is preferable as it allow + early failures. + + API endpoint is supposed to run with the `text-generation-inference` backend (TGI). This backend is the + go-to solution to run large language models at scale. However, for some smaller models (e.g. "gpt2") the + default `transformers` + `api-inference` solution is still in use. Both approaches have very similar APIs, but + not exactly the same. This method is compatible with both approaches but some parameters are only available for + `text-generation-inference`. If some parameters are ignored, a warning message is triggered but the process + continues correctly. + + To learn more about the TGI project, please refer to https://github.com/huggingface/text-generation-inference. + + Args: + prompt (`str`): + Input text. + details (`bool`, *optional*): + By default, text_generation returns a string. Pass `details=True` if you want a detailed output (tokens, + probabilities, seed, finish reason, etc.). Only available for models running on with the + `text-generation-inference` backend. + stream (`bool`, *optional*): + By default, text_generation returns the full generated text. Pass `stream=True` if you want a stream of + tokens to be returned. Only available for models running on with the `text-generation-inference` + backend. + model (`str`, *optional*): + The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed + Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None. + do_sample (`bool`): + Activate logits sampling + max_new_tokens (`int`): + Maximum number of generated tokens + best_of (`int`): + Generate best_of sequences and return the one if the highest token logprobs + repetition_penalty (`float`): + The parameter for repetition penalty. 1.0 means no penalty. See [this + paper](https://arxiv.org/pdf/1909.05858.pdf) for more details. + return_full_text (`bool`): + Whether to prepend the prompt to the generated text + seed (`int`): + Random sampling seed + stop_sequences (`List[str]`): + Stop generating tokens if a member of `stop_sequences` is generated + temperature (`float`): + The value used to module the logits distribution. + top_k (`int`): + The number of highest probability vocabulary tokens to keep for top-k-filtering. + top_p (`float`): + If set to < 1, only the smallest set of most probable tokens with probabilities that add up to `top_p` or + higher are kept for generation. + truncate (`int`): + Truncate inputs tokens to the given size + typical_p (`float`): + Typical Decoding mass + See [Typical Decoding for Natural Language Generation](https://arxiv.org/abs/2202.00666) for more information + watermark (`bool`): + Watermarking with [A Watermark for Large Language Models](https://arxiv.org/abs/2301.10226) + decoder_input_details (`bool`): + Return the decoder input token logprobs and ids. You must set `details=True` as well for it to be taken + into account. Defaults to `False`. + + Returns: + `Union[str, TextGenerationResponse, Iterable[str], Iterable[TextGenerationStreamResponse]]`: + Generated text returned from the server: + - if `stream=False` and `details=False`, the generated text is returned as a `str` (default) + - if `stream=True` and `details=False`, the generated text is returned token by token as a `Iterable[str]` + - if `stream=False` and `details=True`, the generated text is returned with more details as a [`~huggingface_hub.inference._text_generation.TextGenerationResponse`] + - if `details=True` and `stream=True`, the generated text is returned token by token as a iterable of [`~huggingface_hub.inference._text_generation.TextGenerationStreamResponse`] + + Raises: + `ValidationError`: + If input values are not valid. No HTTP call is made to the server. + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `aiohttp.ClientResponseError`: + If the request fails with an HTTP error status code other than HTTP 503. + + Example: + ```py + # Must be run in an async context + >>> from huggingface_hub import AsyncInferenceClient + >>> client = AsyncInferenceClient() + + # Case 1: generate text + >>> await client.text_generation("The huggingface_hub library is ", max_new_tokens=12) + '100% open source and built to be easy to use.' + + # Case 2: iterate over the generated tokens. Useful async for large generation. + >>> async for token in await client.text_generation("The huggingface_hub library is ", max_new_tokens=12, stream=True): + ... print(token) + 100 + % + open + source + and + built + to + be + easy + to + use + . + + # Case 3: get more details about the generation process. + >>> await client.text_generation("The huggingface_hub library is ", max_new_tokens=12, details=True) + TextGenerationResponse( + generated_text='100% open source and built to be easy to use.', + details=Details( + finish_reason=, + generated_tokens=12, + seed=None, + prefill=[ + InputToken(id=487, text='The', logprob=None), + InputToken(id=53789, text=' hugging', logprob=-13.171875), + (...) + InputToken(id=204, text=' ', logprob=-7.0390625) + ], + tokens=[ + Token(id=1425, text='100', logprob=-1.0175781, special=False), + Token(id=16, text='%', logprob=-0.0463562, special=False), + (...) + Token(id=25, text='.', logprob=-0.5703125, special=False) + ], + best_of_sequences=None + ) + ) + + # Case 4: iterate over the generated tokens with more details. + # Last object is more complete, containing the full generated text and the finish reason. + >>> async for details in await client.text_generation("The huggingface_hub library is ", max_new_tokens=12, details=True, stream=True): + ... print(details) + ... + TextGenerationStreamResponse(token=Token(id=1425, text='100', logprob=-1.0175781, special=False), generated_text=None, details=None) + TextGenerationStreamResponse(token=Token(id=16, text='%', logprob=-0.0463562, special=False), generated_text=None, details=None) + TextGenerationStreamResponse(token=Token(id=1314, text=' open', logprob=-1.3359375, special=False), generated_text=None, details=None) + TextGenerationStreamResponse(token=Token(id=3178, text=' source', logprob=-0.28100586, special=False), generated_text=None, details=None) + TextGenerationStreamResponse(token=Token(id=273, text=' and', logprob=-0.5961914, special=False), generated_text=None, details=None) + TextGenerationStreamResponse(token=Token(id=3426, text=' built', logprob=-1.9423828, special=False), generated_text=None, details=None) + TextGenerationStreamResponse(token=Token(id=271, text=' to', logprob=-1.4121094, special=False), generated_text=None, details=None) + TextGenerationStreamResponse(token=Token(id=314, text=' be', logprob=-1.5224609, special=False), generated_text=None, details=None) + TextGenerationStreamResponse(token=Token(id=1833, text=' easy', logprob=-2.1132812, special=False), generated_text=None, details=None) + TextGenerationStreamResponse(token=Token(id=271, text=' to', logprob=-0.08520508, special=False), generated_text=None, details=None) + TextGenerationStreamResponse(token=Token(id=745, text=' use', logprob=-0.39453125, special=False), generated_text=None, details=None) + TextGenerationStreamResponse(token=Token( + id=25, + text='.', + logprob=-0.5703125, + special=False), + generated_text='100% open source and built to be easy to use.', + details=StreamDetails(finish_reason=, generated_tokens=12, seed=None) + ) + ``` + """ + # NOTE: Text-generation integration is taken from the text-generation-inference project. It has more features + # like input/output validation (if Pydantic is installed). See `_text_generation.py` header for more details. + + if decoder_input_details and not details: + warnings.warn( + "`decoder_input_details=True` has been passed to the server but `details=False` is set meaning that" + " the output from the server will be truncated." + ) + decoder_input_details = False + + # Validate parameters + parameters = TextGenerationParameters( + best_of=best_of, + details=details, + do_sample=do_sample, + max_new_tokens=max_new_tokens, + repetition_penalty=repetition_penalty, + return_full_text=return_full_text, + seed=seed, + stop=stop_sequences if stop_sequences is not None else [], + temperature=temperature, + top_k=top_k, + top_p=top_p, + truncate=truncate, + typical_p=typical_p, + watermark=watermark, + decoder_input_details=decoder_input_details, + ) + request = TextGenerationRequest(inputs=prompt, stream=stream, parameters=parameters) + payload = asdict(request) + + # Remove some parameters if not a TGI server + if not _is_tgi_server(model): + ignored_parameters = [] + for key in "watermark", "stop", "details", "decoder_input_details": + if payload["parameters"][key] is not None: + ignored_parameters.append(key) + del payload["parameters"][key] + if len(ignored_parameters) > 0: + warnings.warn( + "API endpoint/model for text-generation is not served via TGI. Ignoring parameters" + f" {ignored_parameters}.", + UserWarning, + ) + if details: + warnings.warn( + "API endpoint/model for text-generation is not served via TGI. Parameter `details=True` will" + " be ignored meaning only the generated text will be returned.", + UserWarning, + ) + details = False + if stream: + raise ValueError( + "API endpoint/model for text-generation is not served via TGI. Cannot return output as a stream." + " Please pass `stream=False` as input." + ) + + # Handle errors separately for more precise error messages + try: + bytes_output = await self.post(json=payload, model=model, task="text-generation", stream=stream) # type: ignore + except _import_aiohttp().ClientResponseError as e: + error_message = getattr(e, "response_error_payload", {}).get("error", "") + if e.code == 400 and "The following `model_kwargs` are not used by the model" in error_message: + _set_as_non_tgi(model) + return await self.text_generation( # type: ignore + prompt=prompt, + details=details, + stream=stream, + model=model, + do_sample=do_sample, + max_new_tokens=max_new_tokens, + best_of=best_of, + repetition_penalty=repetition_penalty, + return_full_text=return_full_text, + seed=seed, + stop_sequences=stop_sequences, + temperature=temperature, + top_k=top_k, + top_p=top_p, + truncate=truncate, + typical_p=typical_p, + watermark=watermark, + decoder_input_details=decoder_input_details, + ) + raise_text_generation_error(e) + + # Parse output + if stream: + return _async_stream_text_generation_response(bytes_output, details) # type: ignore + + data = _bytes_to_dict(bytes_output)[0] + return TextGenerationResponse(**data) if details else data["generated_text"] + + async def text_to_image( + self, + prompt: str, + *, + negative_prompt: Optional[str] = None, + height: Optional[float] = None, + width: Optional[float] = None, + num_inference_steps: Optional[float] = None, + guidance_scale: Optional[float] = None, + model: Optional[str] = None, + **kwargs, + ) -> "Image": + """ + Generate an image based on a given text using a specified model. + + + + You must have `PIL` installed if you want to work with images (`pip install Pillow`). + + + + Args: + prompt (`str`): + The prompt to generate an image from. + negative_prompt (`str`, *optional*): + An optional negative prompt for the image generation. + height (`float`, *optional*): + The height in pixels of the image to generate. + width (`float`, *optional*): + The width in pixels of the image to generate. + num_inference_steps (`int`, *optional*): + The number of denoising steps. More denoising steps usually lead to a higher quality image at the + expense of slower inference. + guidance_scale (`float`, *optional*): + Higher guidance scale encourages to generate images that are closely linked to the text `prompt`, + usually at the expense of lower image quality. + model (`str`, *optional*): + The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed + Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None. + + Returns: + `Image`: The generated image. + + Raises: + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `aiohttp.ClientResponseError`: + If the request fails with an HTTP error status code other than HTTP 503. + + Example: + ```py + # Must be run in an async context + >>> from huggingface_hub import AsyncInferenceClient + >>> client = AsyncInferenceClient() + + >>> image = await client.text_to_image("An astronaut riding a horse on the moon.") + >>> image.save("astronaut.png") + + >>> image = await client.text_to_image( + ... "An astronaut riding a horse on the moon.", + ... negative_prompt="low resolution, blurry", + ... model="stabilityai/stable-diffusion-2-1", + ... ) + >>> image.save("better_astronaut.png") + ``` + """ + payload = {"inputs": prompt} + parameters = { + "negative_prompt": negative_prompt, + "height": height, + "width": width, + "num_inference_steps": num_inference_steps, + "guidance_scale": guidance_scale, + **kwargs, + } + for key, value in parameters.items(): + if value is not None: + payload.setdefault("parameters", {})[key] = value # type: ignore + response = await self.post(json=payload, model=model, task="text-to-image") + return _bytes_to_image(response) + + async def text_to_speech(self, text: str, *, model: Optional[str] = None) -> bytes: + """ + Synthesize an audio of a voice pronouncing a given text. + + Args: + text (`str`): + The text to synthesize. + model (`str`, *optional*): + The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed + Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None. + + Returns: + `bytes`: The generated audio. + + Raises: + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `aiohttp.ClientResponseError`: + If the request fails with an HTTP error status code other than HTTP 503. + + Example: + ```py + # Must be run in an async context + >>> from pathlib import Path + >>> from huggingface_hub import AsyncInferenceClient + >>> client = AsyncInferenceClient() + + >>> audio = await client.text_to_speech("Hello world") + >>> Path("hello_world.flac").write_bytes(audio) + ``` + """ + return await self.post(json={"inputs": text}, model=model, task="text-to-speech") + + async def token_classification(self, text: str, *, model: Optional[str] = None) -> List[TokenClassificationOutput]: + """ + Perform token classification on the given text. + Usually used for sentence parsing, either grammatical, or Named Entity Recognition (NER) to understand keywords contained within text. + + Args: + text (`str`): + A string to be classified. + model (`str`, *optional*): + The model to use for the token classification task. Can be a model ID hosted on the Hugging Face Hub or a URL to + a deployed Inference Endpoint. If not provided, the default recommended token classification model will be used. + Defaults to None. + + Returns: + `List[Dict]`: List of token classification outputs containing the entity group, confidence score, word, start and end index. + + Raises: + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `aiohttp.ClientResponseError`: + If the request fails with an HTTP error status code other than HTTP 503. + + Example: + ```py + # Must be run in an async context + >>> from huggingface_hub import AsyncInferenceClient + >>> client = AsyncInferenceClient() + >>> await client.token_classification("My name is Sarah Jessica Parker but you can call me Jessica") + [{'entity_group': 'PER', + 'score': 0.9971321225166321, + 'word': 'Sarah Jessica Parker', + 'start': 11, + 'end': 31}, + {'entity_group': 'PER', + 'score': 0.9773476123809814, + 'word': 'Jessica', + 'start': 52, + 'end': 59}] + ``` + """ + payload: Dict[str, Any] = {"inputs": text} + response = await self.post( + json=payload, + model=model, + task="token-classification", + ) + return _bytes_to_list(response) + + async def translation( + self, text: str, *, model: Optional[str] = None, src_lang: Optional[str] = None, tgt_lang: Optional[str] = None + ) -> str: + """ + Convert text from one language to another. + + Check out https://huggingface.co/tasks/translation for more information on how to choose the best model for + your specific use case. Source and target languages usually depend on the model. + However, it is possible to specify source and target languages for certain models. If you are working with one of these models, + you can use `src_lang` and `tgt_lang` arguments to pass the relevant information. + You can find this information in the model card. + + Args: + text (`str`): + A string to be translated. + model (`str`, *optional*): + The model to use for the translation task. Can be a model ID hosted on the Hugging Face Hub or a URL to + a deployed Inference Endpoint. If not provided, the default recommended translation model will be used. + Defaults to None. + src_lang (`str`, *optional*): + Source language of the translation task, i.e. input language. Cannot be passed without `tgt_lang`. + tgt_lang (`str`, *optional*): + Target language of the translation task, i.e. output language. Cannot be passed without `src_lang`. + + Returns: + `str`: The generated translated text. + + Raises: + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `aiohttp.ClientResponseError`: + If the request fails with an HTTP error status code other than HTTP 503. + `ValueError`: + If only one of the `src_lang` and `tgt_lang` arguments are provided. + + Example: + ```py + # Must be run in an async context + >>> from huggingface_hub import AsyncInferenceClient + >>> client = AsyncInferenceClient() + >>> await client.translation("My name is Wolfgang and I live in Berlin") + 'Mein Name ist Wolfgang und ich lebe in Berlin.' + >>> await client.translation("My name is Wolfgang and I live in Berlin", model="Helsinki-NLP/opus-mt-en-fr") + "Je m'appelle Wolfgang et je vis à Berlin." + ``` + + Specifying languages: + ```py + >>> client.translation("My name is Sarah Jessica Parker but you can call me Jessica", model="facebook/mbart-large-50-many-to-many-mmt", src_lang="en_XX", tgt_lang="fr_XX") + "Mon nom est Sarah Jessica Parker mais vous pouvez m\'appeler Jessica" + ``` + """ + # Throw error if only one of `src_lang` and `tgt_lang` was given + if src_lang is not None and tgt_lang is None: + raise ValueError("You cannot specify `src_lang` without specifying `tgt_lang`.") + + if src_lang is None and tgt_lang is not None: + raise ValueError("You cannot specify `tgt_lang` without specifying `src_lang`.") + + # If both `src_lang` and `tgt_lang` are given, pass them to the request body + payload: Dict = {"inputs": text} + if src_lang and tgt_lang: + payload["parameters"] = {"src_lang": src_lang, "tgt_lang": tgt_lang} + response = await self.post(json=payload, model=model, task="translation") + return _bytes_to_dict(response)[0]["translation_text"] + + async def zero_shot_classification( + self, text: str, labels: List[str], *, multi_label: bool = False, model: Optional[str] = None + ) -> List[ClassificationOutput]: + """ + Provide as input a text and a set of candidate labels to classify the input text. + + Args: + text (`str`): + The input text to classify. + labels (`List[str]`): + List of string possible labels. There must be at least 2 labels. + multi_label (`bool`): + Boolean that is set to True if classes can overlap. + model (`str`, *optional*): + The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed + Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None. + + Returns: + `List[Dict]`: List of classification outputs containing the predicted labels and their confidence. + + Raises: + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `aiohttp.ClientResponseError`: + If the request fails with an HTTP error status code other than HTTP 503. + + Example: + ```py + # Must be run in an async context + >>> from huggingface_hub import AsyncInferenceClient + >>> client = AsyncInferenceClient() + >>> text = ( + ... "A new model offers an explanation async for how the Galilean satellites formed around the solar system's" + ... "largest world. Konstantin Batygin did not set out to solve one of the solar system's most puzzling" + ... " mysteries when he went async for a run up a hill in Nice, France." + ... ) + >>> labels = ["space & cosmos", "scientific discovery", "microbiology", "robots", "archeology"] + >>> await client.zero_shot_classification(text, labels) + [ + {"label": "scientific discovery", "score": 0.7961668968200684}, + {"label": "space & cosmos", "score": 0.18570658564567566}, + {"label": "microbiology", "score": 0.00730885099619627}, + {"label": "archeology", "score": 0.006258360575884581}, + {"label": "robots", "score": 0.004559356719255447}, + ] + >>> await client.zero_shot_classification(text, labels, multi_label=True) + [ + {"label": "scientific discovery", "score": 0.9829297661781311}, + {"label": "space & cosmos", "score": 0.755190908908844}, + {"label": "microbiology", "score": 0.0005462635890580714}, + {"label": "archeology", "score": 0.00047131875180639327}, + {"label": "robots", "score": 0.00030448526376858354}, + ] + ``` + """ + # Raise ValueError if input is less than 2 labels + if len(labels) < 2: + raise ValueError("You must specify at least 2 classes to compare.") + + response = await self.post( + json={ + "inputs": text, + "parameters": { + "candidate_labels": ",".join(labels), + "multi_label": multi_label, + }, + }, + model=model, + task="zero-shot-classification", + ) + output = _bytes_to_dict(response) + return [{"label": label, "score": score} for label, score in zip(output["labels"], output["scores"])] + + async def zero_shot_image_classification( + self, image: ContentT, labels: List[str], *, model: Optional[str] = None + ) -> List[ClassificationOutput]: + """ + Provide input image and text labels to predict text labels for the image. + + Args: + image (`Union[str, Path, bytes, BinaryIO]`): + The input image to caption. It can be raw bytes, an image file, or a URL to an online image. + labels (`List[str]`): + List of string possible labels. There must be at least 2 labels. + model (`str`, *optional*): + The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed + Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None. + + Returns: + `List[Dict]`: List of classification outputs containing the predicted labels and their confidence. + + Raises: + [`InferenceTimeoutError`]: + If the model is unavailable or the request times out. + `aiohttp.ClientResponseError`: + If the request fails with an HTTP error status code other than HTTP 503. + + Example: + ```py + # Must be run in an async context + >>> from huggingface_hub import AsyncInferenceClient + >>> client = AsyncInferenceClient() + + >>> await client.zero_shot_image_classification( + ... "https://upload.wikimedia.org/wikipedia/commons/thumb/4/43/Cute_dog.jpg/320px-Cute_dog.jpg", + ... labels=["dog", "cat", "horse"], + ... ) + [{"label": "dog", "score": 0.956}, ...] + ``` + """ + # Raise ValueError if input is less than 2 labels + if len(labels) < 2: + raise ValueError("You must specify at least 2 classes to compare.") + + response = await self.post( + json={"image": _b64_encode(image), "parameters": {"candidate_labels": ",".join(labels)}}, + model=model, + task="zero-shot-image-classification", + ) + return _bytes_to_list(response) + + def _resolve_url(self, model: Optional[str] = None, task: Optional[str] = None) -> str: + model = model or self.model + + # If model is already a URL, ignore `task` and return directly + if model is not None and (model.startswith("http://") or model.startswith("https://")): + return model + + # # If no model but task is set => fetch the recommended one for this task + if model is None: + if task is None: + raise ValueError( + "You must specify at least a model (repo_id or URL) or a task, either when instantiating" + " `InferenceClient` or when making a request." + ) + model = self.get_recommended_model(task) + logger.info( + f"Using recommended model {model} for task {task}. Note that it is" + f" encouraged to explicitly set `model='{model}'` as the recommended" + " models list might get updated without prior notice." + ) + + # Compute InferenceAPI url + return ( + # Feature-extraction and sentence-similarity are the only cases where we handle models with several tasks. + f"{INFERENCE_ENDPOINT}/pipeline/{task}/{model}" + if task in ("feature-extraction", "sentence-similarity") + # Otherwise, we use the default endpoint + else f"{INFERENCE_ENDPOINT}/models/{model}" + ) + + @staticmethod + def get_recommended_model(task: str) -> str: + """ + Get the model Hugging Face recommends for the input task. + + Args: + task (`str`): + The Hugging Face task to get which model Hugging Face recommends. + All available tasks can be found [here](https://huggingface.co/tasks). + + Returns: + `str`: Name of the model recommended for the input task. + + Raises: + `ValueError`: If Hugging Face has no recommendation for the input task. + """ + model = _fetch_recommended_models().get(task) + if model is None: + raise ValueError( + f"Task {task} has no recommended model. Please specify a model" + " explicitly. Visit https://huggingface.co/tasks for more info." + ) + return model + + async def get_model_status(self, model: Optional[str] = None) -> ModelStatus: + """ + Get the status of a model hosted on the Inference API. + + + + This endpoint is mostly useful when you already know which model you want to use and want to check its + availability. If you want to discover already deployed models, you should rather use [`~InferenceClient.list_deployed_models`]. + + + + Args: + model (`str`, *optional*): + Identifier of the model for witch the status gonna be checked. If model is not provided, + the model associated with this instance of [`InferenceClient`] will be used. Only InferenceAPI service can be checked so the + identifier cannot be a URL. + + + Returns: + [`ModelStatus`]: An instance of ModelStatus dataclass, containing information, + about the state of the model: load, state, compute type and framework. + + Example: + ```py + # Must be run in an async context + >>> from huggingface_hub import AsyncInferenceClient + >>> client = AsyncInferenceClient() + >>> await client.get_model_status("bigcode/starcoder") + ModelStatus(loaded=True, state='Loaded', compute_type='gpu', framework='text-generation-inference') + ``` + """ + model = model or self.model + if model is None: + raise ValueError("Model id not provided.") + if model.startswith("https://"): + raise NotImplementedError("Model status is only available for Inference API endpoints.") + url = f"{INFERENCE_ENDPOINT}/status/{model}" + + async with _import_aiohttp().ClientSession(headers=self.headers) as client: + response = await client.get(url) + response.raise_for_status() + response_data = await response.json() + + if "error" in response_data: + raise ValueError(response_data["error"]) + + return ModelStatus( + loaded=response_data["loaded"], + state=response_data["state"], + compute_type=response_data["compute_type"], + framework=response_data["framework"], + ) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/inference/_text_generation.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/inference/_text_generation.py new file mode 100644 index 0000000000000000000000000000000000000000..f48b0424e3d512c3ff6b6d651c932dbff010a9cd --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/inference/_text_generation.py @@ -0,0 +1,546 @@ +# coding=utf-8 +# Copyright 2023-present, the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Original implementation taken from the `text-generation` Python client (see https://pypi.org/project/text-generation/ +# and https://github.com/huggingface/text-generation-inference/tree/main/clients/python) +# +# Changes compared to original implementation: +# - use pydantic.dataclasses instead of BaseModel +# - default to Python's dataclasses if Pydantic is not installed (same implementation but no validation) +# - added default values for all parameters (not needed in BaseModel but dataclasses yes) +# - integrated in `huggingface_hub.InferenceClient`` +# - added `stream: bool` and `details: bool` in the `text_generation` method instead of having different methods for each use case +import warnings +from dataclasses import field +from enum import Enum +from typing import List, NoReturn, Optional + +from requests import HTTPError + +from ..utils import is_pydantic_available + + +if is_pydantic_available(): + from pydantic import validator as pydantic_validator + from pydantic.dataclasses import dataclass + + def validator(*args, **kwargs): + # Pydantic v1's `@validator` is deprecated in favor of `@field_validator`. In order to support both pydantic v1 + # and v2 without changing the logic, we catch the warning message in pydantic v2 and ignore it. If we want to + # support pydantic v3 in the future, we will drop support for pydantic v1 and use `pydantic.field_validator` + # correctly. + # + # Related: + # - https://docs.pydantic.dev/latest/migration/#changes-to-validators + # - https://github.com/huggingface/huggingface_hub/pull/1837 + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", message="Pydantic V1 style `@validator` validators are deprecated.") + return pydantic_validator(*args, **kwargs) +else: + # No validation if Pydantic is not installed + from dataclasses import dataclass # type: ignore + + def validator(x): # type: ignore + return lambda y: y + + +@dataclass +class TextGenerationParameters: + """ + Parameters for text generation. + + Args: + do_sample (`bool`, *optional*): + Activate logits sampling. Defaults to False. + max_new_tokens (`int`, *optional*): + Maximum number of generated tokens. Defaults to 20. + repetition_penalty (`Optional[float]`, *optional*): + The parameter for repetition penalty. A value of 1.0 means no penalty. See [this paper](https://arxiv.org/pdf/1909.05858.pdf) + for more details. Defaults to None. + return_full_text (`bool`, *optional*): + Whether to prepend the prompt to the generated text. Defaults to False. + stop (`List[str]`, *optional*): + Stop generating tokens if a member of `stop_sequences` is generated. Defaults to an empty list. + seed (`Optional[int]`, *optional*): + Random sampling seed. Defaults to None. + temperature (`Optional[float]`, *optional*): + The value used to modulate the logits distribution. Defaults to None. + top_k (`Optional[int]`, *optional*): + The number of highest probability vocabulary tokens to keep for top-k-filtering. Defaults to None. + top_p (`Optional[float]`, *optional*): + If set to a value less than 1, only the smallest set of most probable tokens with probabilities that add up + to `top_p` or higher are kept for generation. Defaults to None. + truncate (`Optional[int]`, *optional*): + Truncate input tokens to the given size. Defaults to None. + typical_p (`Optional[float]`, *optional*): + Typical Decoding mass. See [Typical Decoding for Natural Language Generation](https://arxiv.org/abs/2202.00666) + for more information. Defaults to None. + best_of (`Optional[int]`, *optional*): + Generate `best_of` sequences and return the one with the highest token logprobs. Defaults to None. + watermark (`bool`, *optional*): + Watermarking with [A Watermark for Large Language Models](https://arxiv.org/abs/2301.10226). Defaults to False. + details (`bool`, *optional*): + Get generation details. Defaults to False. + decoder_input_details (`bool`, *optional*): + Get decoder input token logprobs and ids. Defaults to False. + """ + + # Activate logits sampling + do_sample: bool = False + # Maximum number of generated tokens + max_new_tokens: int = 20 + # The parameter for repetition penalty. 1.0 means no penalty. + # See [this paper](https://arxiv.org/pdf/1909.05858.pdf) for more details. + repetition_penalty: Optional[float] = None + # Whether to prepend the prompt to the generated text + return_full_text: bool = False + # Stop generating tokens if a member of `stop_sequences` is generated + stop: List[str] = field(default_factory=lambda: []) + # Random sampling seed + seed: Optional[int] = None + # The value used to module the logits distribution. + temperature: Optional[float] = None + # The number of highest probability vocabulary tokens to keep for top-k-filtering. + top_k: Optional[int] = None + # If set to < 1, only the smallest set of most probable tokens with probabilities that add up to `top_p` or + # higher are kept for generation. + top_p: Optional[float] = None + # truncate inputs tokens to the given size + truncate: Optional[int] = None + # Typical Decoding mass + # See [Typical Decoding for Natural Language Generation](https://arxiv.org/abs/2202.00666) for more information + typical_p: Optional[float] = None + # Generate best_of sequences and return the one if the highest token logprobs + best_of: Optional[int] = None + # Watermarking with [A Watermark for Large Language Models](https://arxiv.org/abs/2301.10226) + watermark: bool = False + # Get generation details + details: bool = False + # Get decoder input token logprobs and ids + decoder_input_details: bool = False + + @validator("best_of") + def valid_best_of(cls, field_value, values): + if field_value is not None: + if field_value <= 0: + raise ValueError("`best_of` must be strictly positive") + if field_value > 1 and values["seed"] is not None: + raise ValueError("`seed` must not be set when `best_of` is > 1") + sampling = ( + values["do_sample"] + | (values["temperature"] is not None) + | (values["top_k"] is not None) + | (values["top_p"] is not None) + | (values["typical_p"] is not None) + ) + if field_value > 1 and not sampling: + raise ValueError("you must use sampling when `best_of` is > 1") + + return field_value + + @validator("repetition_penalty") + def valid_repetition_penalty(cls, v): + if v is not None and v <= 0: + raise ValueError("`repetition_penalty` must be strictly positive") + return v + + @validator("seed") + def valid_seed(cls, v): + if v is not None and v < 0: + raise ValueError("`seed` must be positive") + return v + + @validator("temperature") + def valid_temp(cls, v): + if v is not None and v <= 0: + raise ValueError("`temperature` must be strictly positive") + return v + + @validator("top_k") + def valid_top_k(cls, v): + if v is not None and v <= 0: + raise ValueError("`top_k` must be strictly positive") + return v + + @validator("top_p") + def valid_top_p(cls, v): + if v is not None and (v <= 0 or v >= 1.0): + raise ValueError("`top_p` must be > 0.0 and < 1.0") + return v + + @validator("truncate") + def valid_truncate(cls, v): + if v is not None and v <= 0: + raise ValueError("`truncate` must be strictly positive") + return v + + @validator("typical_p") + def valid_typical_p(cls, v): + if v is not None and (v <= 0 or v >= 1.0): + raise ValueError("`typical_p` must be > 0.0 and < 1.0") + return v + + +@dataclass +class TextGenerationRequest: + """ + Request object for text generation (only for internal use). + + Args: + inputs (`str`): + The prompt for text generation. + parameters (`Optional[TextGenerationParameters]`, *optional*): + Generation parameters. + stream (`bool`, *optional*): + Whether to stream output tokens. Defaults to False. + """ + + # Prompt + inputs: str + # Generation parameters + parameters: Optional[TextGenerationParameters] = None + # Whether to stream output tokens + stream: bool = False + + @validator("inputs") + def valid_input(cls, v): + if not v: + raise ValueError("`inputs` cannot be empty") + return v + + @validator("stream") + def valid_best_of_stream(cls, field_value, values): + parameters = values["parameters"] + if parameters is not None and parameters.best_of is not None and parameters.best_of > 1 and field_value: + raise ValueError("`best_of` != 1 is not supported when `stream` == True") + return field_value + + def __post_init__(self): + if not is_pydantic_available(): + # If pydantic is not installed, we need to instantiate the nested dataclasses manually + if self.parameters is not None and isinstance(self.parameters, dict): + self.parameters = TextGenerationParameters(**self.parameters) + + +# Decoder input tokens +@dataclass +class InputToken: + """ + Represents an input token. + + Args: + id (`int`): + Token ID from the model tokenizer. + text (`str`): + Token text. + logprob (`float` or `None`): + Log probability of the token. Optional since the logprob of the first token cannot be computed. + """ + + # Token ID from the model tokenizer + id: int + # Token text + text: str + # Logprob + # Optional since the logprob of the first token cannot be computed + logprob: Optional[float] = None + + +# Generated tokens +@dataclass +class Token: + """ + Represents a token. + + Args: + id (`int`): + Token ID from the model tokenizer. + text (`str`): + Token text. + logprob (`float`): + Log probability of the token. + special (`bool`): + Indicates whether the token is a special token. It can be used to ignore + tokens when concatenating. + """ + + # Token ID from the model tokenizer + id: int + # Token text + text: str + # Logprob + logprob: float + # Is the token a special token + # Can be used to ignore tokens when concatenating + special: bool + + +# Generation finish reason +class FinishReason(str, Enum): + # number of generated tokens == `max_new_tokens` + Length = "length" + # the model generated its end of sequence token + EndOfSequenceToken = "eos_token" + # the model generated a text included in `stop_sequences` + StopSequence = "stop_sequence" + + +# Additional sequences when using the `best_of` parameter +@dataclass +class BestOfSequence: + """ + Represents a best-of sequence generated during text generation. + + Args: + generated_text (`str`): + The generated text. + finish_reason (`FinishReason`): + The reason for the generation to finish, represented by a `FinishReason` value. + generated_tokens (`int`): + The number of generated tokens in the sequence. + seed (`Optional[int]`): + The sampling seed if sampling was activated. + prefill (`List[InputToken]`): + The decoder input tokens. Empty if `decoder_input_details` is False. Defaults to an empty list. + tokens (`List[Token]`): + The generated tokens. Defaults to an empty list. + """ + + # Generated text + generated_text: str + # Generation finish reason + finish_reason: FinishReason + # Number of generated tokens + generated_tokens: int + # Sampling seed if sampling was activated + seed: Optional[int] = None + # Decoder input tokens, empty if decoder_input_details is False + prefill: List[InputToken] = field(default_factory=lambda: []) + # Generated tokens + tokens: List[Token] = field(default_factory=lambda: []) + + def __post_init__(self): + if not is_pydantic_available(): + # If pydantic is not installed, we need to instantiate the nested dataclasses manually + self.prefill = [ + InputToken(**input_token) if isinstance(input_token, dict) else input_token + for input_token in self.prefill + ] + self.tokens = [Token(**token) if isinstance(token, dict) else token for token in self.tokens] + + +# `generate` details +@dataclass +class Details: + """ + Represents details of a text generation. + + Args: + finish_reason (`FinishReason`): + The reason for the generation to finish, represented by a `FinishReason` value. + generated_tokens (`int`): + The number of generated tokens. + seed (`Optional[int]`): + The sampling seed if sampling was activated. + prefill (`List[InputToken]`, *optional*): + The decoder input tokens. Empty if `decoder_input_details` is False. Defaults to an empty list. + tokens (`List[Token]`): + The generated tokens. Defaults to an empty list. + best_of_sequences (`Optional[List[BestOfSequence]]`): + Additional sequences when using the `best_of` parameter. + """ + + # Generation finish reason + finish_reason: FinishReason + # Number of generated tokens + generated_tokens: int + # Sampling seed if sampling was activated + seed: Optional[int] = None + # Decoder input tokens, empty if decoder_input_details is False + prefill: List[InputToken] = field(default_factory=lambda: []) + # Generated tokens + tokens: List[Token] = field(default_factory=lambda: []) + # Additional sequences when using the `best_of` parameter + best_of_sequences: Optional[List[BestOfSequence]] = None + + def __post_init__(self): + if not is_pydantic_available(): + # If pydantic is not installed, we need to instantiate the nested dataclasses manually + self.prefill = [ + InputToken(**input_token) if isinstance(input_token, dict) else input_token + for input_token in self.prefill + ] + self.tokens = [Token(**token) if isinstance(token, dict) else token for token in self.tokens] + if self.best_of_sequences is not None: + self.best_of_sequences = [ + BestOfSequence(**best_of_sequence) if isinstance(best_of_sequence, dict) else best_of_sequence + for best_of_sequence in self.best_of_sequences + ] + + +# `generate` return value +@dataclass +class TextGenerationResponse: + """ + Represents a response for text generation. + + Only returned when `details=True`, otherwise a string is returned. + + Args: + generated_text (`str`): + The generated text. + details (`Optional[Details]`): + Generation details. Returned only if `details=True` is sent to the server. + """ + + # Generated text + generated_text: str + # Generation details + details: Optional[Details] = None + + def __post_init__(self): + if not is_pydantic_available(): + # If pydantic is not installed, we need to instantiate the nested dataclasses manually + if self.details is not None and isinstance(self.details, dict): + self.details = Details(**self.details) + + +# `generate_stream` details +@dataclass +class StreamDetails: + """ + Represents details of a text generation stream. + + Args: + finish_reason (`FinishReason`): + The reason for the generation to finish, represented by a `FinishReason` value. + generated_tokens (`int`): + The number of generated tokens. + seed (`Optional[int]`): + The sampling seed if sampling was activated. + """ + + # Generation finish reason + finish_reason: FinishReason + # Number of generated tokens + generated_tokens: int + # Sampling seed if sampling was activated + seed: Optional[int] = None + + +# `generate_stream` return value +@dataclass +class TextGenerationStreamResponse: + """ + Represents a response for streaming text generation. + + Only returned when `details=True` and `stream=True`. + + Args: + token (`Token`): + The generated token. + generated_text (`Optional[str]`, *optional*): + The complete generated text. Only available when the generation is finished. + details (`Optional[StreamDetails]`, *optional*): + Generation details. Only available when the generation is finished. + """ + + # Generated token + token: Token + # Complete generated text + # Only available when the generation is finished + generated_text: Optional[str] = None + # Generation details + # Only available when the generation is finished + details: Optional[StreamDetails] = None + + def __post_init__(self): + if not is_pydantic_available(): + # If pydantic is not installed, we need to instantiate the nested dataclasses manually + if isinstance(self.token, dict): + self.token = Token(**self.token) + if self.details is not None and isinstance(self.details, dict): + self.details = StreamDetails(**self.details) + + +# TEXT GENERATION ERRORS +# ---------------------- +# Text-generation errors are parsed separately to handle as much as possible the errors returned by the text generation +# inference project (https://github.com/huggingface/text-generation-inference). +# ---------------------- + + +class TextGenerationError(HTTPError): + """Generic error raised if text-generation went wrong.""" + + +# Text Generation Inference Errors +class ValidationError(TextGenerationError): + """Server-side validation error.""" + + +class GenerationError(TextGenerationError): + pass + + +class OverloadedError(TextGenerationError): + pass + + +class IncompleteGenerationError(TextGenerationError): + pass + + +class UnknownError(TextGenerationError): + pass + + +def raise_text_generation_error(http_error: HTTPError) -> NoReturn: + """ + Try to parse text-generation-inference error message and raise HTTPError in any case. + + Args: + error (`HTTPError`): + The HTTPError that have been raised. + """ + # Try to parse a Text Generation Inference error + + try: + # Hacky way to retrieve payload in case of aiohttp error + payload = getattr(http_error, "response_error_payload", None) or http_error.response.json() + error = payload.get("error") + error_type = payload.get("error_type") + except Exception: # no payload + raise http_error + + # If error_type => more information than `hf_raise_for_status` + if error_type is not None: + exception = _parse_text_generation_error(error, error_type) + raise exception from http_error + + # Otherwise, fallback to default error + raise http_error + + +def _parse_text_generation_error(error: Optional[str], error_type: Optional[str]) -> TextGenerationError: + if error_type == "generation": + return GenerationError(error) # type: ignore + if error_type == "incomplete_generation": + return IncompleteGenerationError(error) # type: ignore + if error_type == "overloaded": + return OverloadedError(error) # type: ignore + if error_type == "validation": + return ValidationError(error) # type: ignore + return UnknownError(error) # type: ignore diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/inference/_types.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/inference/_types.py new file mode 100644 index 0000000000000000000000000000000000000000..fb5537b9240cba26f04d5385a15cfa954c9d1d91 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/inference/_types.py @@ -0,0 +1,183 @@ +# coding=utf-8 +# Copyright 2023-present, the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import TYPE_CHECKING, List, TypedDict + + +if TYPE_CHECKING: + from PIL import Image + + +class ClassificationOutput(TypedDict): + """Dictionary containing the output of a [`~InferenceClient.audio_classification`] and [`~InferenceClient.image_classification`] task. + + Args: + label (`str`): + The label predicted by the model. + score (`float`): + The score of the label predicted by the model. + """ + + label: str + score: float + + +class ConversationalOutputConversation(TypedDict): + """Dictionary containing the "conversation" part of a [`~InferenceClient.conversational`] task. + + Args: + generated_responses (`List[str]`): + A list of the responses from the model. + past_user_inputs (`List[str]`): + A list of the inputs from the user. Must be the same length as `generated_responses`. + """ + + generated_responses: List[str] + past_user_inputs: List[str] + + +class ConversationalOutput(TypedDict): + """Dictionary containing the output of a [`~InferenceClient.conversational`] task. + + Args: + generated_text (`str`): + The last response from the model. + conversation (`ConversationalOutputConversation`): + The past conversation. + warnings (`List[str]`): + A list of warnings associated with the process. + """ + + conversation: ConversationalOutputConversation + generated_text: str + warnings: List[str] + + +class FillMaskOutput(TypedDict): + """Dictionary containing information about a [`~InferenceClient.fill_mask`] task. + + Args: + score (`float`): + The probability of the token. + token (`int`): + The id of the token. + token_str (`str`): + The string representation of the token. + sequence (`str`): + The actual sequence of tokens that ran against the model (may contain special tokens). + """ + + score: float + token: int + token_str: str + sequence: str + + +class ImageSegmentationOutput(TypedDict): + """Dictionary containing information about a [`~InferenceClient.image_segmentation`] task. In practice, image segmentation returns a + list of `ImageSegmentationOutput` with 1 item per mask. + + Args: + label (`str`): + The label corresponding to the mask. + mask (`Image`): + An Image object representing the mask predicted by the model. + score (`float`): + The score associated with the label for this mask. + """ + + label: str + mask: "Image" + score: float + + +class ObjectDetectionOutput(TypedDict): + """Dictionary containing information about a [`~InferenceClient.object_detection`] task. + + Args: + label (`str`): + The label corresponding to the detected object. + box (`dict`): + A dict response of bounding box coordinates of + the detected object: xmin, ymin, xmax, ymax + score (`float`): + The score corresponding to the detected object. + """ + + label: str + box: dict + score: float + + +class QuestionAnsweringOutput(TypedDict): + """Dictionary containing information about a [`~InferenceClient.question_answering`] task. + + Args: + score (`float`): + A float that represents how likely that the answer is correct. + start (`int`): + The index (string wise) of the start of the answer within context. + end (`int`): + The index (string wise) of the end of the answer within context. + answer (`str`): + A string that is the answer within the text. + """ + + score: float + start: int + end: int + answer: str + + +class TableQuestionAnsweringOutput(TypedDict): + """Dictionary containing information about a [`~InferenceClient.table_question_answering`] task. + + Args: + answer (`str`): + The plaintext answer. + coordinates (`List[List[int]]`): + A list of coordinates of the cells referenced in the answer. + cells (`List[int]`): + A list of coordinates of the cells contents. + aggregator (`str`): + The aggregator used to get the answer. + """ + + answer: str + coordinates: List[List[int]] + cells: List[List[int]] + aggregator: str + + +class TokenClassificationOutput(TypedDict): + """Dictionary containing the output of a [`~InferenceClient.token_classification`] task. + + Args: + entity_group (`str`): + The type for the entity being recognized (model specific). + score (`float`): + The score of the label predicted by the model. + word (`str`): + The string that was captured. + start (`int`): + The offset stringwise where the answer is located. Useful to disambiguate if word occurs multiple times. + end (`int`): + The offset stringwise where the answer is located. Useful to disambiguate if word occurs multiple times. + """ + + entity_group: str + score: float + word: str + start: int + end: int diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/templates/datasetcard_template.md b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/templates/datasetcard_template.md new file mode 100644 index 0000000000000000000000000000000000000000..f8cb4c80bfe647627589bb2a0b58273c8478cd00 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/templates/datasetcard_template.md @@ -0,0 +1,143 @@ +--- +# For reference on dataset card metadata, see the spec: https://github.com/huggingface/hub-docs/blob/main/datasetcard.md?plain=1 +# Doc / guide: https://huggingface.co/docs/hub/datasets-cards +{{ card_data }} +--- + +# Dataset Card for {{ pretty_name | default("Dataset Name", true) }} + + + +{{ dataset_summary | default("", true) }} + +## Dataset Details + +### Dataset Description + + + +{{ dataset_description | default("", true) }} + +- **Curated by:** {{ curators | default("[More Information Needed]", true)}} +- **Funded by [optional]:** {{ funded_by | default("[More Information Needed]", true)}} +- **Shared by [optional]:** {{ shared_by | default("[More Information Needed]", true)}} +- **Language(s) (NLP):** {{ language | default("[More Information Needed]", true)}} +- **License:** {{ license | default("[More Information Needed]", true)}} + +### Dataset Sources [optional] + + + +- **Repository:** {{ repo | default("[More Information Needed]", true)}} +- **Paper [optional]:** {{ paper | default("[More Information Needed]", true)}} +- **Demo [optional]:** {{ demo | default("[More Information Needed]", true)}} + +## Uses + + + +### Direct Use + + + +{{ direct_use | default("[More Information Needed]", true)}} + +### Out-of-Scope Use + + + +{{ out_of_scope_use | default("[More Information Needed]", true)}} + +## Dataset Structure + + + +{{ dataset_structure | default("[More Information Needed]", true)}} + +## Dataset Creation + +### Curation Rationale + + + +{{ curation_rationale_section | default("[More Information Needed]", true)}} + +### Source Data + + + +#### Data Collection and Processing + + + +{{ data_collection_and_processing_section | default("[More Information Needed]", true)}} + +#### Who are the source data producers? + + + +{{ source_data_producers_section | default("[More Information Needed]", true)}} + +### Annotations [optional] + + + +#### Annotation process + + + +{{ annotation_process_section | default("[More Information Needed]", true)}} + +#### Who are the annotators? + + + +{{ who_are_annotators_section | default("[More Information Needed]", true)}} + +#### Personal and Sensitive Information + + + +{{ personal_and_sensitive_information | default("[More Information Needed]", true)}} + +## Bias, Risks, and Limitations + + + +{{ bias_risks_limitations | default("[More Information Needed]", true)}} + +### Recommendations + + + +{{ bias_recommendations | default("Users should be made aware of the risks, biases and limitations of the dataset. More information needed for further recommendations.", true)}} + +## Citation [optional] + + + +**BibTeX:** + +{{ citation_bibtex | default("[More Information Needed]", true)}} + +**APA:** + +{{ citation_apa | default("[More Information Needed]", true)}} + +## Glossary [optional] + + + +{{ glossary | default("[More Information Needed]", true)}} + +## More Information [optional] + +{{ more_information | default("[More Information Needed]", true)}} + +## Dataset Card Authors [optional] + +{{ dataset_card_authors | default("[More Information Needed]", true)}} + +## Dataset Card Contact + +{{ dataset_card_contact | default("[More Information Needed]", true)}} \ No newline at end of file diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/templates/modelcard_template.md b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/templates/modelcard_template.md new file mode 100644 index 0000000000000000000000000000000000000000..4a1bc02704ada2d19f83f85af4558f1fbe2a2097 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/templates/modelcard_template.md @@ -0,0 +1,203 @@ +--- +# For reference on model card metadata, see the spec: https://github.com/huggingface/hub-docs/blob/main/modelcard.md?plain=1 +# Doc / guide: https://huggingface.co/docs/hub/model-cards +{{ card_data }} +--- + +# Model Card for {{ model_id | default("Model ID", true) }} + + + +{{ model_summary | default("", true) }} + +## Model Details + +### Model Description + + + +{{ model_description | default("", true) }} + +- **Developed by:** {{ developers | default("[More Information Needed]", true)}} +- **Funded by [optional]:** {{ funded_by | default("[More Information Needed]", true)}} +- **Shared by [optional]:** {{ shared_by | default("[More Information Needed]", true)}} +- **Model type:** {{ model_type | default("[More Information Needed]", true)}} +- **Language(s) (NLP):** {{ language | default("[More Information Needed]", true)}} +- **License:** {{ license | default("[More Information Needed]", true)}} +- **Finetuned from model [optional]:** {{ base_model | default("[More Information Needed]", true)}} + +### Model Sources [optional] + + + +- **Repository:** {{ repo | default("[More Information Needed]", true)}} +- **Paper [optional]:** {{ paper | default("[More Information Needed]", true)}} +- **Demo [optional]:** {{ demo | default("[More Information Needed]", true)}} + +## Uses + + + +### Direct Use + + + +{{ direct_use | default("[More Information Needed]", true)}} + +### Downstream Use [optional] + + + +{{ downstream_use | default("[More Information Needed]", true)}} + +### Out-of-Scope Use + + + +{{ out_of_scope_use | default("[More Information Needed]", true)}} + +## Bias, Risks, and Limitations + + + +{{ bias_risks_limitations | default("[More Information Needed]", true)}} + +### Recommendations + + + +{{ bias_recommendations | default("Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.", true)}} + +## How to Get Started with the Model + +Use the code below to get started with the model. + +{{ get_started_code | default("[More Information Needed]", true)}} + +## Training Details + +### Training Data + + + +{{ training_data | default("[More Information Needed]", true)}} + +### Training Procedure + + + +#### Preprocessing [optional] + +{{ preprocessing | default("[More Information Needed]", true)}} + + +#### Training Hyperparameters + +- **Training regime:** {{ training_regime | default("[More Information Needed]", true)}} + +#### Speeds, Sizes, Times [optional] + + + +{{ speeds_sizes_times | default("[More Information Needed]", true)}} + +## Evaluation + + + +### Testing Data, Factors & Metrics + +#### Testing Data + + + +{{ testing_data | default("[More Information Needed]", true)}} + +#### Factors + + + +{{ testing_factors | default("[More Information Needed]", true)}} + +#### Metrics + + + +{{ testing_metrics | default("[More Information Needed]", true)}} + +### Results + +{{ results | default("[More Information Needed]", true)}} + +#### Summary + +{{ results_summary | default("", true) }} + +## Model Examination [optional] + + + +{{ model_examination | default("[More Information Needed]", true)}} + +## Environmental Impact + + + +Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700). + +- **Hardware Type:** {{ hardware_type | default("[More Information Needed]", true)}} +- **Hours used:** {{ hours_used | default("[More Information Needed]", true)}} +- **Cloud Provider:** {{ cloud_provider | default("[More Information Needed]", true)}} +- **Compute Region:** {{ cloud_region | default("[More Information Needed]", true)}} +- **Carbon Emitted:** {{ co2_emitted | default("[More Information Needed]", true)}} + +## Technical Specifications [optional] + +### Model Architecture and Objective + +{{ model_specs | default("[More Information Needed]", true)}} + +### Compute Infrastructure + +{{ compute_infrastructure | default("[More Information Needed]", true)}} + +#### Hardware + +{{ hardware_requirements | default("[More Information Needed]", true)}} + +#### Software + +{{ software | default("[More Information Needed]", true)}} + +## Citation [optional] + + + +**BibTeX:** + +{{ citation_bibtex | default("[More Information Needed]", true)}} + +**APA:** + +{{ citation_apa | default("[More Information Needed]", true)}} + +## Glossary [optional] + + + +{{ glossary | default("[More Information Needed]", true)}} + +## More Information [optional] + +{{ more_information | default("[More Information Needed]", true)}} + +## Model Card Authors [optional] + +{{ model_card_authors | default("[More Information Needed]", true)}} + +## Model Card Contact + +{{ model_card_contact | default("[More Information Needed]", true)}} + + + diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a15434e0004ccb3a993eaeeffecc1f9a8c3ff928 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__init__.py @@ -0,0 +1,108 @@ +# flake8: noqa +#!/usr/bin/env python +# coding=utf-8 +# Copyright 2021 The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License + +from . import tqdm as _tqdm # _tqdm is the module +from ._cache_assets import cached_assets_path +from ._cache_manager import ( + CachedFileInfo, + CachedRepoInfo, + CachedRevisionInfo, + CacheNotFound, + CorruptedCacheException, + DeleteCacheStrategy, + HFCacheInfo, + scan_cache_dir, +) +from ._chunk_utils import chunk_iterable +from ._datetime import parse_datetime +from ._errors import ( + BadRequestError, + EntryNotFoundError, + FileMetadataError, + GatedRepoError, + HfHubHTTPError, + LocalEntryNotFoundError, + RepositoryNotFoundError, + RevisionNotFoundError, + hf_raise_for_status, +) +from ._token import get_token +from ._fixes import SoftTemporaryDirectory, yaml_dump +from ._git_credential import list_credential_helpers, set_git_credential, unset_git_credential +from ._headers import build_hf_headers, get_token_to_send, LocalTokenNotFoundError +from ._hf_folder import HfFolder +from ._http import configure_http_backend, get_session, http_backoff, reset_sessions, OfflineModeIsEnabled +from ._pagination import paginate +from ._paths import filter_repo_objects, IGNORE_GIT_FOLDER_PATTERNS +from ._experimental import experimental +from ._runtime import ( + dump_environment_info, + get_aiohttp_version, + get_fastai_version, + get_fastcore_version, + get_gradio_version, + get_graphviz_version, + get_hf_hub_version, + get_hf_transfer_version, + get_jinja_version, + get_numpy_version, + get_pillow_version, + get_pydantic_version, + get_pydot_version, + get_python_version, + get_tensorboard_version, + get_tf_version, + get_torch_version, + is_aiohttp_available, + is_fastai_available, + is_fastcore_available, + is_numpy_available, + is_google_colab, + is_gradio_available, + is_graphviz_available, + is_hf_transfer_available, + is_jinja_available, + is_notebook, + is_pillow_available, + is_pydantic_available, + is_pydot_available, + is_tensorboard_available, + is_tf_available, + is_torch_available, +) +from ._safetensors import ( + SafetensorsFileMetadata, + SafetensorsRepoMetadata, + TensorInfo, + SafetensorsParsingError, + NotASafetensorsRepoError, +) +from ._subprocess import capture_output, run_interactive_subprocess, run_subprocess +from ._validators import ( + HFValidationError, + smoothly_deprecate_use_auth_token, + validate_hf_hub_args, + validate_repo_id, +) +from .tqdm import ( + are_progress_bars_disabled, + disable_progress_bars, + enable_progress_bars, + tqdm, + tqdm_stream_file, +) +from ._telemetry import send_telemetry diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fdbbb8fdb267736418a9dd853a85cd1104d99628 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_cache_assets.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_cache_assets.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5b87dcd08389183a05eb136b130eabe3832c3ba0 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_cache_assets.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_cache_manager.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_cache_manager.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..58cde24776168e7c0a57477a4a8112b0fec45dd9 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_cache_manager.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_chunk_utils.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_chunk_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..34edbc25ceaf903f77e699f153d629d7d5c69fef Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_chunk_utils.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_datetime.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_datetime.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..328f5976afaa362839a6ab2f42f396615f943d3a Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_datetime.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_deprecation.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_deprecation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..18261a0b265a0bc9e3cf6ffec9fd4fd7e87bc3e2 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_deprecation.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_errors.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_errors.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e6d2a38b5adf3d03c2cb5379aa3b9272a82224b7 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_errors.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_experimental.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_experimental.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d96328ac3382fd9a874c5e35a34b09f049ffdac1 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_experimental.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_fixes.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_fixes.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d40e2654c3e1512f9fd42bf3347bd7bd0f5f5620 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_fixes.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_git_credential.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_git_credential.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..16151751203f516ee5b59fd4285c1b2bb96d4229 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_git_credential.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_headers.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_headers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..beb5d740c2ddab17f156124cb15fd719f88b1da2 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_headers.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_hf_folder.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_hf_folder.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d321df8b5945dcf905144edd5acbc2ce59571c42 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_hf_folder.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_http.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_http.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b3f4b9e12da6478a3686f75c1c1dd0accd08ae85 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_http.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_pagination.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_pagination.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..052c299b9ac7033a3ed2bb67c2e4b27edb4785e7 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_pagination.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_paths.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_paths.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eb31b5d2c49431dafdd083aafefa5eefecdb4802 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_paths.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_runtime.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_runtime.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e5cedda0a15325a25f4d405efff4e04ee3e1b8d5 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_runtime.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_safetensors.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_safetensors.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..30cee660c9f1ade646a549559482a6248b3c0b86 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_safetensors.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_subprocess.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_subprocess.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..df51dac4be55dd05d3fcbb7b680b77affbbc1206 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_subprocess.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_telemetry.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_telemetry.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a5fb5b5cb8baf75d51fcc68fcfef407eba23d7f Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_telemetry.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_token.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_token.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..08a9f5a1f5fefdd8cc6809d40338845fa2c44973 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_token.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_typing.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_typing.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3b0ca5c335cc678c2eef2b640c05801ee4b2561c Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_typing.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_validators.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_validators.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9edf1fea71fc78aa6712524bf8010451c0b890e8 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/_validators.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/endpoint_helpers.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/endpoint_helpers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..25f52c413a88e32bf1d7a0eb0d29714c642542c9 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/endpoint_helpers.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/insecure_hashlib.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/insecure_hashlib.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..516bad8f9eb5438cb792f59495f7633064d46297 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/insecure_hashlib.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/logging.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/logging.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..17b78f03a41754e69a51d8b584b095bb6705dcd0 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/logging.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/sha.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/sha.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ec3fc6d4f453379969953687968b35a96d35b19e Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/sha.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/tqdm.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/tqdm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..67a83545adb27a64093fb777bfff001a329f81e0 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/__pycache__/tqdm.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_cache_assets.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_cache_assets.py new file mode 100644 index 0000000000000000000000000000000000000000..e5d435df9b0bb0c67c0bcb5ef65711e9aef367f6 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_cache_assets.py @@ -0,0 +1,135 @@ +# coding=utf-8 +# Copyright 2019-present, the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from pathlib import Path +from typing import Union + +from ..constants import HF_ASSETS_CACHE + + +def cached_assets_path( + library_name: str, + namespace: str = "default", + subfolder: str = "default", + *, + assets_dir: Union[str, Path, None] = None, +): + """Return a folder path to cache arbitrary files. + + `huggingface_hub` provides a canonical folder path to store assets. This is the + recommended way to integrate cache in a downstream library as it will benefit from + the builtins tools to scan and delete the cache properly. + + The distinction is made between files cached from the Hub and assets. Files from the + Hub are cached in a git-aware manner and entirely managed by `huggingface_hub`. See + [related documentation](https://huggingface.co/docs/huggingface_hub/how-to-cache). + All other files that a downstream library caches are considered to be "assets" + (files downloaded from external sources, extracted from a .tar archive, preprocessed + for training,...). + + Once the folder path is generated, it is guaranteed to exist and to be a directory. + The path is based on 3 levels of depth: the library name, a namespace and a + subfolder. Those 3 levels grants flexibility while allowing `huggingface_hub` to + expect folders when scanning/deleting parts of the assets cache. Within a library, + it is expected that all namespaces share the same subset of subfolder names but this + is not a mandatory rule. The downstream library has then full control on which file + structure to adopt within its cache. Namespace and subfolder are optional (would + default to a `"default/"` subfolder) but library name is mandatory as we want every + downstream library to manage its own cache. + + Expected tree: + ```text + assets/ + └── datasets/ + │ ├── SQuAD/ + │ │ ├── downloaded/ + │ │ ├── extracted/ + │ │ └── processed/ + │ ├── Helsinki-NLP--tatoeba_mt/ + │ ├── downloaded/ + │ ├── extracted/ + │ └── processed/ + └── transformers/ + ├── default/ + │ ├── something/ + ├── bert-base-cased/ + │ ├── default/ + │ └── training/ + hub/ + └── models--julien-c--EsperBERTo-small/ + ├── blobs/ + │ ├── (...) + │ ├── (...) + ├── refs/ + │ └── (...) + └── [ 128] snapshots/ + ├── 2439f60ef33a0d46d85da5001d52aeda5b00ce9f/ + │ ├── (...) + └── bbc77c8132af1cc5cf678da3f1ddf2de43606d48/ + └── (...) + ``` + + + Args: + library_name (`str`): + Name of the library that will manage the cache folder. Example: `"dataset"`. + namespace (`str`, *optional*, defaults to "default"): + Namespace to which the data belongs. Example: `"SQuAD"`. + subfolder (`str`, *optional*, defaults to "default"): + Subfolder in which the data will be stored. Example: `extracted`. + assets_dir (`str`, `Path`, *optional*): + Path to the folder where assets are cached. This must not be the same folder + where Hub files are cached. Defaults to `HF_HOME / "assets"` if not provided. + Can also be set with `HF_ASSETS_CACHE` environment variable. + + Returns: + Path to the cache folder (`Path`). + + Example: + ```py + >>> from huggingface_hub import cached_assets_path + + >>> cached_assets_path(library_name="datasets", namespace="SQuAD", subfolder="download") + PosixPath('/home/wauplin/.cache/huggingface/extra/datasets/SQuAD/download') + + >>> cached_assets_path(library_name="datasets", namespace="SQuAD", subfolder="extracted") + PosixPath('/home/wauplin/.cache/huggingface/extra/datasets/SQuAD/extracted') + + >>> cached_assets_path(library_name="datasets", namespace="Helsinki-NLP/tatoeba_mt") + PosixPath('/home/wauplin/.cache/huggingface/extra/datasets/Helsinki-NLP--tatoeba_mt/default') + + >>> cached_assets_path(library_name="datasets", assets_dir="/tmp/tmp123456") + PosixPath('/tmp/tmp123456/datasets/default/default') + ``` + """ + # Resolve assets_dir + if assets_dir is None: + assets_dir = HF_ASSETS_CACHE + assets_dir = Path(assets_dir).expanduser().resolve() + + # Avoid names that could create path issues + for part in (" ", "/", "\\"): + library_name = library_name.replace(part, "--") + namespace = namespace.replace(part, "--") + subfolder = subfolder.replace(part, "--") + + # Path to subfolder is created + path = assets_dir / library_name / namespace / subfolder + try: + path.mkdir(exist_ok=True, parents=True) + except (FileExistsError, NotADirectoryError): + raise ValueError(f"Corrupted assets folder: cannot create directory because of an existing file ({path}).") + + # Return + return path diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_cache_manager.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_cache_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..896eee724b90deb6dc24f57fe50847ce69287d47 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_cache_manager.py @@ -0,0 +1,806 @@ +# coding=utf-8 +# Copyright 2022-present, the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Contains utilities to manage the HF cache directory.""" +import os +import shutil +import time +from collections import defaultdict +from dataclasses import dataclass +from pathlib import Path +from typing import Dict, FrozenSet, List, Literal, Optional, Set, Union + +from ..constants import HF_HUB_CACHE +from . import logging + + +logger = logging.get_logger(__name__) + +REPO_TYPE_T = Literal["model", "dataset", "space"] + + +class CacheNotFound(Exception): + """Exception thrown when the Huggingface cache is not found.""" + + cache_dir: Union[str, Path] + + def __init__(self, msg: str, cache_dir: Union[str, Path], *args, **kwargs): + super().__init__(msg, *args, **kwargs) + self.cache_dir = cache_dir + + +class CorruptedCacheException(Exception): + """Exception for any unexpected structure in the Huggingface cache-system.""" + + +@dataclass(frozen=True) +class CachedFileInfo: + """Frozen data structure holding information about a single cached file. + + Args: + file_name (`str`): + Name of the file. Example: `config.json`. + file_path (`Path`): + Path of the file in the `snapshots` directory. The file path is a symlink + referring to a blob in the `blobs` folder. + blob_path (`Path`): + Path of the blob file. This is equivalent to `file_path.resolve()`. + size_on_disk (`int`): + Size of the blob file in bytes. + blob_last_accessed (`float`): + Timestamp of the last time the blob file has been accessed (from any + revision). + blob_last_modified (`float`): + Timestamp of the last time the blob file has been modified/created. + + + + `blob_last_accessed` and `blob_last_modified` reliability can depend on the OS you + are using. See [python documentation](https://docs.python.org/3/library/os.html#os.stat_result) + for more details. + + + """ + + file_name: str + file_path: Path + blob_path: Path + size_on_disk: int + + blob_last_accessed: float + blob_last_modified: float + + @property + def blob_last_accessed_str(self) -> str: + """ + (property) Timestamp of the last time the blob file has been accessed (from any + revision), returned as a human-readable string. + + Example: "2 weeks ago". + """ + return _format_timesince(self.blob_last_accessed) + + @property + def blob_last_modified_str(self) -> str: + """ + (property) Timestamp of the last time the blob file has been modified, returned + as a human-readable string. + + Example: "2 weeks ago". + """ + return _format_timesince(self.blob_last_modified) + + @property + def size_on_disk_str(self) -> str: + """ + (property) Size of the blob file as a human-readable string. + + Example: "42.2K". + """ + return _format_size(self.size_on_disk) + + +@dataclass(frozen=True) +class CachedRevisionInfo: + """Frozen data structure holding information about a revision. + + A revision correspond to a folder in the `snapshots` folder and is populated with + the exact tree structure as the repo on the Hub but contains only symlinks. A + revision can be either referenced by 1 or more `refs` or be "detached" (no refs). + + Args: + commit_hash (`str`): + Hash of the revision (unique). + Example: `"9338f7b671827df886678df2bdd7cc7b4f36dffd"`. + snapshot_path (`Path`): + Path to the revision directory in the `snapshots` folder. It contains the + exact tree structure as the repo on the Hub. + files: (`FrozenSet[CachedFileInfo]`): + Set of [`~CachedFileInfo`] describing all files contained in the snapshot. + refs (`FrozenSet[str]`): + Set of `refs` pointing to this revision. If the revision has no `refs`, it + is considered detached. + Example: `{"main", "2.4.0"}` or `{"refs/pr/1"}`. + size_on_disk (`int`): + Sum of the blob file sizes that are symlink-ed by the revision. + last_modified (`float`): + Timestamp of the last time the revision has been created/modified. + + + + `last_accessed` cannot be determined correctly on a single revision as blob files + are shared across revisions. + + + + + + `size_on_disk` is not necessarily the sum of all file sizes because of possible + duplicated files. Besides, only blobs are taken into account, not the (negligible) + size of folders and symlinks. + + + """ + + commit_hash: str + snapshot_path: Path + size_on_disk: int + files: FrozenSet[CachedFileInfo] + refs: FrozenSet[str] + + last_modified: float + + @property + def last_modified_str(self) -> str: + """ + (property) Timestamp of the last time the revision has been modified, returned + as a human-readable string. + + Example: "2 weeks ago". + """ + return _format_timesince(self.last_modified) + + @property + def size_on_disk_str(self) -> str: + """ + (property) Sum of the blob file sizes as a human-readable string. + + Example: "42.2K". + """ + return _format_size(self.size_on_disk) + + @property + def nb_files(self) -> int: + """ + (property) Total number of files in the revision. + """ + return len(self.files) + + +@dataclass(frozen=True) +class CachedRepoInfo: + """Frozen data structure holding information about a cached repository. + + Args: + repo_id (`str`): + Repo id of the repo on the Hub. Example: `"google/fleurs"`. + repo_type (`Literal["dataset", "model", "space"]`): + Type of the cached repo. + repo_path (`Path`): + Local path to the cached repo. + size_on_disk (`int`): + Sum of the blob file sizes in the cached repo. + nb_files (`int`): + Total number of blob files in the cached repo. + revisions (`FrozenSet[CachedRevisionInfo]`): + Set of [`~CachedRevisionInfo`] describing all revisions cached in the repo. + last_accessed (`float`): + Timestamp of the last time a blob file of the repo has been accessed. + last_modified (`float`): + Timestamp of the last time a blob file of the repo has been modified/created. + + + + `size_on_disk` is not necessarily the sum of all revisions sizes because of + duplicated files. Besides, only blobs are taken into account, not the (negligible) + size of folders and symlinks. + + + + + + `last_accessed` and `last_modified` reliability can depend on the OS you are using. + See [python documentation](https://docs.python.org/3/library/os.html#os.stat_result) + for more details. + + + """ + + repo_id: str + repo_type: REPO_TYPE_T + repo_path: Path + size_on_disk: int + nb_files: int + revisions: FrozenSet[CachedRevisionInfo] + + last_accessed: float + last_modified: float + + @property + def last_accessed_str(self) -> str: + """ + (property) Last time a blob file of the repo has been accessed, returned as a + human-readable string. + + Example: "2 weeks ago". + """ + return _format_timesince(self.last_accessed) + + @property + def last_modified_str(self) -> str: + """ + (property) Last time a blob file of the repo has been modified, returned as a + human-readable string. + + Example: "2 weeks ago". + """ + return _format_timesince(self.last_modified) + + @property + def size_on_disk_str(self) -> str: + """ + (property) Sum of the blob file sizes as a human-readable string. + + Example: "42.2K". + """ + return _format_size(self.size_on_disk) + + @property + def refs(self) -> Dict[str, CachedRevisionInfo]: + """ + (property) Mapping between `refs` and revision data structures. + """ + return {ref: revision for revision in self.revisions for ref in revision.refs} + + +@dataclass(frozen=True) +class DeleteCacheStrategy: + """Frozen data structure holding the strategy to delete cached revisions. + + This object is not meant to be instantiated programmatically but to be returned by + [`~utils.HFCacheInfo.delete_revisions`]. See documentation for usage example. + + Args: + expected_freed_size (`float`): + Expected freed size once strategy is executed. + blobs (`FrozenSet[Path]`): + Set of blob file paths to be deleted. + refs (`FrozenSet[Path]`): + Set of reference file paths to be deleted. + repos (`FrozenSet[Path]`): + Set of entire repo paths to be deleted. + snapshots (`FrozenSet[Path]`): + Set of snapshots to be deleted (directory of symlinks). + """ + + expected_freed_size: int + blobs: FrozenSet[Path] + refs: FrozenSet[Path] + repos: FrozenSet[Path] + snapshots: FrozenSet[Path] + + @property + def expected_freed_size_str(self) -> str: + """ + (property) Expected size that will be freed as a human-readable string. + + Example: "42.2K". + """ + return _format_size(self.expected_freed_size) + + def execute(self) -> None: + """Execute the defined strategy. + + + + If this method is interrupted, the cache might get corrupted. Deletion order is + implemented so that references and symlinks are deleted before the actual blob + files. + + + + + + This method is irreversible. If executed, cached files are erased and must be + downloaded again. + + + """ + # Deletion order matters. Blobs are deleted in last so that the user can't end + # up in a state where a `ref`` refers to a missing snapshot or a snapshot + # symlink refers to a deleted blob. + + # Delete entire repos + for path in self.repos: + _try_delete_path(path, path_type="repo") + + # Delete snapshot directories + for path in self.snapshots: + _try_delete_path(path, path_type="snapshot") + + # Delete refs files + for path in self.refs: + _try_delete_path(path, path_type="ref") + + # Delete blob files + for path in self.blobs: + _try_delete_path(path, path_type="blob") + + logger.info(f"Cache deletion done. Saved {self.expected_freed_size_str}.") + + +@dataclass(frozen=True) +class HFCacheInfo: + """Frozen data structure holding information about the entire cache-system. + + This data structure is returned by [`scan_cache_dir`] and is immutable. + + Args: + size_on_disk (`int`): + Sum of all valid repo sizes in the cache-system. + repos (`FrozenSet[CachedRepoInfo]`): + Set of [`~CachedRepoInfo`] describing all valid cached repos found on the + cache-system while scanning. + warnings (`List[CorruptedCacheException]`): + List of [`~CorruptedCacheException`] that occurred while scanning the cache. + Those exceptions are captured so that the scan can continue. Corrupted repos + are skipped from the scan. + + + + Here `size_on_disk` is equal to the sum of all repo sizes (only blobs). However if + some cached repos are corrupted, their sizes are not taken into account. + + + """ + + size_on_disk: int + repos: FrozenSet[CachedRepoInfo] + warnings: List[CorruptedCacheException] + + @property + def size_on_disk_str(self) -> str: + """ + (property) Sum of all valid repo sizes in the cache-system as a human-readable + string. + + Example: "42.2K". + """ + return _format_size(self.size_on_disk) + + def delete_revisions(self, *revisions: str) -> DeleteCacheStrategy: + """Prepare the strategy to delete one or more revisions cached locally. + + Input revisions can be any revision hash. If a revision hash is not found in the + local cache, a warning is thrown but no error is raised. Revisions can be from + different cached repos since hashes are unique across repos, + + Examples: + ```py + >>> from huggingface_hub import scan_cache_dir + >>> cache_info = scan_cache_dir() + >>> delete_strategy = cache_info.delete_revisions( + ... "81fd1d6e7847c99f5862c9fb81387956d99ec7aa" + ... ) + >>> print(f"Will free {delete_strategy.expected_freed_size_str}.") + Will free 7.9K. + >>> delete_strategy.execute() + Cache deletion done. Saved 7.9K. + ``` + + ```py + >>> from huggingface_hub import scan_cache_dir + >>> scan_cache_dir().delete_revisions( + ... "81fd1d6e7847c99f5862c9fb81387956d99ec7aa", + ... "e2983b237dccf3ab4937c97fa717319a9ca1a96d", + ... "6c0e6080953db56375760c0471a8c5f2929baf11", + ... ).execute() + Cache deletion done. Saved 8.6G. + ``` + + + + `delete_revisions` returns a [`~utils.DeleteCacheStrategy`] object that needs to + be executed. The [`~utils.DeleteCacheStrategy`] is not meant to be modified but + allows having a dry run before actually executing the deletion. + + + """ + hashes_to_delete: Set[str] = set(revisions) + + repos_with_revisions: Dict[CachedRepoInfo, Set[CachedRevisionInfo]] = defaultdict(set) + + for repo in self.repos: + for revision in repo.revisions: + if revision.commit_hash in hashes_to_delete: + repos_with_revisions[repo].add(revision) + hashes_to_delete.remove(revision.commit_hash) + + if len(hashes_to_delete) > 0: + logger.warning(f"Revision(s) not found - cannot delete them: {', '.join(hashes_to_delete)}") + + delete_strategy_blobs: Set[Path] = set() + delete_strategy_refs: Set[Path] = set() + delete_strategy_repos: Set[Path] = set() + delete_strategy_snapshots: Set[Path] = set() + delete_strategy_expected_freed_size = 0 + + for affected_repo, revisions_to_delete in repos_with_revisions.items(): + other_revisions = affected_repo.revisions - revisions_to_delete + + # If no other revisions, it means all revisions are deleted + # -> delete the entire cached repo + if len(other_revisions) == 0: + delete_strategy_repos.add(affected_repo.repo_path) + delete_strategy_expected_freed_size += affected_repo.size_on_disk + continue + + # Some revisions of the repo will be deleted but not all. We need to filter + # which blob files will not be linked anymore. + for revision_to_delete in revisions_to_delete: + # Snapshot dir + delete_strategy_snapshots.add(revision_to_delete.snapshot_path) + + # Refs dir + for ref in revision_to_delete.refs: + delete_strategy_refs.add(affected_repo.repo_path / "refs" / ref) + + # Blobs dir + for file in revision_to_delete.files: + if file.blob_path not in delete_strategy_blobs: + is_file_alone = True + for revision in other_revisions: + for rev_file in revision.files: + if file.blob_path == rev_file.blob_path: + is_file_alone = False + break + if not is_file_alone: + break + + # Blob file not referenced by remaining revisions -> delete + if is_file_alone: + delete_strategy_blobs.add(file.blob_path) + delete_strategy_expected_freed_size += file.size_on_disk + + # Return the strategy instead of executing it. + return DeleteCacheStrategy( + blobs=frozenset(delete_strategy_blobs), + refs=frozenset(delete_strategy_refs), + repos=frozenset(delete_strategy_repos), + snapshots=frozenset(delete_strategy_snapshots), + expected_freed_size=delete_strategy_expected_freed_size, + ) + + +def scan_cache_dir(cache_dir: Optional[Union[str, Path]] = None) -> HFCacheInfo: + """Scan the entire HF cache-system and return a [`~HFCacheInfo`] structure. + + Use `scan_cache_dir` in order to programmatically scan your cache-system. The cache + will be scanned repo by repo. If a repo is corrupted, a [`~CorruptedCacheException`] + will be thrown internally but captured and returned in the [`~HFCacheInfo`] + structure. Only valid repos get a proper report. + + ```py + >>> from huggingface_hub import scan_cache_dir + + >>> hf_cache_info = scan_cache_dir() + HFCacheInfo( + size_on_disk=3398085269, + repos=frozenset({ + CachedRepoInfo( + repo_id='t5-small', + repo_type='model', + repo_path=PosixPath(...), + size_on_disk=970726914, + nb_files=11, + revisions=frozenset({ + CachedRevisionInfo( + commit_hash='d78aea13fa7ecd06c29e3e46195d6341255065d5', + size_on_disk=970726339, + snapshot_path=PosixPath(...), + files=frozenset({ + CachedFileInfo( + file_name='config.json', + size_on_disk=1197 + file_path=PosixPath(...), + blob_path=PosixPath(...), + ), + CachedFileInfo(...), + ... + }), + ), + CachedRevisionInfo(...), + ... + }), + ), + CachedRepoInfo(...), + ... + }), + warnings=[ + CorruptedCacheException("Snapshots dir doesn't exist in cached repo: ..."), + CorruptedCacheException(...), + ... + ], + ) + ``` + + You can also print a detailed report directly from the `huggingface-cli` using: + ```text + > huggingface-cli scan-cache + REPO ID REPO TYPE SIZE ON DISK NB FILES REFS LOCAL PATH + --------------------------- --------- ------------ -------- ------------------- ------------------------------------------------------------------------- + glue dataset 116.3K 15 1.17.0, main, 2.4.0 /Users/lucain/.cache/huggingface/hub/datasets--glue + google/fleurs dataset 64.9M 6 main, refs/pr/1 /Users/lucain/.cache/huggingface/hub/datasets--google--fleurs + Jean-Baptiste/camembert-ner model 441.0M 7 main /Users/lucain/.cache/huggingface/hub/models--Jean-Baptiste--camembert-ner + bert-base-cased model 1.9G 13 main /Users/lucain/.cache/huggingface/hub/models--bert-base-cased + t5-base model 10.1K 3 main /Users/lucain/.cache/huggingface/hub/models--t5-base + t5-small model 970.7M 11 refs/pr/1, main /Users/lucain/.cache/huggingface/hub/models--t5-small + + Done in 0.0s. Scanned 6 repo(s) for a total of 3.4G. + Got 1 warning(s) while scanning. Use -vvv to print details. + ``` + + Args: + cache_dir (`str` or `Path`, `optional`): + Cache directory to cache. Defaults to the default HF cache directory. + + + + Raises: + + `CacheNotFound` + If the cache directory does not exist. + + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If the cache directory is a file, instead of a directory. + + + + Returns: a [`~HFCacheInfo`] object. + """ + if cache_dir is None: + cache_dir = HF_HUB_CACHE + + cache_dir = Path(cache_dir).expanduser().resolve() + if not cache_dir.exists(): + raise CacheNotFound( + f"Cache directory not found: {cache_dir}. Please use `cache_dir` argument or set `HF_HUB_CACHE` environment variable.", + cache_dir=cache_dir, + ) + + if cache_dir.is_file(): + raise ValueError( + f"Scan cache expects a directory but found a file: {cache_dir}. Please use `cache_dir` argument or set `HF_HUB_CACHE` environment variable." + ) + + repos: Set[CachedRepoInfo] = set() + warnings: List[CorruptedCacheException] = [] + for repo_path in cache_dir.iterdir(): + if repo_path.name == ".locks": # skip './.locks/' folder + continue + try: + repos.add(_scan_cached_repo(repo_path)) + except CorruptedCacheException as e: + warnings.append(e) + + return HFCacheInfo( + repos=frozenset(repos), + size_on_disk=sum(repo.size_on_disk for repo in repos), + warnings=warnings, + ) + + +def _scan_cached_repo(repo_path: Path) -> CachedRepoInfo: + """Scan a single cache repo and return information about it. + + Any unexpected behavior will raise a [`~CorruptedCacheException`]. + """ + if not repo_path.is_dir(): + raise CorruptedCacheException(f"Repo path is not a directory: {repo_path}") + + if "--" not in repo_path.name: + raise CorruptedCacheException(f"Repo path is not a valid HuggingFace cache directory: {repo_path}") + + repo_type, repo_id = repo_path.name.split("--", maxsplit=1) + repo_type = repo_type[:-1] # "models" -> "model" + repo_id = repo_id.replace("--", "/") # google/fleurs -> "google/fleurs" + + if repo_type not in {"dataset", "model", "space"}: + raise CorruptedCacheException( + f"Repo type must be `dataset`, `model` or `space`, found `{repo_type}` ({repo_path})." + ) + + blob_stats: Dict[Path, os.stat_result] = {} # Key is blob_path, value is blob stats + + snapshots_path = repo_path / "snapshots" + refs_path = repo_path / "refs" + + if not snapshots_path.exists() or not snapshots_path.is_dir(): + raise CorruptedCacheException(f"Snapshots dir doesn't exist in cached repo: {snapshots_path}") + + # Scan over `refs` directory + + # key is revision hash, value is set of refs + refs_by_hash: Dict[str, Set[str]] = defaultdict(set) + if refs_path.exists(): + # Example of `refs` directory + # ── refs + # ├── main + # └── refs + # └── pr + # └── 1 + if refs_path.is_file(): + raise CorruptedCacheException(f"Refs directory cannot be a file: {refs_path}") + + for ref_path in refs_path.glob("**/*"): + # glob("**/*") iterates over all files and directories -> skip directories + if ref_path.is_dir(): + continue + + ref_name = str(ref_path.relative_to(refs_path)) + with ref_path.open() as f: + commit_hash = f.read() + + refs_by_hash[commit_hash].add(ref_name) + + # Scan snapshots directory + cached_revisions: Set[CachedRevisionInfo] = set() + for revision_path in snapshots_path.iterdir(): + if revision_path.is_file(): + raise CorruptedCacheException(f"Snapshots folder corrupted. Found a file: {revision_path}") + + cached_files = set() + for file_path in revision_path.glob("**/*"): + # glob("**/*") iterates over all files and directories -> skip directories + if file_path.is_dir(): + continue + + blob_path = Path(file_path).resolve() + if not blob_path.exists(): + raise CorruptedCacheException(f"Blob missing (broken symlink): {blob_path}") + + if blob_path not in blob_stats: + blob_stats[blob_path] = blob_path.stat() + + cached_files.add( + CachedFileInfo( + file_name=file_path.name, + file_path=file_path, + size_on_disk=blob_stats[blob_path].st_size, + blob_path=blob_path, + blob_last_accessed=blob_stats[blob_path].st_atime, + blob_last_modified=blob_stats[blob_path].st_mtime, + ) + ) + + # Last modified is either the last modified blob file or the revision folder + # itself if it is empty + if len(cached_files) > 0: + revision_last_modified = max(blob_stats[file.blob_path].st_mtime for file in cached_files) + else: + revision_last_modified = revision_path.stat().st_mtime + + cached_revisions.add( + CachedRevisionInfo( + commit_hash=revision_path.name, + files=frozenset(cached_files), + refs=frozenset(refs_by_hash.pop(revision_path.name, set())), + size_on_disk=sum( + blob_stats[blob_path].st_size for blob_path in set(file.blob_path for file in cached_files) + ), + snapshot_path=revision_path, + last_modified=revision_last_modified, + ) + ) + + # Check that all refs referred to an existing revision + if len(refs_by_hash) > 0: + raise CorruptedCacheException( + f"Reference(s) refer to missing commit hashes: {dict(refs_by_hash)} ({repo_path})." + ) + + # Last modified is either the last modified blob file or the repo folder itself if + # no blob files has been found. Same for last accessed. + if len(blob_stats) > 0: + repo_last_accessed = max(stat.st_atime for stat in blob_stats.values()) + repo_last_modified = max(stat.st_mtime for stat in blob_stats.values()) + else: + repo_stats = repo_path.stat() + repo_last_accessed = repo_stats.st_atime + repo_last_modified = repo_stats.st_mtime + + # Build and return frozen structure + return CachedRepoInfo( + nb_files=len(blob_stats), + repo_id=repo_id, + repo_path=repo_path, + repo_type=repo_type, # type: ignore + revisions=frozenset(cached_revisions), + size_on_disk=sum(stat.st_size for stat in blob_stats.values()), + last_accessed=repo_last_accessed, + last_modified=repo_last_modified, + ) + + +def _format_size(num: int) -> str: + """Format size in bytes into a human-readable string. + + Taken from https://stackoverflow.com/a/1094933 + """ + num_f = float(num) + for unit in ["", "K", "M", "G", "T", "P", "E", "Z"]: + if abs(num_f) < 1000.0: + return f"{num_f:3.1f}{unit}" + num_f /= 1000.0 + return f"{num_f:.1f}Y" + + +_TIMESINCE_CHUNKS = ( + # Label, divider, max value + ("second", 1, 60), + ("minute", 60, 60), + ("hour", 60 * 60, 24), + ("day", 60 * 60 * 24, 6), + ("week", 60 * 60 * 24 * 7, 6), + ("month", 60 * 60 * 24 * 30, 11), + ("year", 60 * 60 * 24 * 365, None), +) + + +def _format_timesince(ts: float) -> str: + """Format timestamp in seconds into a human-readable string, relative to now. + + Vaguely inspired by Django's `timesince` formatter. + """ + delta = time.time() - ts + if delta < 20: + return "a few seconds ago" + for label, divider, max_value in _TIMESINCE_CHUNKS: # noqa: B007 + value = round(delta / divider) + if max_value is not None and value <= max_value: + break + return f"{value} {label}{'s' if value > 1 else ''} ago" + + +def _try_delete_path(path: Path, path_type: str) -> None: + """Try to delete a local file or folder. + + If the path does not exists, error is logged as a warning and then ignored. + + Args: + path (`Path`) + Path to delete. Can be a file or a folder. + path_type (`str`) + What path are we deleting ? Only for logging purposes. Example: "snapshot". + """ + logger.info(f"Delete {path_type}: {path}") + try: + if path.is_file(): + os.remove(path) + else: + shutil.rmtree(path) + except FileNotFoundError: + logger.warning(f"Couldn't delete {path_type}: file not found ({path})", exc_info=True) + except PermissionError: + logger.warning(f"Couldn't delete {path_type}: permission denied ({path})", exc_info=True) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_chunk_utils.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_chunk_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..5ff0b8125ece381b1270754669ae8e708c370f61 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_chunk_utils.py @@ -0,0 +1,64 @@ +# coding=utf-8 +# Copyright 2022-present, the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Contains a utility to iterate by chunks over an iterator.""" +import itertools +from typing import Iterable, TypeVar + + +T = TypeVar("T") + + +def chunk_iterable(iterable: Iterable[T], chunk_size: int) -> Iterable[Iterable[T]]: + """Iterates over an iterator chunk by chunk. + + Taken from https://stackoverflow.com/a/8998040. + See also https://github.com/huggingface/huggingface_hub/pull/920#discussion_r938793088. + + Args: + iterable (`Iterable`): + The iterable on which we want to iterate. + chunk_size (`int`): + Size of the chunks. Must be a strictly positive integer (e.g. >0). + + Example: + + ```python + >>> from huggingface_hub.utils import chunk_iterable + + >>> for items in chunk_iterable(range(17), chunk_size=8): + ... print(items) + # [0, 1, 2, 3, 4, 5, 6, 7] + # [8, 9, 10, 11, 12, 13, 14, 15] + # [16] # smaller last chunk + ``` + + Raises: + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If `chunk_size` <= 0. + + + The last chunk can be smaller than `chunk_size`. + + """ + if not isinstance(chunk_size, int) or chunk_size <= 0: + raise ValueError("`chunk_size` must be a strictly positive integer (>0).") + + iterator = iter(iterable) + while True: + try: + next_item = next(iterator) + except StopIteration: + return + yield itertools.chain((next_item,), itertools.islice(iterator, chunk_size - 1)) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_datetime.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_datetime.py new file mode 100644 index 0000000000000000000000000000000000000000..716f373e2eef30ac312c4fa9d2acb1fd4614f4c5 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_datetime.py @@ -0,0 +1,68 @@ +# coding=utf-8 +# Copyright 2022-present, the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Contains utilities to handle datetimes in Huggingface Hub.""" +from datetime import datetime, timedelta, timezone + + +# Local machine offset compared to UTC. +# Taken from https://stackoverflow.com/a/3168394. +# `utcoffset()` returns `None` if no offset -> empty timedelta. +UTC_OFFSET = datetime.now(timezone.utc).astimezone().utcoffset() or timedelta() + + +def parse_datetime(date_string: str) -> datetime: + """ + Parses a date_string returned from the server to a datetime object. + + This parser is a weak-parser is the sense that it handles only a single format of + date_string. It is expected that the server format will never change. The + implementation depends only on the standard lib to avoid an external dependency + (python-dateutil). See full discussion about this decision on PR: + https://github.com/huggingface/huggingface_hub/pull/999. + + Example: + ```py + > parse_datetime('2022-08-19T07:19:38.123Z') + datetime.datetime(2022, 8, 19, 7, 19, 38, 123000, tzinfo=timezone.utc) + ``` + + Args: + date_string (`str`): + A string representing a datetime returned by the Hub server. + String is expected to follow '%Y-%m-%dT%H:%M:%S.%fZ' pattern. + + Returns: + A python datetime object. + + Raises: + :class:`ValueError`: + If `date_string` cannot be parsed. + """ + try: + # Datetime ending with a Z means "UTC". Here we parse the date as local machine + # timezone and then move it to the appropriate UTC timezone. + # See https://en.wikipedia.org/wiki/ISO_8601#Coordinated_Universal_Time_(UTC) + # Taken from https://stackoverflow.com/a/3168394. + if len(date_string) == 30: + # Means timezoned-timestamp with nanoseconds precision. We need to truncate the last 3 digits. + date_string = date_string[:-4] + "Z" + dt = datetime.strptime(date_string, "%Y-%m-%dT%H:%M:%S.%fZ") + dt += UTC_OFFSET # By default, datetime is not timezoned -> move to UTC time + return dt.astimezone(timezone.utc) # Set explicit timezone + except ValueError as e: + raise ValueError( + f"Cannot parse '{date_string}' as a datetime. Date string is expected to" + " follow '%Y-%m-%dT%H:%M:%S.%fZ' pattern." + ) from e diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_deprecation.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_deprecation.py new file mode 100644 index 0000000000000000000000000000000000000000..4cb8d6e418c76accd1ecd61158b4bdd265e12f71 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_deprecation.py @@ -0,0 +1,136 @@ +import warnings +from functools import wraps +from inspect import Parameter, signature +from typing import Iterable, Optional + + +def _deprecate_positional_args(*, version: str): + """Decorator for methods that issues warnings for positional arguments. + Using the keyword-only argument syntax in pep 3102, arguments after the + * will issue a warning when passed as a positional argument. + + Args: + version (`str`): + The version when positional arguments will result in error. + """ + + def _inner_deprecate_positional_args(f): + sig = signature(f) + kwonly_args = [] + all_args = [] + for name, param in sig.parameters.items(): + if param.kind == Parameter.POSITIONAL_OR_KEYWORD: + all_args.append(name) + elif param.kind == Parameter.KEYWORD_ONLY: + kwonly_args.append(name) + + @wraps(f) + def inner_f(*args, **kwargs): + extra_args = len(args) - len(all_args) + if extra_args <= 0: + return f(*args, **kwargs) + # extra_args > 0 + args_msg = [ + f"{name}='{arg}'" if isinstance(arg, str) else f"{name}={arg}" + for name, arg in zip(kwonly_args[:extra_args], args[-extra_args:]) + ] + args_msg = ", ".join(args_msg) + warnings.warn( + f"Deprecated positional argument(s) used in '{f.__name__}': pass" + f" {args_msg} as keyword args. From version {version} passing these" + " as positional arguments will result in an error,", + FutureWarning, + ) + kwargs.update(zip(sig.parameters, args)) + return f(**kwargs) + + return inner_f + + return _inner_deprecate_positional_args + + +def _deprecate_arguments( + *, + version: str, + deprecated_args: Iterable[str], + custom_message: Optional[str] = None, +): + """Decorator to issue warnings when using deprecated arguments. + + TODO: could be useful to be able to set a custom error message. + + Args: + version (`str`): + The version when deprecated arguments will result in error. + deprecated_args (`List[str]`): + List of the arguments to be deprecated. + custom_message (`str`, *optional*): + Warning message that is raised. If not passed, a default warning message + will be created. + """ + + def _inner_deprecate_positional_args(f): + sig = signature(f) + + @wraps(f) + def inner_f(*args, **kwargs): + # Check for used deprecated arguments + used_deprecated_args = [] + for _, parameter in zip(args, sig.parameters.values()): + if parameter.name in deprecated_args: + used_deprecated_args.append(parameter.name) + for kwarg_name, kwarg_value in kwargs.items(): + if ( + # If argument is deprecated but still used + kwarg_name in deprecated_args + # And then the value is not the default value + and kwarg_value != sig.parameters[kwarg_name].default + ): + used_deprecated_args.append(kwarg_name) + + # Warn and proceed + if len(used_deprecated_args) > 0: + message = ( + f"Deprecated argument(s) used in '{f.__name__}':" + f" {', '.join(used_deprecated_args)}. Will not be supported from" + f" version '{version}'." + ) + if custom_message is not None: + message += "\n\n" + custom_message + warnings.warn(message, FutureWarning) + return f(*args, **kwargs) + + return inner_f + + return _inner_deprecate_positional_args + + +def _deprecate_method(*, version: str, message: Optional[str] = None): + """Decorator to issue warnings when using a deprecated method. + + Args: + version (`str`): + The version when deprecated arguments will result in error. + message (`str`, *optional*): + Warning message that is raised. If not passed, a default warning message + will be created. + """ + + def _inner_deprecate_method(f): + name = f.__name__ + if name == "__init__": + name = f.__qualname__.split(".")[0] # class name instead of method name + + @wraps(f) + def inner_f(*args, **kwargs): + warning_message = ( + f"'{name}' (from '{f.__module__}') is deprecated and will be removed from version '{version}'." + ) + if message is not None: + warning_message += " " + message + warnings.warn(warning_message, FutureWarning) + return f(*args, **kwargs) + + return inner_f + + return _inner_deprecate_method diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_errors.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_errors.py new file mode 100644 index 0000000000000000000000000000000000000000..37bddf331dddd4a8b5a825028f505f3685e2d6a1 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_errors.py @@ -0,0 +1,359 @@ +import re +from typing import Optional + +from requests import HTTPError, Response + +from ._fixes import JSONDecodeError + + +REPO_API_REGEX = re.compile( + r""" + # staging or production endpoint + ^https://(hub-ci.)?huggingface.co + ( + # on /api/repo_type/repo_id + /api/(models|datasets|spaces)/(.+) + | + # or /repo_id/resolve/revision/... + /(.+)/resolve/(.+) + ) + """, + flags=re.VERBOSE, +) + + +class FileMetadataError(OSError): + """Error triggered when the metadata of a file on the Hub cannot be retrieved (missing ETag or commit_hash). + + Inherits from `OSError` for backward compatibility. + """ + + +class HfHubHTTPError(HTTPError): + """ + HTTPError to inherit from for any custom HTTP Error raised in HF Hub. + + Any HTTPError is converted at least into a `HfHubHTTPError`. If some information is + sent back by the server, it will be added to the error message. + + Added details: + - Request id from "X-Request-Id" header if exists. + - Server error message from the header "X-Error-Message". + - Server error message if we can found one in the response body. + + Example: + ```py + import requests + from huggingface_hub.utils import get_session, hf_raise_for_status, HfHubHTTPError + + response = get_session().post(...) + try: + hf_raise_for_status(response) + except HfHubHTTPError as e: + print(str(e)) # formatted message + e.request_id, e.server_message # details returned by server + + # Complete the error message with additional information once it's raised + e.append_to_message("\n`create_commit` expects the repository to exist.") + raise + ``` + """ + + request_id: Optional[str] = None + server_message: Optional[str] = None + + def __init__(self, message: str, response: Optional[Response] = None): + # Parse server information if any. + if response is not None: + self.request_id = response.headers.get("X-Request-Id") + try: + server_data = response.json() + except JSONDecodeError: + server_data = {} + + # Retrieve server error message from multiple sources + server_message_from_headers = response.headers.get("X-Error-Message") + server_message_from_body = server_data.get("error") + server_multiple_messages_from_body = "\n".join( + error["message"] for error in server_data.get("errors", []) if "message" in error + ) + + # Concatenate error messages + _server_message = "" + if server_message_from_headers is not None: # from headers + _server_message += server_message_from_headers + "\n" + if server_message_from_body is not None: # from body "error" + if isinstance(server_message_from_body, list): + server_message_from_body = "\n".join(server_message_from_body) + if server_message_from_body not in _server_message: + _server_message += server_message_from_body + "\n" + if server_multiple_messages_from_body is not None: # from body "errors" + if server_multiple_messages_from_body not in _server_message: + _server_message += server_multiple_messages_from_body + "\n" + _server_message = _server_message.strip() + + # Set message to `HfHubHTTPError` (if any) + if _server_message != "": + self.server_message = _server_message + + super().__init__( + _format_error_message( + message, + request_id=self.request_id, + server_message=self.server_message, + ), + response=response, # type: ignore + request=response.request if response is not None else None, # type: ignore + ) + + def append_to_message(self, additional_message: str) -> None: + """Append additional information to the `HfHubHTTPError` initial message.""" + self.args = (self.args[0] + additional_message,) + self.args[1:] + + +class RepositoryNotFoundError(HfHubHTTPError): + """ + Raised when trying to access a hf.co URL with an invalid repository name, or + with a private repo name the user does not have access to. + + Example: + + ```py + >>> from huggingface_hub import model_info + >>> model_info("") + (...) + huggingface_hub.utils._errors.RepositoryNotFoundError: 401 Client Error. (Request ID: PvMw_VjBMjVdMz53WKIzP) + + Repository Not Found for url: https://huggingface.co/api/models/%3Cnon_existent_repository%3E. + Please make sure you specified the correct `repo_id` and `repo_type`. + If the repo is private, make sure you are authenticated. + Invalid username or password. + ``` + """ + + +class GatedRepoError(RepositoryNotFoundError): + """ + Raised when trying to access a gated repository for which the user is not on the + authorized list. + + Note: derives from `RepositoryNotFoundError` to ensure backward compatibility. + + Example: + + ```py + >>> from huggingface_hub import model_info + >>> model_info("") + (...) + huggingface_hub.utils._errors.GatedRepoError: 403 Client Error. (Request ID: ViT1Bf7O_026LGSQuVqfa) + + Cannot access gated repo for url https://huggingface.co/api/models/ardent-figment/gated-model. + Access to model ardent-figment/gated-model is restricted and you are not in the authorized list. + Visit https://huggingface.co/ardent-figment/gated-model to ask for access. + ``` + """ + + +class RevisionNotFoundError(HfHubHTTPError): + """ + Raised when trying to access a hf.co URL with a valid repository but an invalid + revision. + + Example: + + ```py + >>> from huggingface_hub import hf_hub_download + >>> hf_hub_download('bert-base-cased', 'config.json', revision='') + (...) + huggingface_hub.utils._errors.RevisionNotFoundError: 404 Client Error. (Request ID: Mwhe_c3Kt650GcdKEFomX) + + Revision Not Found for url: https://huggingface.co/bert-base-cased/resolve/%3Cnon-existent-revision%3E/config.json. + ``` + """ + + +class EntryNotFoundError(HfHubHTTPError): + """ + Raised when trying to access a hf.co URL with a valid repository and revision + but an invalid filename. + + Example: + + ```py + >>> from huggingface_hub import hf_hub_download + >>> hf_hub_download('bert-base-cased', '') + (...) + huggingface_hub.utils._errors.EntryNotFoundError: 404 Client Error. (Request ID: 53pNl6M0MxsnG5Sw8JA6x) + + Entry Not Found for url: https://huggingface.co/bert-base-cased/resolve/main/%3Cnon-existent-file%3E. + ``` + """ + + +class LocalEntryNotFoundError(EntryNotFoundError, FileNotFoundError, ValueError): + """ + Raised when trying to access a file or snapshot that is not on the disk when network is + disabled or unavailable (connection issue). The entry may exist on the Hub. + + Note: `ValueError` type is to ensure backward compatibility. + Note: `LocalEntryNotFoundError` derives from `HTTPError` because of `EntryNotFoundError` + even when it is not a network issue. + + Example: + + ```py + >>> from huggingface_hub import hf_hub_download + >>> hf_hub_download('bert-base-cased', '', local_files_only=True) + (...) + huggingface_hub.utils._errors.LocalEntryNotFoundError: Cannot find the requested files in the disk cache and outgoing traffic has been disabled. To enable hf.co look-ups and downloads online, set 'local_files_only' to False. + ``` + """ + + def __init__(self, message: str): + super().__init__(message, response=None) + + +class BadRequestError(HfHubHTTPError, ValueError): + """ + Raised by `hf_raise_for_status` when the server returns a HTTP 400 error. + + Example: + + ```py + >>> resp = requests.post("hf.co/api/check", ...) + >>> hf_raise_for_status(resp, endpoint_name="check") + huggingface_hub.utils._errors.BadRequestError: Bad request for check endpoint: {details} (Request ID: XXX) + ``` + """ + + +def hf_raise_for_status(response: Response, endpoint_name: Optional[str] = None) -> None: + """ + Internal version of `response.raise_for_status()` that will refine a + potential HTTPError. Raised exception will be an instance of `HfHubHTTPError`. + + This helper is meant to be the unique method to raise_for_status when making a call + to the Hugging Face Hub. + + Example: + ```py + import requests + from huggingface_hub.utils import get_session, hf_raise_for_status, HfHubHTTPError + + response = get_session().post(...) + try: + hf_raise_for_status(response) + except HfHubHTTPError as e: + print(str(e)) # formatted message + e.request_id, e.server_message # details returned by server + + # Complete the error message with additional information once it's raised + e.append_to_message("\n`create_commit` expects the repository to exist.") + raise + ``` + + Args: + response (`Response`): + Response from the server. + endpoint_name (`str`, *optional*): + Name of the endpoint that has been called. If provided, the error message + will be more complete. + + + + Raises when the request has failed: + + - [`~utils.RepositoryNotFoundError`] + If the repository to download from cannot be found. This may be because it + doesn't exist, because `repo_type` is not set correctly, or because the repo + is `private` and you do not have access. + - [`~utils.GatedRepoError`] + If the repository exists but is gated and the user is not on the authorized + list. + - [`~utils.RevisionNotFoundError`] + If the repository exists but the revision couldn't be find. + - [`~utils.EntryNotFoundError`] + If the repository exists but the entry (e.g. the requested file) couldn't be + find. + - [`~utils.BadRequestError`] + If request failed with a HTTP 400 BadRequest error. + - [`~utils.HfHubHTTPError`] + If request failed for a reason not listed above. + + + """ + try: + response.raise_for_status() + except HTTPError as e: + error_code = response.headers.get("X-Error-Code") + + if error_code == "RevisionNotFound": + message = f"{response.status_code} Client Error." + "\n\n" + f"Revision Not Found for url: {response.url}." + raise RevisionNotFoundError(message, response) from e + + elif error_code == "EntryNotFound": + message = f"{response.status_code} Client Error." + "\n\n" + f"Entry Not Found for url: {response.url}." + raise EntryNotFoundError(message, response) from e + + elif error_code == "GatedRepo": + message = ( + f"{response.status_code} Client Error." + "\n\n" + f"Cannot access gated repo for url {response.url}." + ) + raise GatedRepoError(message, response) from e + + elif error_code == "RepoNotFound" or ( + response.status_code == 401 + and response.request is not None + and response.request.url is not None + and REPO_API_REGEX.search(response.request.url) is not None + ): + # 401 is misleading as it is returned for: + # - private and gated repos if user is not authenticated + # - missing repos + # => for now, we process them as `RepoNotFound` anyway. + # See https://gist.github.com/Wauplin/46c27ad266b15998ce56a6603796f0b9 + message = ( + f"{response.status_code} Client Error." + + "\n\n" + + f"Repository Not Found for url: {response.url}." + + "\nPlease make sure you specified the correct `repo_id` and" + " `repo_type`.\nIf you are trying to access a private or gated repo," + " make sure you are authenticated." + ) + raise RepositoryNotFoundError(message, response) from e + + elif response.status_code == 400: + message = ( + f"\n\nBad request for {endpoint_name} endpoint:" if endpoint_name is not None else "\n\nBad request:" + ) + raise BadRequestError(message, response=response) from e + + # Convert `HTTPError` into a `HfHubHTTPError` to display request information + # as well (request id and/or server error message) + raise HfHubHTTPError(str(e), response=response) from e + + +def _format_error_message(message: str, request_id: Optional[str], server_message: Optional[str]) -> str: + """ + Format the `HfHubHTTPError` error message based on initial message and information + returned by the server. + + Used when initializing `HfHubHTTPError`. + """ + # Add message from response body + if server_message is not None and len(server_message) > 0 and server_message.lower() not in message.lower(): + if "\n\n" in message: + message += "\n" + server_message + else: + message += "\n\n" + server_message + + # Add Request ID + if request_id is not None and str(request_id).lower() not in message.lower(): + request_id_message = f" (Request ID: {request_id})" + if "\n" in message: + newline_index = message.index("\n") + message = message[:newline_index] + request_id_message + message[newline_index:] + else: + message += request_id_message + + return message diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_experimental.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_experimental.py new file mode 100644 index 0000000000000000000000000000000000000000..34162d22aca71b8a0d2513bc08e9e0a5325109c0 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_experimental.py @@ -0,0 +1,65 @@ +# coding=utf-8 +# Copyright 2023-present, the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Contains utilities to flag a feature as "experimental" in Huggingface Hub.""" +import warnings +from functools import wraps +from typing import Callable + +from .. import constants + + +def experimental(fn: Callable) -> Callable: + """Decorator to flag a feature as experimental. + + An experimental feature trigger a warning when used as it might be subject to breaking changes in the future. + Warnings can be disabled by setting the environment variable `HF_EXPERIMENTAL_WARNING` to `0`. + + Args: + fn (`Callable`): + The function to flag as experimental. + + Returns: + `Callable`: The decorated function. + + Example: + + ```python + >>> from huggingface_hub.utils import experimental + + >>> @experimental + ... def my_function(): + ... print("Hello world!") + + >>> my_function() + UserWarning: 'my_function' is experimental and might be subject to breaking changes in the future. You can disable + this warning by setting `HF_HUB_DISABLE_EXPERIMENTAL_WARNING=1` as environment variable. + Hello world! + ``` + """ + # For classes, put the "experimental" around the "__new__" method => __new__ will be removed in warning message + name = fn.__qualname__[: -len(".__new__")] if fn.__qualname__.endswith(".__new__") else fn.__qualname__ + + @wraps(fn) + def _inner_fn(*args, **kwargs): + if not constants.HF_HUB_DISABLE_EXPERIMENTAL_WARNING: + warnings.warn( + f"'{name}' is experimental and might be subject to breaking changes in the future." + " You can disable this warning by setting `HF_HUB_DISABLE_EXPERIMENTAL_WARNING=1` as environment" + " variable.", + UserWarning, + ) + return fn(*args, **kwargs) + + return _inner_fn diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_fixes.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_fixes.py new file mode 100644 index 0000000000000000000000000000000000000000..ff4f9e2d70e323e108fbd7bade2fbed3f5595cbe --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_fixes.py @@ -0,0 +1,77 @@ +# JSONDecodeError was introduced in requests=2.27 released in 2022. +# This allows us to support older requests for users +# More information: https://github.com/psf/requests/pull/5856 +try: + from requests import JSONDecodeError # type: ignore # noqa: F401 +except ImportError: + try: + from simplejson import JSONDecodeError # type: ignore # noqa: F401 + except ImportError: + from json import JSONDecodeError # type: ignore # noqa: F401 + +import contextlib +import os +import shutil +import stat +import tempfile +from functools import partial +from pathlib import Path +from typing import Callable, Generator, Optional, Union + +import yaml + + +# Wrap `yaml.dump` to set `allow_unicode=True` by default. +# +# Example: +# ```py +# >>> yaml.dump({"emoji": "👀", "some unicode": "日本か"}) +# 'emoji: "\\U0001F440"\nsome unicode: "\\u65E5\\u672C\\u304B"\n' +# +# >>> yaml_dump({"emoji": "👀", "some unicode": "日本か"}) +# 'emoji: "👀"\nsome unicode: "日本か"\n' +# ``` +yaml_dump: Callable[..., str] = partial(yaml.dump, stream=None, allow_unicode=True) # type: ignore + + +@contextlib.contextmanager +def SoftTemporaryDirectory( + suffix: Optional[str] = None, + prefix: Optional[str] = None, + dir: Optional[Union[Path, str]] = None, + **kwargs, +) -> Generator[str, None, None]: + """ + Context manager to create a temporary directory and safely delete it. + + If tmp directory cannot be deleted normally, we set the WRITE permission and retry. + If cleanup still fails, we give up but don't raise an exception. This is equivalent + to `tempfile.TemporaryDirectory(..., ignore_cleanup_errors=True)` introduced in + Python 3.10. + + See https://www.scivision.dev/python-tempfile-permission-error-windows/. + """ + tmpdir = tempfile.TemporaryDirectory(prefix=prefix, suffix=suffix, dir=dir, **kwargs) + yield tmpdir.name + + try: + # First once with normal cleanup + shutil.rmtree(tmpdir.name) + except Exception: + # If failed, try to set write permission and retry + try: + shutil.rmtree(tmpdir.name, onerror=_set_write_permission_and_retry) + except Exception: + pass + + # And finally, cleanup the tmpdir. + # If it fails again, give up but do not throw error + try: + tmpdir.cleanup() + except Exception: + pass + + +def _set_write_permission_and_retry(func, path, excinfo): + os.chmod(path, stat.S_IWRITE) + func(path) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_git_credential.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_git_credential.py new file mode 100644 index 0000000000000000000000000000000000000000..7f078365d08387cc4c6c4459488045869fb0db73 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_git_credential.py @@ -0,0 +1,120 @@ +# coding=utf-8 +# Copyright 2022-present, the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Contains utilities to manage Git credentials.""" +import re +import subprocess +from typing import List, Optional + +from ..constants import ENDPOINT +from ._subprocess import run_interactive_subprocess, run_subprocess + + +GIT_CREDENTIAL_REGEX = re.compile( + r""" + ^\s* # start of line + credential\.helper # credential.helper value + \s*=\s* # separator + (\w+) # the helper name (group 1) + (\s|$) # whitespace or end of line + """, + flags=re.MULTILINE | re.IGNORECASE | re.VERBOSE, +) + + +def list_credential_helpers(folder: Optional[str] = None) -> List[str]: + """Return the list of git credential helpers configured. + + See https://git-scm.com/docs/gitcredentials. + + Credentials are saved in all configured helpers (store, cache, macOS keychain,...). + Calls "`git credential approve`" internally. See https://git-scm.com/docs/git-credential. + + Args: + folder (`str`, *optional*): + The folder in which to check the configured helpers. + """ + try: + output = run_subprocess("git config --list", folder=folder).stdout + parsed = _parse_credential_output(output) + return parsed + except subprocess.CalledProcessError as exc: + raise EnvironmentError(exc.stderr) + + +def set_git_credential(token: str, username: str = "hf_user", folder: Optional[str] = None) -> None: + """Save a username/token pair in git credential for HF Hub registry. + + Credentials are saved in all configured helpers (store, cache, macOS keychain,...). + Calls "`git credential approve`" internally. See https://git-scm.com/docs/git-credential. + + Args: + username (`str`, defaults to `"hf_user"`): + A git username. Defaults to `"hf_user"`, the default user used in the Hub. + token (`str`, defaults to `"hf_user"`): + A git password. In practice, the User Access Token for the Hub. + See https://huggingface.co/settings/tokens. + folder (`str`, *optional*): + The folder in which to check the configured helpers. + """ + with run_interactive_subprocess("git credential approve", folder=folder) as ( + stdin, + _, + ): + stdin.write(f"url={ENDPOINT}\nusername={username.lower()}\npassword={token}\n\n") + stdin.flush() + + +def unset_git_credential(username: str = "hf_user", folder: Optional[str] = None) -> None: + """Erase credentials from git credential for HF Hub registry. + + Credentials are erased from the configured helpers (store, cache, macOS + keychain,...), if any. If `username` is not provided, any credential configured for + HF Hub endpoint is erased. + Calls "`git credential erase`" internally. See https://git-scm.com/docs/git-credential. + + Args: + username (`str`, defaults to `"hf_user"`): + A git username. Defaults to `"hf_user"`, the default user used in the Hub. + folder (`str`, *optional*): + The folder in which to check the configured helpers. + """ + with run_interactive_subprocess("git credential reject", folder=folder) as ( + stdin, + _, + ): + standard_input = f"url={ENDPOINT}\n" + if username is not None: + standard_input += f"username={username.lower()}\n" + standard_input += "\n" + + stdin.write(standard_input) + stdin.flush() + + +def _parse_credential_output(output: str) -> List[str]: + """Parse the output of `git credential fill` to extract the password. + + Args: + output (`str`): + The output of `git credential fill`. + """ + # NOTE: If user has set an helper for a custom URL, it will not we caught here. + # Example: `credential.https://huggingface.co.helper=store` + # See: https://github.com/huggingface/huggingface_hub/pull/1138#discussion_r1013324508 + return sorted( # Sort for nice printing + set( # Might have some duplicates + match[0] for match in GIT_CREDENTIAL_REGEX.findall(output) + ) + ) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_headers.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_headers.py new file mode 100644 index 0000000000000000000000000000000000000000..ea5123d20d2e262d6aafd6d929886e442f45db6e --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_headers.py @@ -0,0 +1,234 @@ +# coding=utf-8 +# Copyright 2022-present, the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Contains utilities to handle headers to send in calls to Huggingface Hub.""" +from typing import Dict, Optional, Union + +from .. import constants +from ._runtime import ( + get_fastai_version, + get_fastcore_version, + get_hf_hub_version, + get_python_version, + get_tf_version, + get_torch_version, + is_fastai_available, + is_fastcore_available, + is_tf_available, + is_torch_available, +) +from ._token import get_token +from ._validators import validate_hf_hub_args + + +class LocalTokenNotFoundError(EnvironmentError): + """Raised if local token is required but not found.""" + + +@validate_hf_hub_args +def build_hf_headers( + *, + token: Optional[Union[bool, str]] = None, + is_write_action: bool = False, + library_name: Optional[str] = None, + library_version: Optional[str] = None, + user_agent: Union[Dict, str, None] = None, +) -> Dict[str, str]: + """ + Build headers dictionary to send in a HF Hub call. + + By default, authorization token is always provided either from argument (explicit + use) or retrieved from the cache (implicit use). To explicitly avoid sending the + token to the Hub, set `token=False` or set the `HF_HUB_DISABLE_IMPLICIT_TOKEN` + environment variable. + + In case of an API call that requires write access, an error is thrown if token is + `None` or token is an organization token (starting with `"api_org***"`). + + In addition to the auth header, a user-agent is added to provide information about + the installed packages (versions of python, huggingface_hub, torch, tensorflow, + fastai and fastcore). + + Args: + token (`str`, `bool`, *optional*): + The token to be sent in authorization header for the Hub call: + - if a string, it is used as the Hugging Face token + - if `True`, the token is read from the machine (cache or env variable) + - if `False`, authorization header is not set + - if `None`, the token is read from the machine only except if + `HF_HUB_DISABLE_IMPLICIT_TOKEN` env variable is set. + is_write_action (`bool`, default to `False`): + Set to True if the API call requires a write access. If `True`, the token + will be validated (cannot be `None`, cannot start by `"api_org***"`). + library_name (`str`, *optional*): + The name of the library that is making the HTTP request. Will be added to + the user-agent header. + library_version (`str`, *optional*): + The version of the library that is making the HTTP request. Will be added + to the user-agent header. + user_agent (`str`, `dict`, *optional*): + The user agent info in the form of a dictionary or a single string. It will + be completed with information about the installed packages. + + Returns: + A `Dict` of headers to pass in your API call. + + Example: + ```py + >>> build_hf_headers(token="hf_***") # explicit token + {"authorization": "Bearer hf_***", "user-agent": ""} + + >>> build_hf_headers(token=True) # explicitly use cached token + {"authorization": "Bearer hf_***",...} + + >>> build_hf_headers(token=False) # explicitly don't use cached token + {"user-agent": ...} + + >>> build_hf_headers() # implicit use of the cached token + {"authorization": "Bearer hf_***",...} + + # HF_HUB_DISABLE_IMPLICIT_TOKEN=True # to set as env variable + >>> build_hf_headers() # token is not sent + {"user-agent": ...} + + >>> build_hf_headers(token="api_org_***", is_write_action=True) + ValueError: You must use your personal account token for write-access methods. + + >>> build_hf_headers(library_name="transformers", library_version="1.2.3") + {"authorization": ..., "user-agent": "transformers/1.2.3; hf_hub/0.10.2; python/3.10.4; tensorflow/1.55"} + ``` + + Raises: + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If organization token is passed and "write" access is required. + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If "write" access is required but token is not passed and not saved locally. + [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError) + If `token=True` but token is not saved locally. + """ + # Get auth token to send + token_to_send = get_token_to_send(token) + _validate_token_to_send(token_to_send, is_write_action=is_write_action) + + # Combine headers + headers = { + "user-agent": _http_user_agent( + library_name=library_name, + library_version=library_version, + user_agent=user_agent, + ) + } + if token_to_send is not None: + headers["authorization"] = f"Bearer {token_to_send}" + return headers + + +def get_token_to_send(token: Optional[Union[bool, str]]) -> Optional[str]: + """Select the token to send from either `token` or the cache.""" + # Case token is explicitly provided + if isinstance(token, str): + return token + + # Case token is explicitly forbidden + if token is False: + return None + + # Token is not provided: we get it from local cache + cached_token = get_token() + + # Case token is explicitly required + if token is True: + if cached_token is None: + raise LocalTokenNotFoundError( + "Token is required (`token=True`), but no token found. You" + " need to provide a token or be logged in to Hugging Face with" + " `huggingface-cli login` or `huggingface_hub.login`. See" + " https://huggingface.co/settings/tokens." + ) + return cached_token + + # Case implicit use of the token is forbidden by env variable + if constants.HF_HUB_DISABLE_IMPLICIT_TOKEN: + return None + + # Otherwise: we use the cached token as the user has not explicitly forbidden it + return cached_token + + +def _validate_token_to_send(token: Optional[str], is_write_action: bool) -> None: + if is_write_action: + if token is None: + raise ValueError( + "Token is required (write-access action) but no token found. You need" + " to provide a token or be logged in to Hugging Face with" + " `huggingface-cli login` or `huggingface_hub.login`. See" + " https://huggingface.co/settings/tokens." + ) + if token.startswith("api_org"): + raise ValueError( + "You must use your personal account token for write-access methods. To" + " generate a write-access token, go to" + " https://huggingface.co/settings/tokens" + ) + + +def _http_user_agent( + *, + library_name: Optional[str] = None, + library_version: Optional[str] = None, + user_agent: Union[Dict, str, None] = None, +) -> str: + """Format a user-agent string containing information about the installed packages. + + Args: + library_name (`str`, *optional*): + The name of the library that is making the HTTP request. + library_version (`str`, *optional*): + The version of the library that is making the HTTP request. + user_agent (`str`, `dict`, *optional*): + The user agent info in the form of a dictionary or a single string. + + Returns: + The formatted user-agent string. + """ + if library_name is not None: + ua = f"{library_name}/{library_version}" + else: + ua = "unknown/None" + ua += f"; hf_hub/{get_hf_hub_version()}" + ua += f"; python/{get_python_version()}" + + if not constants.HF_HUB_DISABLE_TELEMETRY: + if is_torch_available(): + ua += f"; torch/{get_torch_version()}" + if is_tf_available(): + ua += f"; tensorflow/{get_tf_version()}" + if is_fastai_available(): + ua += f"; fastai/{get_fastai_version()}" + if is_fastcore_available(): + ua += f"; fastcore/{get_fastcore_version()}" + + if isinstance(user_agent, dict): + ua += "; " + "; ".join(f"{k}/{v}" for k, v in user_agent.items()) + elif isinstance(user_agent, str): + ua += "; " + user_agent + + return _deduplicate_user_agent(ua) + + +def _deduplicate_user_agent(user_agent: str) -> str: + """Deduplicate redundant information in the generated user-agent.""" + # Split around ";" > Strip whitespaces > Store as dict keys (ensure unicity) > format back as string + # Order is implicitly preserved by dictionary structure (see https://stackoverflow.com/a/53657523). + return "; ".join({key.strip(): None for key in user_agent.split(";")}.keys()) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_hf_folder.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_hf_folder.py new file mode 100644 index 0000000000000000000000000000000000000000..eb091ee9545fae83ac01efe14f88f9ba5dec150d --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_hf_folder.py @@ -0,0 +1,114 @@ +# coding=utf-8 +# Copyright 2022-present, the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Contain helper class to retrieve/store token from/to local cache.""" +import os +import warnings +from pathlib import Path +from typing import Optional + +from .. import constants + + +class HfFolder: + path_token = Path(constants.HF_TOKEN_PATH) + # Private attribute. Will be removed in v0.15 + _old_path_token = Path(constants._OLD_HF_TOKEN_PATH) + + # TODO: deprecate when adapted in transformers/datasets/gradio + # @_deprecate_method(version="1.0", message="Use `huggingface_hub.login` instead.") + @classmethod + def save_token(cls, token: str) -> None: + """ + Save token, creating folder as needed. + + Token is saved in the huggingface home folder. You can configure it by setting + the `HF_HOME` environment variable. + + Args: + token (`str`): + The token to save to the [`HfFolder`] + """ + cls.path_token.parent.mkdir(parents=True, exist_ok=True) + cls.path_token.write_text(token) + + # TODO: deprecate when adapted in transformers/datasets/gradio + # @_deprecate_method(version="1.0", message="Use `huggingface_hub.get_token` instead.") + @classmethod + def get_token(cls) -> Optional[str]: + """ + Get token or None if not existent. + + Note that a token can be also provided using the `HF_TOKEN` environment variable. + + Token is saved in the huggingface home folder. You can configure it by setting + the `HF_HOME` environment variable. Previous location was `~/.huggingface/token`. + If token is found in old location but not in new location, it is copied there first. + For more details, see https://github.com/huggingface/huggingface_hub/issues/1232. + + Returns: + `str` or `None`: The token, `None` if it doesn't exist. + """ + # 0. Check if token exist in old path but not new location + try: + cls._copy_to_new_path_and_warn() + except Exception: # if not possible (e.g. PermissionError), do not raise + pass + + # 1. Is it set by environment variable ? + token: Optional[str] = os.environ.get("HF_TOKEN") + if token is None: # Ensure backward compatibility but doesn't have priority + token = os.environ.get("HUGGING_FACE_HUB_TOKEN") + if token is not None: + token = token.replace("\r", "").replace("\n", "").strip() + if token != "": + return token + + # 2. Is it set in token path ? + try: + token = cls.path_token.read_text() + token = token.replace("\r", "").replace("\n", "").strip() + return token + except FileNotFoundError: + return None + + # TODO: deprecate when adapted in transformers/datasets/gradio + # @_deprecate_method(version="1.0", message="Use `huggingface_hub.logout` instead.") + @classmethod + def delete_token(cls) -> None: + """ + Deletes the token from storage. Does not fail if token does not exist. + """ + try: + cls.path_token.unlink() + except FileNotFoundError: + pass + + try: + cls._old_path_token.unlink() + except FileNotFoundError: + pass + + @classmethod + def _copy_to_new_path_and_warn(cls): + if cls._old_path_token.exists() and not cls.path_token.exists(): + cls.save_token(cls._old_path_token.read_text()) + warnings.warn( + f"A token has been found in `{cls._old_path_token}`. This is the old" + " path where tokens were stored. The new location is" + f" `{cls.path_token}` which is configurable using `HF_HOME` environment" + " variable. Your token has been copied to this new location. You can" + " now safely delete the old token file manually or use" + " `huggingface-cli logout`." + ) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_http.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_http.py new file mode 100644 index 0000000000000000000000000000000000000000..69cbfc22574cd872a946dceae6791a56b1487523 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_http.py @@ -0,0 +1,307 @@ +# coding=utf-8 +# Copyright 2022-present, the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Contains utilities to handle HTTP requests in Huggingface Hub.""" +import io +import os +import threading +import time +import uuid +from functools import lru_cache +from http import HTTPStatus +from typing import Callable, Tuple, Type, Union + +import requests +from requests import Response +from requests.adapters import HTTPAdapter +from requests.models import PreparedRequest + +from .. import constants +from . import logging +from ._typing import HTTP_METHOD_T + + +logger = logging.get_logger(__name__) + +# Both headers are used by the Hub to debug failed requests. +# `X_AMZN_TRACE_ID` is better as it also works to debug on Cloudfront and ALB. +# If `X_AMZN_TRACE_ID` is set, the Hub will use it as well. +X_AMZN_TRACE_ID = "X-Amzn-Trace-Id" +X_REQUEST_ID = "x-request-id" + + +class OfflineModeIsEnabled(ConnectionError): + """Raised when a request is made but `HF_HUB_OFFLINE=1` is set as environment variable.""" + + +class UniqueRequestIdAdapter(HTTPAdapter): + X_AMZN_TRACE_ID = "X-Amzn-Trace-Id" + + def add_headers(self, request, **kwargs): + super().add_headers(request, **kwargs) + + # Add random request ID => easier for server-side debug + if X_AMZN_TRACE_ID not in request.headers: + request.headers[X_AMZN_TRACE_ID] = request.headers.get(X_REQUEST_ID) or str(uuid.uuid4()) + + # Add debug log + has_token = str(request.headers.get("authorization", "")).startswith("Bearer hf_") + logger.debug( + f"Request {request.headers[X_AMZN_TRACE_ID]}: {request.method} {request.url} (authenticated: {has_token})" + ) + + def send(self, request: PreparedRequest, *args, **kwargs) -> Response: + """Catch any RequestException to append request id to the error message for debugging.""" + try: + return super().send(request, *args, **kwargs) + except requests.RequestException as e: + request_id = request.headers.get(X_AMZN_TRACE_ID) + if request_id is not None: + # Taken from https://stackoverflow.com/a/58270258 + e.args = (*e.args, f"(Request ID: {request_id})") + raise + + +class OfflineAdapter(HTTPAdapter): + def send(self, request: PreparedRequest, *args, **kwargs) -> Response: + raise OfflineModeIsEnabled( + f"Cannot reach {request.url}: offline mode is enabled. To disable it, please unset the `HF_HUB_OFFLINE` environment variable." + ) + + +def _default_backend_factory() -> requests.Session: + session = requests.Session() + if constants.HF_HUB_OFFLINE: + session.mount("http://", OfflineAdapter()) + session.mount("https://", OfflineAdapter()) + else: + session.mount("http://", UniqueRequestIdAdapter()) + session.mount("https://", UniqueRequestIdAdapter()) + return session + + +BACKEND_FACTORY_T = Callable[[], requests.Session] +_GLOBAL_BACKEND_FACTORY: BACKEND_FACTORY_T = _default_backend_factory + + +def configure_http_backend(backend_factory: BACKEND_FACTORY_T = _default_backend_factory) -> None: + """ + Configure the HTTP backend by providing a `backend_factory`. Any HTTP calls made by `huggingface_hub` will use a + Session object instantiated by this factory. This can be useful if you are running your scripts in a specific + environment requiring custom configuration (e.g. custom proxy or certifications). + + Use [`get_session`] to get a configured Session. Since `requests.Session` is not guaranteed to be thread-safe, + `huggingface_hub` creates 1 Session instance per thread. They are all instantiated using the same `backend_factory` + set in [`configure_http_backend`]. A LRU cache is used to cache the created sessions (and connections) between + calls. Max size is 128 to avoid memory leaks if thousands of threads are spawned. + + See [this issue](https://github.com/psf/requests/issues/2766) to know more about thread-safety in `requests`. + + Example: + ```py + import requests + from huggingface_hub import configure_http_backend, get_session + + # Create a factory function that returns a Session with configured proxies + def backend_factory() -> requests.Session: + session = requests.Session() + session.proxies = {"http": "http://10.10.1.10:3128", "https": "https://10.10.1.11:1080"} + return session + + # Set it as the default session factory + configure_http_backend(backend_factory=backend_factory) + + # In practice, this is mostly done internally in `huggingface_hub` + session = get_session() + ``` + """ + global _GLOBAL_BACKEND_FACTORY + _GLOBAL_BACKEND_FACTORY = backend_factory + reset_sessions() + + +def get_session() -> requests.Session: + """ + Get a `requests.Session` object, using the session factory from the user. + + Use [`get_session`] to get a configured Session. Since `requests.Session` is not guaranteed to be thread-safe, + `huggingface_hub` creates 1 Session instance per thread. They are all instantiated using the same `backend_factory` + set in [`configure_http_backend`]. A LRU cache is used to cache the created sessions (and connections) between + calls. Max size is 128 to avoid memory leaks if thousands of threads are spawned. + + See [this issue](https://github.com/psf/requests/issues/2766) to know more about thread-safety in `requests`. + + Example: + ```py + import requests + from huggingface_hub import configure_http_backend, get_session + + # Create a factory function that returns a Session with configured proxies + def backend_factory() -> requests.Session: + session = requests.Session() + session.proxies = {"http": "http://10.10.1.10:3128", "https": "https://10.10.1.11:1080"} + return session + + # Set it as the default session factory + configure_http_backend(backend_factory=backend_factory) + + # In practice, this is mostly done internally in `huggingface_hub` + session = get_session() + ``` + """ + return _get_session_from_cache(process_id=os.getpid(), thread_id=threading.get_ident()) + + +def reset_sessions() -> None: + """Reset the cache of sessions. + + Mostly used internally when sessions are reconfigured or an SSLError is raised. + See [`configure_http_backend`] for more details. + """ + _get_session_from_cache.cache_clear() + + +@lru_cache +def _get_session_from_cache(process_id: int, thread_id: int) -> requests.Session: + """ + Create a new session per thread using global factory. Using LRU cache (maxsize 128) to avoid memory leaks when + using thousands of threads. Cache is cleared when `configure_http_backend` is called. + """ + return _GLOBAL_BACKEND_FACTORY() + + +def http_backoff( + method: HTTP_METHOD_T, + url: str, + *, + max_retries: int = 5, + base_wait_time: float = 1, + max_wait_time: float = 8, + retry_on_exceptions: Union[Type[Exception], Tuple[Type[Exception], ...]] = ( + requests.Timeout, + requests.ConnectionError, + ), + retry_on_status_codes: Union[int, Tuple[int, ...]] = HTTPStatus.SERVICE_UNAVAILABLE, + **kwargs, +) -> Response: + """Wrapper around requests to retry calls on an endpoint, with exponential backoff. + + Endpoint call is retried on exceptions (ex: connection timeout, proxy error,...) + and/or on specific status codes (ex: service unavailable). If the call failed more + than `max_retries`, the exception is thrown or `raise_for_status` is called on the + response object. + + Re-implement mechanisms from the `backoff` library to avoid adding an external + dependencies to `hugging_face_hub`. See https://github.com/litl/backoff. + + Args: + method (`Literal["GET", "OPTIONS", "HEAD", "POST", "PUT", "PATCH", "DELETE"]`): + HTTP method to perform. + url (`str`): + The URL of the resource to fetch. + max_retries (`int`, *optional*, defaults to `5`): + Maximum number of retries, defaults to 5 (no retries). + base_wait_time (`float`, *optional*, defaults to `1`): + Duration (in seconds) to wait before retrying the first time. + Wait time between retries then grows exponentially, capped by + `max_wait_time`. + max_wait_time (`float`, *optional*, defaults to `8`): + Maximum duration (in seconds) to wait before retrying. + retry_on_exceptions (`Type[Exception]` or `Tuple[Type[Exception]]`, *optional*): + Define which exceptions must be caught to retry the request. Can be a single type or a tuple of types. + By default, retry on `requests.Timeout` and `requests.ConnectionError`. + retry_on_status_codes (`int` or `Tuple[int]`, *optional*, defaults to `503`): + Define on which status codes the request must be retried. By default, only + HTTP 503 Service Unavailable is retried. + **kwargs (`dict`, *optional*): + kwargs to pass to `requests.request`. + + Example: + ``` + >>> from huggingface_hub.utils import http_backoff + + # Same usage as "requests.request". + >>> response = http_backoff("GET", "https://www.google.com") + >>> response.raise_for_status() + + # If you expect a Gateway Timeout from time to time + >>> http_backoff("PUT", upload_url, data=data, retry_on_status_codes=504) + >>> response.raise_for_status() + ``` + + + + When using `requests` it is possible to stream data by passing an iterator to the + `data` argument. On http backoff this is a problem as the iterator is not reset + after a failed call. This issue is mitigated for file objects or any IO streams + by saving the initial position of the cursor (with `data.tell()`) and resetting the + cursor between each call (with `data.seek()`). For arbitrary iterators, http backoff + will fail. If this is a hard constraint for you, please let us know by opening an + issue on [Github](https://github.com/huggingface/huggingface_hub). + + + """ + if isinstance(retry_on_exceptions, type): # Tuple from single exception type + retry_on_exceptions = (retry_on_exceptions,) + + if isinstance(retry_on_status_codes, int): # Tuple from single status code + retry_on_status_codes = (retry_on_status_codes,) + + nb_tries = 0 + sleep_time = base_wait_time + + # If `data` is used and is a file object (or any IO), it will be consumed on the + # first HTTP request. We need to save the initial position so that the full content + # of the file is re-sent on http backoff. See warning tip in docstring. + io_obj_initial_pos = None + if "data" in kwargs and isinstance(kwargs["data"], io.IOBase): + io_obj_initial_pos = kwargs["data"].tell() + + session = get_session() + while True: + nb_tries += 1 + try: + # If `data` is used and is a file object (or any IO), set back cursor to + # initial position. + if io_obj_initial_pos is not None: + kwargs["data"].seek(io_obj_initial_pos) + + # Perform request and return if status_code is not in the retry list. + response = session.request(method=method, url=url, **kwargs) + if response.status_code not in retry_on_status_codes: + return response + + # Wrong status code returned (HTTP 503 for instance) + logger.warning(f"HTTP Error {response.status_code} thrown while requesting {method} {url}") + if nb_tries > max_retries: + response.raise_for_status() # Will raise uncaught exception + # We return response to avoid infinite loop in the corner case where the + # user ask for retry on a status code that doesn't raise_for_status. + return response + + except retry_on_exceptions as err: + logger.warning(f"'{err}' thrown while requesting {method} {url}") + + if isinstance(err, requests.ConnectionError): + reset_sessions() # In case of SSLError it's best to reset the shared requests.Session objects + + if nb_tries > max_retries: + raise err + + # Sleep for X seconds + logger.warning(f"Retrying in {sleep_time}s [Retry {nb_tries}/{max_retries}].") + time.sleep(sleep_time) + + # Update sleep time for next retry + sleep_time = min(max_wait_time, sleep_time * 2) # Exponential backoff diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_pagination.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_pagination.py new file mode 100644 index 0000000000000000000000000000000000000000..ad9048ac55b518a1a54fe0431ac375d203bd1554 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_pagination.py @@ -0,0 +1,51 @@ +# coding=utf-8 +# Copyright 2022-present, the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Contains utilities to handle pagination on Huggingface Hub.""" +from typing import Dict, Iterable, Optional + +import requests + +from . import get_session, hf_raise_for_status, logging + + +logger = logging.get_logger(__name__) + + +def paginate(path: str, params: Dict, headers: Dict) -> Iterable: + """Fetch a list of models/datasets/spaces and paginate through results. + + This is using the same "Link" header format as GitHub. + See: + - https://requests.readthedocs.io/en/latest/api/#requests.Response.links + - https://docs.github.com/en/rest/guides/traversing-with-pagination#link-header + """ + session = get_session() + r = session.get(path, params=params, headers=headers) + hf_raise_for_status(r) + yield from r.json() + + # Follow pages + # Next link already contains query params + next_page = _get_next_page(r) + while next_page is not None: + logger.debug(f"Pagination detected. Requesting next page: {next_page}") + r = session.get(next_page, headers=headers) + hf_raise_for_status(r) + yield from r.json() + next_page = _get_next_page(r) + + +def _get_next_page(response: requests.Response) -> Optional[str]: + return response.links.get("next", {}).get("url") diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_paths.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_paths.py new file mode 100644 index 0000000000000000000000000000000000000000..0a994bf5e93fa773148dbe0941fcdb5532fbc15a --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_paths.py @@ -0,0 +1,117 @@ +# coding=utf-8 +# Copyright 2022-present, the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Contains utilities to handle paths in Huggingface Hub.""" +from fnmatch import fnmatch +from pathlib import Path +from typing import Callable, Generator, Iterable, List, Optional, TypeVar, Union + + +T = TypeVar("T") + +IGNORE_GIT_FOLDER_PATTERNS = [".git", ".git/*", "*/.git", "**/.git/**"] + + +def filter_repo_objects( + items: Iterable[T], + *, + allow_patterns: Optional[Union[List[str], str]] = None, + ignore_patterns: Optional[Union[List[str], str]] = None, + key: Optional[Callable[[T], str]] = None, +) -> Generator[T, None, None]: + """Filter repo objects based on an allowlist and a denylist. + + Input must be a list of paths (`str` or `Path`) or a list of arbitrary objects. + In the later case, `key` must be provided and specifies a function of one argument + that is used to extract a path from each element in iterable. + + Patterns are Unix shell-style wildcards which are NOT regular expressions. See + https://docs.python.org/3/library/fnmatch.html for more details. + + Args: + items (`Iterable`): + List of items to filter. + allow_patterns (`str` or `List[str]`, *optional*): + Patterns constituting the allowlist. If provided, item paths must match at + least one pattern from the allowlist. + ignore_patterns (`str` or `List[str]`, *optional*): + Patterns constituting the denylist. If provided, item paths must not match + any patterns from the denylist. + key (`Callable[[T], str]`, *optional*): + Single-argument function to extract a path from each item. If not provided, + the `items` must already be `str` or `Path`. + + Returns: + Filtered list of objects, as a generator. + + Raises: + :class:`ValueError`: + If `key` is not provided and items are not `str` or `Path`. + + Example usage with paths: + ```python + >>> # Filter only PDFs that are not hidden. + >>> list(filter_repo_objects( + ... ["aaa.PDF", "bbb.jpg", ".ccc.pdf", ".ddd.png"], + ... allow_patterns=["*.pdf"], + ... ignore_patterns=[".*"], + ... )) + ["aaa.pdf"] + ``` + + Example usage with objects: + ```python + >>> list(filter_repo_objects( + ... [ + ... CommitOperationAdd(path_or_fileobj="/tmp/aaa.pdf", path_in_repo="aaa.pdf") + ... CommitOperationAdd(path_or_fileobj="/tmp/bbb.jpg", path_in_repo="bbb.jpg") + ... CommitOperationAdd(path_or_fileobj="/tmp/.ccc.pdf", path_in_repo=".ccc.pdf") + ... CommitOperationAdd(path_or_fileobj="/tmp/.ddd.png", path_in_repo=".ddd.png") + ... ], + ... allow_patterns=["*.pdf"], + ... ignore_patterns=[".*"], + ... key=lambda x: x.repo_in_path + ... )) + [CommitOperationAdd(path_or_fileobj="/tmp/aaa.pdf", path_in_repo="aaa.pdf")] + ``` + """ + if isinstance(allow_patterns, str): + allow_patterns = [allow_patterns] + + if isinstance(ignore_patterns, str): + ignore_patterns = [ignore_patterns] + + if key is None: + + def _identity(item: T) -> str: + if isinstance(item, str): + return item + if isinstance(item, Path): + return str(item) + raise ValueError(f"Please provide `key` argument in `filter_repo_objects`: `{item}` is not a string.") + + key = _identity # Items must be `str` or `Path`, otherwise raise ValueError + + for item in items: + path = key(item) + + # Skip if there's an allowlist and path doesn't match any + if allow_patterns is not None and not any(fnmatch(path, r) for r in allow_patterns): + continue + + # Skip if there's a denylist and path matches any + if ignore_patterns is not None and any(fnmatch(path, r) for r in ignore_patterns): + continue + + yield item diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_runtime.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_runtime.py new file mode 100644 index 0000000000000000000000000000000000000000..82aa41ce1473f88197a60a463f3132a2b23ed8ad --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_runtime.py @@ -0,0 +1,344 @@ +# coding=utf-8 +# Copyright 2022-present, the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Check presence of installed packages at runtime.""" +import importlib.metadata +import platform +import sys +import warnings +from typing import Any, Dict + +from .. import __version__, constants + + +_PY_VERSION: str = sys.version.split()[0].rstrip("+") + +_package_versions = {} + +_CANDIDATES = { + "aiohttp": {"aiohttp"}, + "fastai": {"fastai"}, + "fastcore": {"fastcore"}, + "gradio": {"gradio"}, + "graphviz": {"graphviz"}, + "hf_transfer": {"hf_transfer"}, + "jinja": {"Jinja2"}, + "numpy": {"numpy"}, + "pillow": {"Pillow"}, + "pydantic": {"pydantic"}, + "pydot": {"pydot"}, + "tensorboard": {"tensorboardX"}, + "tensorflow": ( + "tensorflow", + "tensorflow-cpu", + "tensorflow-gpu", + "tf-nightly", + "tf-nightly-cpu", + "tf-nightly-gpu", + "intel-tensorflow", + "intel-tensorflow-avx512", + "tensorflow-rocm", + "tensorflow-macos", + ), + "torch": {"torch"}, +} + +# Check once at runtime +for candidate_name, package_names in _CANDIDATES.items(): + _package_versions[candidate_name] = "N/A" + for name in package_names: + try: + _package_versions[candidate_name] = importlib.metadata.version(name) + break + except importlib.metadata.PackageNotFoundError: + pass + + +def _get_version(package_name: str) -> str: + return _package_versions.get(package_name, "N/A") + + +def _is_available(package_name: str) -> bool: + return _get_version(package_name) != "N/A" + + +# Python +def get_python_version() -> str: + return _PY_VERSION + + +# Huggingface Hub +def get_hf_hub_version() -> str: + return __version__ + + +# aiohttp +def is_aiohttp_available() -> bool: + return _is_available("aiohttp") + + +def get_aiohttp_version() -> str: + return _get_version("aiohttp") + + +# FastAI +def is_fastai_available() -> bool: + return _is_available("fastai") + + +def get_fastai_version() -> str: + return _get_version("fastai") + + +# Fastcore +def is_fastcore_available() -> bool: + return _is_available("fastcore") + + +def get_fastcore_version() -> str: + return _get_version("fastcore") + + +# FastAI +def is_gradio_available() -> bool: + return _is_available("gradio") + + +def get_gradio_version() -> str: + return _get_version("gradio") + + +# Graphviz +def is_graphviz_available() -> bool: + return _is_available("graphviz") + + +def get_graphviz_version() -> str: + return _get_version("graphviz") + + +# hf_transfer +def is_hf_transfer_available() -> bool: + return _is_available("hf_transfer") + + +def get_hf_transfer_version() -> str: + return _get_version("hf_transfer") + + +# Numpy +def is_numpy_available() -> bool: + return _is_available("numpy") + + +def get_numpy_version() -> str: + return _get_version("numpy") + + +# Jinja +def is_jinja_available() -> bool: + return _is_available("jinja") + + +def get_jinja_version() -> str: + return _get_version("jinja") + + +# Pillow +def is_pillow_available() -> bool: + return _is_available("pillow") + + +def get_pillow_version() -> str: + return _get_version("pillow") + + +# Pydantic +def is_pydantic_available() -> bool: + if not _is_available("pydantic"): + return False + # For Pydantic, we add an extra check to test whether it is correctly installed or not. If both pydantic 2.x and + # typing_extensions<=4.5.0 are installed, then pydantic will fail at import time. This should not happen when + # it is installed with `pip install huggingface_hub[inference]` but it can happen when it is installed manually + # by the user in an environment that we don't control. + # + # Usually we won't need to do this kind of check on optional dependencies. However, pydantic is a special case + # as it is automatically imported when doing `from huggingface_hub import ...` even if the user doesn't use it. + # + # See https://github.com/huggingface/huggingface_hub/pull/1829 for more details. + try: + from pydantic import validator # noqa: F401 + except ImportError: + # Example: "ImportError: cannot import name 'TypeAliasType' from 'typing_extensions'" + warnings.warn( + "Pydantic is installed but cannot be imported. Please check your installation. `huggingface_hub` will " + "default to not using Pydantic. Error message: '{e}'" + ) + return False + return True + + +def get_pydantic_version() -> str: + return _get_version("pydantic") + + +# Pydot +def is_pydot_available() -> bool: + return _is_available("pydot") + + +def get_pydot_version() -> str: + return _get_version("pydot") + + +# Tensorboard +def is_tensorboard_available() -> bool: + return _is_available("tensorboard") + + +def get_tensorboard_version() -> str: + return _get_version("tensorboard") + + +# Tensorflow +def is_tf_available() -> bool: + return _is_available("tensorflow") + + +def get_tf_version() -> str: + return _get_version("tensorflow") + + +# Torch +def is_torch_available() -> bool: + return _is_available("torch") + + +def get_torch_version() -> str: + return _get_version("torch") + + +# Shell-related helpers +try: + # Set to `True` if script is running in a Google Colab notebook. + # If running in Google Colab, git credential store is set globally which makes the + # warning disappear. See https://github.com/huggingface/huggingface_hub/issues/1043 + # + # Taken from https://stackoverflow.com/a/63519730. + _is_google_colab = "google.colab" in str(get_ipython()) # type: ignore # noqa: F821 +except NameError: + _is_google_colab = False + + +def is_notebook() -> bool: + """Return `True` if code is executed in a notebook (Jupyter, Colab, QTconsole). + + Taken from https://stackoverflow.com/a/39662359. + Adapted to make it work with Google colab as well. + """ + try: + shell_class = get_ipython().__class__ # type: ignore # noqa: F821 + for parent_class in shell_class.__mro__: # e.g. "is subclass of" + if parent_class.__name__ == "ZMQInteractiveShell": + return True # Jupyter notebook, Google colab or qtconsole + return False + except NameError: + return False # Probably standard Python interpreter + + +def is_google_colab() -> bool: + """Return `True` if code is executed in a Google colab. + + Taken from https://stackoverflow.com/a/63519730. + """ + return _is_google_colab + + +def dump_environment_info() -> Dict[str, Any]: + """Dump information about the machine to help debugging issues. + + Similar helper exist in: + - `datasets` (https://github.com/huggingface/datasets/blob/main/src/datasets/commands/env.py) + - `diffusers` (https://github.com/huggingface/diffusers/blob/main/src/diffusers/commands/env.py) + - `transformers` (https://github.com/huggingface/transformers/blob/main/src/transformers/commands/env.py) + """ + from huggingface_hub import get_token, whoami + from huggingface_hub.utils import list_credential_helpers + + token = get_token() + + # Generic machine info + info: Dict[str, Any] = { + "huggingface_hub version": get_hf_hub_version(), + "Platform": platform.platform(), + "Python version": get_python_version(), + } + + # Interpreter info + try: + shell_class = get_ipython().__class__ # type: ignore # noqa: F821 + info["Running in iPython ?"] = "Yes" + info["iPython shell"] = shell_class.__name__ + except NameError: + info["Running in iPython ?"] = "No" + info["Running in notebook ?"] = "Yes" if is_notebook() else "No" + info["Running in Google Colab ?"] = "Yes" if is_google_colab() else "No" + + # Login info + info["Token path ?"] = constants.HF_TOKEN_PATH + info["Has saved token ?"] = token is not None + if token is not None: + try: + info["Who am I ?"] = whoami()["name"] + except Exception: + pass + + try: + info["Configured git credential helpers"] = ", ".join(list_credential_helpers()) + except Exception: + pass + + # Installed dependencies + info["FastAI"] = get_fastai_version() + info["Tensorflow"] = get_tf_version() + info["Torch"] = get_torch_version() + info["Jinja2"] = get_jinja_version() + info["Graphviz"] = get_graphviz_version() + info["Pydot"] = get_pydot_version() + info["Pillow"] = get_pillow_version() + info["hf_transfer"] = get_hf_transfer_version() + info["gradio"] = get_gradio_version() + info["tensorboard"] = get_tensorboard_version() + info["numpy"] = get_numpy_version() + info["pydantic"] = get_pydantic_version() + info["aiohttp"] = get_aiohttp_version() + + # Environment variables + info["ENDPOINT"] = constants.ENDPOINT + info["HF_HUB_CACHE"] = constants.HF_HUB_CACHE + info["HF_ASSETS_CACHE"] = constants.HF_ASSETS_CACHE + info["HF_TOKEN_PATH"] = constants.HF_TOKEN_PATH + info["HF_HUB_OFFLINE"] = constants.HF_HUB_OFFLINE + info["HF_HUB_DISABLE_TELEMETRY"] = constants.HF_HUB_DISABLE_TELEMETRY + info["HF_HUB_DISABLE_PROGRESS_BARS"] = constants.HF_HUB_DISABLE_PROGRESS_BARS + info["HF_HUB_DISABLE_SYMLINKS_WARNING"] = constants.HF_HUB_DISABLE_SYMLINKS_WARNING + info["HF_HUB_DISABLE_EXPERIMENTAL_WARNING"] = constants.HF_HUB_DISABLE_EXPERIMENTAL_WARNING + info["HF_HUB_DISABLE_IMPLICIT_TOKEN"] = constants.HF_HUB_DISABLE_IMPLICIT_TOKEN + info["HF_HUB_ENABLE_HF_TRANSFER"] = constants.HF_HUB_ENABLE_HF_TRANSFER + info["HF_HUB_ETAG_TIMEOUT"] = constants.HF_HUB_ETAG_TIMEOUT + info["HF_HUB_DOWNLOAD_TIMEOUT"] = constants.HF_HUB_DOWNLOAD_TIMEOUT + + print("\nCopy-and-paste the text below in your GitHub issue.\n") + print("\n".join([f"- {prop}: {val}" for prop, val in info.items()]) + "\n") + return info diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_safetensors.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_safetensors.py new file mode 100644 index 0000000000000000000000000000000000000000..d37e8f76fee25976d48ad591fe8afb277ae6ef38 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_safetensors.py @@ -0,0 +1,124 @@ +import functools +import operator +from collections import defaultdict +from dataclasses import dataclass, field +from typing import Dict, List, Literal, Optional, Tuple + + +FILENAME_T = str +TENSOR_NAME_T = str +DTYPE_T = Literal["F64", "F32", "F16", "BF16", "I64", "I32", "I16", "I8", "U8", "BOOL"] + + +class SafetensorsParsingError(Exception): + """Raised when failing to parse a safetensors file metadata. + + This can be the case if the file is not a safetensors file or does not respect the specification. + """ + + +class NotASafetensorsRepoError(Exception): + """Raised when a repo is not a Safetensors repo i.e. doesn't have either a `model.safetensors` or a + `model.safetensors.index.json` file. + """ + + +@dataclass +class TensorInfo: + """Information about a tensor. + + For more details regarding the safetensors format, check out https://huggingface.co/docs/safetensors/index#format. + + Attributes: + dtype (`str`): + The data type of the tensor ("F64", "F32", "F16", "BF16", "I64", "I32", "I16", "I8", "U8", "BOOL"). + shape (`List[int]`): + The shape of the tensor. + data_offsets (`Tuple[int, int]`): + The offsets of the data in the file as a tuple `[BEGIN, END]`. + parameter_count (`int`): + The number of parameters in the tensor. + """ + + dtype: DTYPE_T + shape: List[int] + data_offsets: Tuple[int, int] + parameter_count: int = field(init=False) + + def __post_init__(self) -> None: + # Taken from https://stackoverflow.com/a/13840436 + try: + self.parameter_count = functools.reduce(operator.mul, self.shape) + except TypeError: + self.parameter_count = 1 # scalar value has no shape + + +@dataclass +class SafetensorsFileMetadata: + """Metadata for a Safetensors file hosted on the Hub. + + This class is returned by [`parse_safetensors_file_metadata`]. + + For more details regarding the safetensors format, check out https://huggingface.co/docs/safetensors/index#format. + + Attributes: + metadata (`Dict`): + The metadata contained in the file. + tensors (`Dict[str, TensorInfo]`): + A map of all tensors. Keys are tensor names and values are information about the corresponding tensor, as a + [`TensorInfo`] object. + parameter_count (`Dict[str, int]`): + A map of the number of parameters per data type. Keys are data types and values are the number of parameters + of that data type. + """ + + metadata: Dict[str, str] + tensors: Dict[TENSOR_NAME_T, TensorInfo] + parameter_count: Dict[DTYPE_T, int] = field(init=False) + + def __post_init__(self) -> None: + parameter_count: Dict[DTYPE_T, int] = defaultdict(int) + for tensor in self.tensors.values(): + parameter_count[tensor.dtype] += tensor.parameter_count + self.parameter_count = dict(parameter_count) + + +@dataclass +class SafetensorsRepoMetadata: + """Metadata for a Safetensors repo. + + A repo is considered to be a Safetensors repo if it contains either a 'model.safetensors' weight file (non-shared + model) or a 'model.safetensors.index.json' index file (sharded model) at its root. + + This class is returned by [`get_safetensors_metadata`]. + + For more details regarding the safetensors format, check out https://huggingface.co/docs/safetensors/index#format. + + Attributes: + metadata (`Dict`, *optional*): + The metadata contained in the 'model.safetensors.index.json' file, if it exists. Only populated for sharded + models. + sharded (`bool`): + Whether the repo contains a sharded model or not. + weight_map (`Dict[str, str]`): + A map of all weights. Keys are tensor names and values are filenames of the files containing the tensors. + files_metadata (`Dict[str, SafetensorsFileMetadata]`): + A map of all files metadata. Keys are filenames and values are the metadata of the corresponding file, as + a [`SafetensorsFileMetadata`] object. + parameter_count (`Dict[str, int]`): + A map of the number of parameters per data type. Keys are data types and values are the number of parameters + of that data type. + """ + + metadata: Optional[Dict] + sharded: bool + weight_map: Dict[TENSOR_NAME_T, FILENAME_T] # tensor name -> filename + files_metadata: Dict[FILENAME_T, SafetensorsFileMetadata] # filename -> metadata + parameter_count: Dict[DTYPE_T, int] = field(init=False) + + def __post_init__(self) -> None: + parameter_count: Dict[DTYPE_T, int] = defaultdict(int) + for file_metadata in self.files_metadata.values(): + for dtype, nb_parameters_ in file_metadata.parameter_count.items(): + parameter_count[dtype] += nb_parameters_ + self.parameter_count = dict(parameter_count) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_subprocess.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_subprocess.py new file mode 100644 index 0000000000000000000000000000000000000000..5ec7936549c11f432c2b98a2f88a7a87d1b38772 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_subprocess.py @@ -0,0 +1,142 @@ +#!/usr/bin/env python +# coding=utf-8 +# Copyright 2021 The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License +"""Contains utilities to easily handle subprocesses in `huggingface_hub`.""" +import os +import subprocess +import sys +from contextlib import contextmanager +from io import StringIO +from pathlib import Path +from typing import IO, Generator, List, Optional, Tuple, Union + +from .logging import get_logger + + +logger = get_logger(__name__) + + +@contextmanager +def capture_output() -> Generator[StringIO, None, None]: + """Capture output that is printed to terminal. + + Taken from https://stackoverflow.com/a/34738440 + + Example: + ```py + >>> with capture_output() as output: + ... print("hello world") + >>> assert output.getvalue() == "hello world\n" + ``` + """ + output = StringIO() + previous_output = sys.stdout + sys.stdout = output + yield output + sys.stdout = previous_output + + +def run_subprocess( + command: Union[str, List[str]], + folder: Optional[Union[str, Path]] = None, + check=True, + **kwargs, +) -> subprocess.CompletedProcess: + """ + Method to run subprocesses. Calling this will capture the `stderr` and `stdout`, + please call `subprocess.run` manually in case you would like for them not to + be captured. + + Args: + command (`str` or `List[str]`): + The command to execute as a string or list of strings. + folder (`str`, *optional*): + The folder in which to run the command. Defaults to current working + directory (from `os.getcwd()`). + check (`bool`, *optional*, defaults to `True`): + Setting `check` to `True` will raise a `subprocess.CalledProcessError` + when the subprocess has a non-zero exit code. + kwargs (`Dict[str]`): + Keyword arguments to be passed to the `subprocess.run` underlying command. + + Returns: + `subprocess.CompletedProcess`: The completed process. + """ + if isinstance(command, str): + command = command.split() + + if isinstance(folder, Path): + folder = str(folder) + + return subprocess.run( + command, + stderr=subprocess.PIPE, + stdout=subprocess.PIPE, + check=check, + encoding="utf-8", + errors="replace", # if not utf-8, replace char by � + cwd=folder or os.getcwd(), + **kwargs, + ) + + +@contextmanager +def run_interactive_subprocess( + command: Union[str, List[str]], + folder: Optional[Union[str, Path]] = None, + **kwargs, +) -> Generator[Tuple[IO[str], IO[str]], None, None]: + """Run a subprocess in an interactive mode in a context manager. + + Args: + command (`str` or `List[str]`): + The command to execute as a string or list of strings. + folder (`str`, *optional*): + The folder in which to run the command. Defaults to current working + directory (from `os.getcwd()`). + kwargs (`Dict[str]`): + Keyword arguments to be passed to the `subprocess.run` underlying command. + + Returns: + `Tuple[IO[str], IO[str]]`: A tuple with `stdin` and `stdout` to interact + with the process (input and output are utf-8 encoded). + + Example: + ```python + with _interactive_subprocess("git credential-store get") as (stdin, stdout): + # Write to stdin + stdin.write("url=hf.co\nusername=obama\n".encode("utf-8")) + stdin.flush() + + # Read from stdout + output = stdout.read().decode("utf-8") + ``` + """ + if isinstance(command, str): + command = command.split() + + with subprocess.Popen( + command, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + encoding="utf-8", + errors="replace", # if not utf-8, replace char by � + cwd=folder or os.getcwd(), + **kwargs, + ) as process: + assert process.stdin is not None, "subprocess is opened as subprocess.PIPE" + assert process.stdout is not None, "subprocess is opened as subprocess.PIPE" + yield process.stdin, process.stdout diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_telemetry.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_telemetry.py new file mode 100644 index 0000000000000000000000000000000000000000..5de988e2795188324f69232d1beb68191591715d --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_telemetry.py @@ -0,0 +1,118 @@ +from queue import Queue +from threading import Lock, Thread +from typing import Dict, Optional, Union +from urllib.parse import quote + +from .. import constants, logging +from . import build_hf_headers, get_session, hf_raise_for_status + + +logger = logging.get_logger(__name__) + +# Telemetry is sent by a separate thread to avoid blocking the main thread. +# A daemon thread is started once and consume tasks from the _TELEMETRY_QUEUE. +# If the thread stops for some reason -shouldn't happen-, we restart a new one. +_TELEMETRY_THREAD: Optional[Thread] = None +_TELEMETRY_THREAD_LOCK = Lock() # Lock to avoid starting multiple threads in parallel +_TELEMETRY_QUEUE: Queue = Queue() + + +def send_telemetry( + topic: str, + *, + library_name: Optional[str] = None, + library_version: Optional[str] = None, + user_agent: Union[Dict, str, None] = None, +) -> None: + """ + Sends telemetry that helps tracking usage of different HF libraries. + + This usage data helps us debug issues and prioritize new features. However, we understand that not everyone wants + to share additional information, and we respect your privacy. You can disable telemetry collection by setting the + `HF_HUB_DISABLE_TELEMETRY=1` as environment variable. Telemetry is also disabled in offline mode (i.e. when setting + `HF_HUB_OFFLINE=1`). + + Telemetry collection is run in a separate thread to minimize impact for the user. + + Args: + topic (`str`): + Name of the topic that is monitored. The topic is directly used to build the URL. If you want to monitor + subtopics, just use "/" separation. Examples: "gradio", "transformers/examples",... + library_name (`str`, *optional*): + The name of the library that is making the HTTP request. Will be added to the user-agent header. + library_version (`str`, *optional*): + The version of the library that is making the HTTP request. Will be added to the user-agent header. + user_agent (`str`, `dict`, *optional*): + The user agent info in the form of a dictionary or a single string. It will be completed with information about the installed packages. + + Example: + ```py + >>> from huggingface_hub.utils import send_telemetry + + # Send telemetry without library information + >>> send_telemetry("ping") + + # Send telemetry to subtopic with library information + >>> send_telemetry("gradio/local_link", library_name="gradio", library_version="3.22.1") + + # Send telemetry with additional data + >>> send_telemetry( + ... topic="examples", + ... library_name="transformers", + ... library_version="4.26.0", + ... user_agent={"pipeline": "text_classification", "framework": "flax"}, + ... ) + ``` + """ + if constants.HF_HUB_OFFLINE or constants.HF_HUB_DISABLE_TELEMETRY: + return + + _start_telemetry_thread() # starts thread only if doesn't exist yet + _TELEMETRY_QUEUE.put( + {"topic": topic, "library_name": library_name, "library_version": library_version, "user_agent": user_agent} + ) + + +def _start_telemetry_thread(): + """Start a daemon thread to consume tasks from the telemetry queue. + + If the thread is interrupted, start a new one. + """ + with _TELEMETRY_THREAD_LOCK: # avoid to start multiple threads if called concurrently + global _TELEMETRY_THREAD + if _TELEMETRY_THREAD is None or not _TELEMETRY_THREAD.is_alive(): + _TELEMETRY_THREAD = Thread(target=_telemetry_worker, daemon=True) + _TELEMETRY_THREAD.start() + + +def _telemetry_worker(): + """Wait for a task and consume it.""" + while True: + kwargs = _TELEMETRY_QUEUE.get() + _send_telemetry_in_thread(**kwargs) + _TELEMETRY_QUEUE.task_done() + + +def _send_telemetry_in_thread( + topic: str, + *, + library_name: Optional[str] = None, + library_version: Optional[str] = None, + user_agent: Union[Dict, str, None] = None, +) -> None: + """Contains the actual data sending data to the Hub.""" + path = "/".join(quote(part) for part in topic.split("/") if len(part) > 0) + try: + r = get_session().head( + f"{constants.ENDPOINT}/api/telemetry/{path}", + headers=build_hf_headers( + token=False, # no need to send a token for telemetry + library_name=library_name, + library_version=library_version, + user_agent=user_agent, + ), + ) + hf_raise_for_status(r) + except Exception as e: + # We don't want to error in case of connection errors of any kind. + logger.debug(f"Error while sending telemetry: {e}") diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_token.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_token.py new file mode 100644 index 0000000000000000000000000000000000000000..511ff5d577acbc3195d3c3dcf3a43c1f26e6288a --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_token.py @@ -0,0 +1,112 @@ +# Copyright 2023 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Contains an helper to get the token from machine (env variable, secret or config file).""" +import os +import warnings +from pathlib import Path +from typing import Optional + +from .. import constants +from ._runtime import is_google_colab + + +_CHECK_GOOGLE_COLAB_SECRET = True + + +def get_token() -> Optional[str]: + """ + Get token if user is logged in. + + Note: in most cases, you should use [`huggingface_hub.utils.build_hf_headers`] instead. This method is only useful + if you want to retrieve the token for other purposes than sending an HTTP request. + + Token is retrieved in priority from the `HF_TOKEN` environment variable. Otherwise, we read the token file located + in the Hugging Face home folder. Returns None if user is not logged in. To log in, use [`login`] or + `huggingface-cli login`. + + Returns: + `str` or `None`: The token, `None` if it doesn't exist. + """ + return _get_token_from_google_colab() or _get_token_from_environment() or _get_token_from_file() + + +def _get_token_from_google_colab() -> Optional[str]: + if not is_google_colab(): + return None + + global _CHECK_GOOGLE_COLAB_SECRET + if not _CHECK_GOOGLE_COLAB_SECRET: # request access only once + return None + + try: + from google.colab import userdata + from google.colab.errors import Error as ColabError + except ImportError: + return None + + try: + token = userdata.get("HF_TOKEN") + except userdata.NotebookAccessError: + # Means the user has a secret call `HF_TOKEN` and got a popup "please grand access to HF_TOKEN" and refused it + # => warn user but ignore error => do not re-request access to user + warnings.warn( + "\nAccess to the secret `HF_TOKEN` has not been granted on this notebook." + "\nYou will not be requested again." + "\nPlease restart the session if you want to be prompted again." + ) + _CHECK_GOOGLE_COLAB_SECRET = False + return None + except userdata.SecretNotFoundError: + # Means the user did not define a `HF_TOKEN` secret => warn + warnings.warn( + "\nThe secret `HF_TOKEN` does not exist in your Colab secrets." + "\nTo authenticate with the Hugging Face Hub, create a token in your settings tab " + "(https://huggingface.co/settings/tokens), set it as secret in your Google Colab and restart your session." + "\nYou will be able to reuse this secret in all of your notebooks." + "\nPlease note that authentication is recommended but still optional to access public models or datasets." + ) + return None + except ColabError as e: + # Something happen but we don't know what => recommend to open a GitHub issue + warnings.warn( + f"\nError while fetching `HF_TOKEN` secret value from your vault: '{str(e)}'." + "\nYou are not authenticated with the Hugging Face Hub in this notebook." + "\nIf the error persists, please let us know by opening an issue on GitHub " + "(https://github.com/huggingface/huggingface_hub/issues/new)." + ) + return None + + return _clean_token(token) + + +def _get_token_from_environment() -> Optional[str]: + # `HF_TOKEN` has priority (keep `HUGGING_FACE_HUB_TOKEN` for backward compatibility) + return _clean_token(os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN")) + + +def _get_token_from_file() -> Optional[str]: + try: + return _clean_token(Path(constants.HF_TOKEN_PATH).read_text()) + except FileNotFoundError: + return None + + +def _clean_token(token: Optional[str]) -> Optional[str]: + """Clean token by removing trailing and leading spaces and newlines. + + If token is an empty string, return None. + """ + if token is None: + return None + return token.replace("\r", "").replace("\n", "").strip() or None diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_typing.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_typing.py new file mode 100644 index 0000000000000000000000000000000000000000..56f2ceed6bb718bbbc119c873caa1b240f5702ac --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_typing.py @@ -0,0 +1,22 @@ +# coding=utf-8 +# Copyright 2022-present, the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Handle typing imports based on system compatibility.""" +from typing import Callable, Literal, TypeVar + + +HTTP_METHOD_T = Literal["GET", "OPTIONS", "HEAD", "POST", "PUT", "PATCH", "DELETE"] + +# type hint meaning "function signature not changed by decorator" +CallableT = TypeVar("CallableT", bound=Callable) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_validators.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_validators.py new file mode 100644 index 0000000000000000000000000000000000000000..5dd64fa51435b97142bb61cfe12f9369e6f1488b --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/_validators.py @@ -0,0 +1,230 @@ +# coding=utf-8 +# Copyright 2022-present, the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Contains utilities to validate argument values in `huggingface_hub`.""" +import inspect +import re +import warnings +from functools import wraps +from itertools import chain +from typing import Any, Dict + +from ._typing import CallableT + + +REPO_ID_REGEX = re.compile( + r""" + ^ + (\b[\w\-.]+\b/)? # optional namespace (username or organization) + \b # starts with a word boundary + [\w\-.]{1,96} # repo_name: alphanumeric + . _ - + \b # ends with a word boundary + $ + """, + flags=re.VERBOSE, +) + + +class HFValidationError(ValueError): + """Generic exception thrown by `huggingface_hub` validators. + + Inherits from [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError). + """ + + +def validate_hf_hub_args(fn: CallableT) -> CallableT: + """Validate values received as argument for any public method of `huggingface_hub`. + + The goal of this decorator is to harmonize validation of arguments reused + everywhere. By default, all defined validators are tested. + + Validators: + - [`~utils.validate_repo_id`]: `repo_id` must be `"repo_name"` + or `"namespace/repo_name"`. Namespace is a username or an organization. + - [`~utils.smoothly_deprecate_use_auth_token`]: Use `token` instead of + `use_auth_token` (only if `use_auth_token` is not expected by the decorated + function - in practice, always the case in `huggingface_hub`). + + Example: + ```py + >>> from huggingface_hub.utils import validate_hf_hub_args + + >>> @validate_hf_hub_args + ... def my_cool_method(repo_id: str): + ... print(repo_id) + + >>> my_cool_method(repo_id="valid_repo_id") + valid_repo_id + + >>> my_cool_method("other..repo..id") + huggingface_hub.utils._validators.HFValidationError: Cannot have -- or .. in repo_id: 'other..repo..id'. + + >>> my_cool_method(repo_id="other..repo..id") + huggingface_hub.utils._validators.HFValidationError: Cannot have -- or .. in repo_id: 'other..repo..id'. + + >>> @validate_hf_hub_args + ... def my_cool_auth_method(token: str): + ... print(token) + + >>> my_cool_auth_method(token="a token") + "a token" + + >>> my_cool_auth_method(use_auth_token="a use_auth_token") + "a use_auth_token" + + >>> my_cool_auth_method(token="a token", use_auth_token="a use_auth_token") + UserWarning: Both `token` and `use_auth_token` are passed (...) + "a token" + ``` + + Raises: + [`~utils.HFValidationError`]: + If an input is not valid. + """ + # TODO: add an argument to opt-out validation for specific argument? + signature = inspect.signature(fn) + + # Should the validator switch `use_auth_token` values to `token`? In practice, always + # True in `huggingface_hub`. Might not be the case in a downstream library. + check_use_auth_token = "use_auth_token" not in signature.parameters and "token" in signature.parameters + + @wraps(fn) + def _inner_fn(*args, **kwargs): + has_token = False + for arg_name, arg_value in chain( + zip(signature.parameters, args), # Args values + kwargs.items(), # Kwargs values + ): + if arg_name in ["repo_id", "from_id", "to_id"]: + validate_repo_id(arg_value) + + elif arg_name == "token" and arg_value is not None: + has_token = True + + if check_use_auth_token: + kwargs = smoothly_deprecate_use_auth_token(fn_name=fn.__name__, has_token=has_token, kwargs=kwargs) + + return fn(*args, **kwargs) + + return _inner_fn # type: ignore + + +def validate_repo_id(repo_id: str) -> None: + """Validate `repo_id` is valid. + + This is not meant to replace the proper validation made on the Hub but rather to + avoid local inconsistencies whenever possible (example: passing `repo_type` in the + `repo_id` is forbidden). + + Rules: + - Between 1 and 96 characters. + - Either "repo_name" or "namespace/repo_name" + - [a-zA-Z0-9] or "-", "_", "." + - "--" and ".." are forbidden + + Valid: `"foo"`, `"foo/bar"`, `"123"`, `"Foo-BAR_foo.bar123"` + + Not valid: `"datasets/foo/bar"`, `".repo_id"`, `"foo--bar"`, `"foo.git"` + + Example: + ```py + >>> from huggingface_hub.utils import validate_repo_id + >>> validate_repo_id(repo_id="valid_repo_id") + >>> validate_repo_id(repo_id="other..repo..id") + huggingface_hub.utils._validators.HFValidationError: Cannot have -- or .. in repo_id: 'other..repo..id'. + ``` + + Discussed in https://github.com/huggingface/huggingface_hub/issues/1008. + In moon-landing (internal repository): + - https://github.com/huggingface/moon-landing/blob/main/server/lib/Names.ts#L27 + - https://github.com/huggingface/moon-landing/blob/main/server/views/components/NewRepoForm/NewRepoForm.svelte#L138 + """ + if not isinstance(repo_id, str): + # Typically, a Path is not a repo_id + raise HFValidationError(f"Repo id must be a string, not {type(repo_id)}: '{repo_id}'.") + + if repo_id.count("/") > 1: + raise HFValidationError( + "Repo id must be in the form 'repo_name' or 'namespace/repo_name':" + f" '{repo_id}'. Use `repo_type` argument if needed." + ) + + if not REPO_ID_REGEX.match(repo_id): + raise HFValidationError( + "Repo id must use alphanumeric chars or '-', '_', '.', '--' and '..' are" + " forbidden, '-' and '.' cannot start or end the name, max length is 96:" + f" '{repo_id}'." + ) + + if "--" in repo_id or ".." in repo_id: + raise HFValidationError(f"Cannot have -- or .. in repo_id: '{repo_id}'.") + + if repo_id.endswith(".git"): + raise HFValidationError(f"Repo_id cannot end by '.git': '{repo_id}'.") + + +def smoothly_deprecate_use_auth_token(fn_name: str, has_token: bool, kwargs: Dict[str, Any]) -> Dict[str, Any]: + """Smoothly deprecate `use_auth_token` in the `huggingface_hub` codebase. + + The long-term goal is to remove any mention of `use_auth_token` in the codebase in + favor of a unique and less verbose `token` argument. This will be done a few steps: + + 0. Step 0: methods that require a read-access to the Hub use the `use_auth_token` + argument (`str`, `bool` or `None`). Methods requiring write-access have a `token` + argument (`str`, `None`). This implicit rule exists to be able to not send the + token when not necessary (`use_auth_token=False`) even if logged in. + + 1. Step 1: we want to harmonize everything and use `token` everywhere (supporting + `token=False` for read-only methods). In order not to break existing code, if + `use_auth_token` is passed to a function, the `use_auth_token` value is passed + as `token` instead, without any warning. + a. Corner case: if both `use_auth_token` and `token` values are passed, a warning + is thrown and the `use_auth_token` value is ignored. + + 2. Step 2: Once it is release, we should push downstream libraries to switch from + `use_auth_token` to `token` as much as possible, but without throwing a warning + (e.g. manually create issues on the corresponding repos). + + 3. Step 3: After a transitional period (6 months e.g. until April 2023?), we update + `huggingface_hub` to throw a warning on `use_auth_token`. Hopefully, very few + users will be impacted as it would have already been fixed. + In addition, unit tests in `huggingface_hub` must be adapted to expect warnings + to be thrown (but still use `use_auth_token` as before). + + 4. Step 4: After a normal deprecation cycle (3 releases ?), remove this validator. + `use_auth_token` will definitely not be supported. + In addition, we update unit tests in `huggingface_hub` to use `token` everywhere. + + This has been discussed in: + - https://github.com/huggingface/huggingface_hub/issues/1094. + - https://github.com/huggingface/huggingface_hub/pull/928 + - (related) https://github.com/huggingface/huggingface_hub/pull/1064 + """ + new_kwargs = kwargs.copy() # do not mutate input ! + + use_auth_token = new_kwargs.pop("use_auth_token", None) # remove from kwargs + if use_auth_token is not None: + if has_token: + warnings.warn( + "Both `token` and `use_auth_token` are passed to" + f" `{fn_name}` with non-None values. `token` is now the" + " preferred argument to pass a User Access Token." + " `use_auth_token` value will be ignored." + ) + else: + # `token` argument is not passed and a non-None value is passed in + # `use_auth_token` => use `use_auth_token` value as `token` kwarg. + new_kwargs["token"] = use_auth_token + + return new_kwargs diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/endpoint_helpers.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/endpoint_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..cbda8938f9a65fff437d75fedf3ad97c445bb0a9 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/endpoint_helpers.py @@ -0,0 +1,223 @@ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +Helpful utility functions and classes in relation to exploring API endpoints +with the aim for a user-friendly interface. +""" +import math +import re +from dataclasses import dataclass +from typing import TYPE_CHECKING, List, Optional, Union + +from ..repocard_data import ModelCardData + + +if TYPE_CHECKING: + from ..hf_api import ModelInfo + + +def _is_emission_within_treshold(model_info: "ModelInfo", minimum_threshold: float, maximum_threshold: float) -> bool: + """Checks if a model's emission is within a given threshold. + + Args: + model_info (`ModelInfo`): + A model info object containing the model's emission information. + minimum_threshold (`float`): + A minimum carbon threshold to filter by, such as 1. + maximum_threshold (`float`): + A maximum carbon threshold to filter by, such as 10. + + Returns: + `bool`: Whether the model's emission is within the given threshold. + """ + if minimum_threshold is None and maximum_threshold is None: + raise ValueError("Both `minimum_threshold` and `maximum_threshold` cannot both be `None`") + if minimum_threshold is None: + minimum_threshold = -1 + if maximum_threshold is None: + maximum_threshold = math.inf + + card_data = getattr(model_info, "card_data", None) + if card_data is None or not isinstance(card_data, (dict, ModelCardData)): + return False + + # Get CO2 emission metadata + emission = card_data.get("co2_eq_emissions", None) + if isinstance(emission, dict): + emission = emission["emissions"] + if not emission: + return False + + # Filter out if value is missing or out of range + matched = re.search(r"\d+\.\d+|\d+", str(emission)) + if matched is None: + return False + + emission_value = float(matched.group(0)) + return minimum_threshold <= emission_value <= maximum_threshold + + +@dataclass +class DatasetFilter: + """ + A class that converts human-readable dataset search parameters into ones + compatible with the REST API. For all parameters capitalization does not + matter. + + Args: + author (`str`, *optional*): + A string or list of strings that can be used to identify datasets on + the Hub by the original uploader (author or organization), such as + `facebook` or `huggingface`. + benchmark (`str` or `List`, *optional*): + A string or list of strings that can be used to identify datasets on + the Hub by their official benchmark. + dataset_name (`str`, *optional*): + A string or list of strings that can be used to identify datasets on + the Hub by its name, such as `SQAC` or `wikineural` + language_creators (`str` or `List`, *optional*): + A string or list of strings that can be used to identify datasets on + the Hub with how the data was curated, such as `crowdsourced` or + `machine_generated`. + language (`str` or `List`, *optional*): + A string or list of strings representing a two-character language to + filter datasets by on the Hub. + multilinguality (`str` or `List`, *optional*): + A string or list of strings representing a filter for datasets that + contain multiple languages. + size_categories (`str` or `List`, *optional*): + A string or list of strings that can be used to identify datasets on + the Hub by the size of the dataset such as `100K>> from huggingface_hub import DatasetFilter + + >>> # Using author + >>> new_filter = DatasetFilter(author="facebook") + + >>> # Using benchmark + >>> new_filter = DatasetFilter(benchmark="raft") + + >>> # Using dataset_name + >>> new_filter = DatasetFilter(dataset_name="wikineural") + + >>> # Using language_creator + >>> new_filter = DatasetFilter(language_creator="crowdsourced") + + >>> # Using language + >>> new_filter = DatasetFilter(language="en") + + >>> # Using multilinguality + >>> new_filter = DatasetFilter(multilinguality="multilingual") + + >>> # Using size_categories + >>> new_filter = DatasetFilter(size_categories="100K>> # Using task_categories + >>> new_filter = DatasetFilter(task_categories="audio_classification") + + >>> # Using task_ids + >>> new_filter = DatasetFilter(task_ids="paraphrase") + ``` + """ + + author: Optional[str] = None + benchmark: Optional[Union[str, List[str]]] = None + dataset_name: Optional[str] = None + language_creators: Optional[Union[str, List[str]]] = None + language: Optional[Union[str, List[str]]] = None + multilinguality: Optional[Union[str, List[str]]] = None + size_categories: Optional[Union[str, List[str]]] = None + task_categories: Optional[Union[str, List[str]]] = None + task_ids: Optional[Union[str, List[str]]] = None + + +@dataclass +class ModelFilter: + """ + A class that converts human-readable model search parameters into ones + compatible with the REST API. For all parameters capitalization does not + matter. + + Args: + author (`str`, *optional*): + A string that can be used to identify models on the Hub by the + original uploader (author or organization), such as `facebook` or + `huggingface`. + library (`str` or `List`, *optional*): + A string or list of strings of foundational libraries models were + originally trained from, such as pytorch, tensorflow, or allennlp. + language (`str` or `List`, *optional*): + A string or list of strings of languages, both by name and country + code, such as "en" or "English" + model_name (`str`, *optional*): + A string that contain complete or partial names for models on the + Hub, such as "bert" or "bert-base-cased" + task (`str` or `List`, *optional*): + A string or list of strings of tasks models were designed for, such + as: "fill-mask" or "automatic-speech-recognition" + tags (`str` or `List`, *optional*): + A string tag or a list of tags to filter models on the Hub by, such + as `text-generation` or `spacy`. + trained_dataset (`str` or `List`, *optional*): + A string tag or a list of string tags of the trained dataset for a + model on the Hub. + + + ```python + >>> from huggingface_hub import ModelFilter + + >>> # For the author_or_organization + >>> new_filter = ModelFilter(author_or_organization="facebook") + + >>> # For the library + >>> new_filter = ModelFilter(library="pytorch") + + >>> # For the language + >>> new_filter = ModelFilter(language="french") + + >>> # For the model_name + >>> new_filter = ModelFilter(model_name="bert") + + >>> # For the task + >>> new_filter = ModelFilter(task="text-classification") + + >>> from huggingface_hub import HfApi + + >>> api = HfApi() + # To list model tags + + >>> new_filter = ModelFilter(tags="benchmark:raft") + + >>> # Related to the dataset + >>> new_filter = ModelFilter(trained_dataset="common_voice") + ``` + """ + + author: Optional[str] = None + library: Optional[Union[str, List[str]]] = None + language: Optional[Union[str, List[str]]] = None + model_name: Optional[str] = None + task: Optional[Union[str, List[str]]] = None + trained_dataset: Optional[Union[str, List[str]]] = None + tags: Optional[Union[str, List[str]]] = None diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/insecure_hashlib.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/insecure_hashlib.py new file mode 100644 index 0000000000000000000000000000000000000000..f232ee0adcfc52dcc18b5ea4d9c913b206521f71 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/insecure_hashlib.py @@ -0,0 +1,34 @@ +# Taken from https://github.com/mlflow/mlflow/pull/10119 +# +# DO NOT use this function for security purposes (e.g., password hashing). +# +# In Python >= 3.9, insecure hashing algorithms such as MD5 fail in FIPS-compliant +# environments unless `usedforsecurity=False` is explicitly passed. +# +# References: +# - https://github.com/mlflow/mlflow/issues/9905 +# - https://github.com/mlflow/mlflow/pull/10119 +# - https://docs.python.org/3/library/hashlib.html +# - https://github.com/huggingface/transformers/pull/27038 +# +# Usage: +# ```python +# # Use +# from huggingface_hub.utils.insecure_hashlib import sha256 +# # instead of +# from hashlib import sha256 +# +# # Use +# from huggingface_hub.utils import insecure_hashlib +# # instead of +# import hashlib +# ``` +import functools +import hashlib +import sys + + +_kwargs = {"usedforsecurity": False} if sys.version_info >= (3, 9) else {} +md5 = functools.partial(hashlib.md5, **_kwargs) +sha1 = functools.partial(hashlib.sha1, **_kwargs) +sha256 = functools.partial(hashlib.sha256, **_kwargs) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/logging.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/logging.py new file mode 100644 index 0000000000000000000000000000000000000000..dc4d6a00542e14a2a9d0764f52968e3e258dc593 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/logging.py @@ -0,0 +1,182 @@ +# coding=utf-8 +# Copyright 2020 Optuna, Hugging Face +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" Logging utilities.""" + +import logging +import os +from logging import ( + CRITICAL, # NOQA + DEBUG, # NOQA + ERROR, # NOQA + FATAL, # NOQA + INFO, # NOQA + NOTSET, # NOQA + WARN, # NOQA + WARNING, # NOQA +) +from typing import Optional + + +log_levels = { + "debug": logging.DEBUG, + "info": logging.INFO, + "warning": logging.WARNING, + "error": logging.ERROR, + "critical": logging.CRITICAL, +} + +_default_log_level = logging.WARNING + + +def _get_library_name() -> str: + return __name__.split(".")[0] + + +def _get_library_root_logger() -> logging.Logger: + return logging.getLogger(_get_library_name()) + + +def _get_default_logging_level(): + """ + If `HF_HUB_VERBOSITY` env var is set to one of the valid choices return that as the new default level. If it is not + - fall back to `_default_log_level` + """ + env_level_str = os.getenv("HF_HUB_VERBOSITY", None) + if env_level_str: + if env_level_str in log_levels: + return log_levels[env_level_str] + else: + logging.getLogger().warning( + f"Unknown option HF_HUB_VERBOSITY={env_level_str}, has to be one of: { ', '.join(log_levels.keys()) }" + ) + return _default_log_level + + +def _configure_library_root_logger() -> None: + library_root_logger = _get_library_root_logger() + library_root_logger.addHandler(logging.StreamHandler()) + library_root_logger.setLevel(_get_default_logging_level()) + + +def _reset_library_root_logger() -> None: + library_root_logger = _get_library_root_logger() + library_root_logger.setLevel(logging.NOTSET) + + +def get_logger(name: Optional[str] = None) -> logging.Logger: + """ + Returns a logger with the specified name. This function is not supposed + to be directly accessed by library users. + + Args: + name (`str`, *optional*): + The name of the logger to get, usually the filename + + Example: + + ```python + >>> from huggingface_hub import get_logger + + >>> logger = get_logger(__file__) + >>> logger.set_verbosity_info() + ``` + """ + + if name is None: + name = _get_library_name() + + return logging.getLogger(name) + + +def get_verbosity() -> int: + """Return the current level for the HuggingFace Hub's root logger. + + Returns: + Logging level, e.g., `huggingface_hub.logging.DEBUG` and + `huggingface_hub.logging.INFO`. + + + + HuggingFace Hub has following logging levels: + + - `huggingface_hub.logging.CRITICAL`, `huggingface_hub.logging.FATAL` + - `huggingface_hub.logging.ERROR` + - `huggingface_hub.logging.WARNING`, `huggingface_hub.logging.WARN` + - `huggingface_hub.logging.INFO` + - `huggingface_hub.logging.DEBUG` + + + """ + return _get_library_root_logger().getEffectiveLevel() + + +def set_verbosity(verbosity: int) -> None: + """ + Sets the level for the HuggingFace Hub's root logger. + + Args: + verbosity (`int`): + Logging level, e.g., `huggingface_hub.logging.DEBUG` and + `huggingface_hub.logging.INFO`. + """ + _get_library_root_logger().setLevel(verbosity) + + +def set_verbosity_info(): + """ + Sets the verbosity to `logging.INFO`. + """ + return set_verbosity(INFO) + + +def set_verbosity_warning(): + """ + Sets the verbosity to `logging.WARNING`. + """ + return set_verbosity(WARNING) + + +def set_verbosity_debug(): + """ + Sets the verbosity to `logging.DEBUG`. + """ + return set_verbosity(DEBUG) + + +def set_verbosity_error(): + """ + Sets the verbosity to `logging.ERROR`. + """ + return set_verbosity(ERROR) + + +def disable_propagation() -> None: + """ + Disable propagation of the library log outputs. Note that log propagation is + disabled by default. + """ + _get_library_root_logger().propagate = False + + +def enable_propagation() -> None: + """ + Enable propagation of the library log outputs. Please disable the + HuggingFace Hub's default handler to prevent double logging if the root + logger has been configured. + """ + _get_library_root_logger().propagate = True + + +_configure_library_root_logger() diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/sha.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/sha.py new file mode 100644 index 0000000000000000000000000000000000000000..adab93512428ce5fc0a1675c8353d4ee27ff89fe --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/sha.py @@ -0,0 +1,28 @@ +"""Utilities to efficiently compute the SHA 256 hash of a bunch of bytes.""" +from typing import BinaryIO, Optional + +from .insecure_hashlib import sha256 + + +def sha_fileobj(fileobj: BinaryIO, chunk_size: Optional[int] = None) -> bytes: + """ + Computes the sha256 hash of the given file object, by chunks of size `chunk_size`. + + Args: + fileobj (file-like object): + The File object to compute sha256 for, typically obtained with `open(path, "rb")` + chunk_size (`int`, *optional*): + The number of bytes to read from `fileobj` at once, defaults to 1MB. + + Returns: + `bytes`: `fileobj`'s sha256 hash as bytes + """ + chunk_size = chunk_size if chunk_size is not None else 1024 * 1024 + + sha = sha256() + while True: + chunk = fileobj.read(chunk_size) + sha.update(chunk) + if not chunk: + break + return sha.digest() diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/tqdm.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/tqdm.py new file mode 100644 index 0000000000000000000000000000000000000000..cae9adb389a6e3777ce0fb2e5f0156b4746dbd3d --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/huggingface_hub/utils/tqdm.py @@ -0,0 +1,186 @@ +#!/usr/bin/env python +# coding=utf-8 +# Copyright 2021 The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License +"""Utility helpers to handle progress bars in `huggingface_hub`. + +Example: + 1. Use `huggingface_hub.utils.tqdm` as you would use `tqdm.tqdm` or `tqdm.auto.tqdm`. + 2. To disable progress bars, either use `disable_progress_bars()` helper or set the + environment variable `HF_HUB_DISABLE_PROGRESS_BARS` to 1. + 3. To re-enable progress bars, use `enable_progress_bars()`. + 4. To check whether progress bars are disabled, use `are_progress_bars_disabled()`. + +NOTE: Environment variable `HF_HUB_DISABLE_PROGRESS_BARS` has the priority. + +Example: + ```py + from huggingface_hub.utils import ( + are_progress_bars_disabled, + disable_progress_bars, + enable_progress_bars, + tqdm, + ) + + # Disable progress bars globally + disable_progress_bars() + + # Use as normal `tqdm` + for _ in tqdm(range(5)): + do_something() + + # Still not showing progress bars, as `disable=False` is overwritten to `True`. + for _ in tqdm(range(5), disable=False): + do_something() + + are_progress_bars_disabled() # True + + # Re-enable progress bars globally + enable_progress_bars() + + # Progress bar will be shown ! + for _ in tqdm(range(5)): + do_something() + ``` +""" +import io +import warnings +from contextlib import contextmanager +from pathlib import Path +from typing import Iterator, Optional, Union + +from tqdm.auto import tqdm as old_tqdm + +from ..constants import HF_HUB_DISABLE_PROGRESS_BARS + + +# `HF_HUB_DISABLE_PROGRESS_BARS` is `Optional[bool]` while `_hf_hub_progress_bars_disabled` +# is a `bool`. If `HF_HUB_DISABLE_PROGRESS_BARS` is set to True or False, it has priority. +# If `HF_HUB_DISABLE_PROGRESS_BARS` is None, it means the user have not set the +# environment variable and is free to enable/disable progress bars programmatically. +# TL;DR: env variable has priority over code. +# +# By default, progress bars are enabled. +_hf_hub_progress_bars_disabled: bool = HF_HUB_DISABLE_PROGRESS_BARS or False + + +def disable_progress_bars() -> None: + """ + Disable globally progress bars used in `huggingface_hub` except if `HF_HUB_DISABLE_PROGRESS_BARS` environment + variable has been set. + + Use [`~utils.enable_progress_bars`] to re-enable them. + """ + if HF_HUB_DISABLE_PROGRESS_BARS is False: + warnings.warn( + "Cannot disable progress bars: environment variable `HF_HUB_DISABLE_PROGRESS_BARS=0` is set and has" + " priority." + ) + return + global _hf_hub_progress_bars_disabled + _hf_hub_progress_bars_disabled = True + + +def enable_progress_bars() -> None: + """ + Enable globally progress bars used in `huggingface_hub` except if `HF_HUB_DISABLE_PROGRESS_BARS` environment + variable has been set. + + Use [`~utils.disable_progress_bars`] to disable them. + """ + if HF_HUB_DISABLE_PROGRESS_BARS is True: + warnings.warn( + "Cannot enable progress bars: environment variable `HF_HUB_DISABLE_PROGRESS_BARS=1` is set and has" + " priority." + ) + return + global _hf_hub_progress_bars_disabled + _hf_hub_progress_bars_disabled = False + + +def are_progress_bars_disabled() -> bool: + """Return whether progress bars are globally disabled or not. + + Progress bars used in `huggingface_hub` can be enable or disabled globally using [`~utils.enable_progress_bars`] + and [`~utils.disable_progress_bars`] or by setting `HF_HUB_DISABLE_PROGRESS_BARS` as environment variable. + """ + global _hf_hub_progress_bars_disabled + return _hf_hub_progress_bars_disabled + + +class tqdm(old_tqdm): + """ + Class to override `disable` argument in case progress bars are globally disabled. + + Taken from https://github.com/tqdm/tqdm/issues/619#issuecomment-619639324. + """ + + def __init__(self, *args, **kwargs): + if are_progress_bars_disabled(): + kwargs["disable"] = True + super().__init__(*args, **kwargs) + + def __delattr__(self, attr: str) -> None: + """Fix for https://github.com/huggingface/huggingface_hub/issues/1603""" + try: + super().__delattr__(attr) + except AttributeError: + if attr != "_lock": + raise + + +@contextmanager +def tqdm_stream_file(path: Union[Path, str]) -> Iterator[io.BufferedReader]: + """ + Open a file as binary and wrap the `read` method to display a progress bar when it's streamed. + + First implemented in `transformers` in 2019 but removed when switched to git-lfs. Used in `huggingface_hub` to show + progress bar when uploading an LFS file to the Hub. See github.com/huggingface/transformers/pull/2078#discussion_r354739608 + for implementation details. + + Note: currently implementation handles only files stored on disk as it is the most common use case. Could be + extended to stream any `BinaryIO` object but we might have to debug some corner cases. + + Example: + ```py + >>> with tqdm_stream_file("config.json") as f: + >>> requests.put(url, data=f) + config.json: 100%|█████████████████████████| 8.19k/8.19k [00:02<00:00, 3.72kB/s] + ``` + """ + if isinstance(path, str): + path = Path(path) + + with path.open("rb") as f: + total_size = path.stat().st_size + pbar = tqdm( + unit="B", + unit_scale=True, + total=total_size, + initial=0, + desc=path.name, + ) + + f_read = f.read + + def _inner_read(size: Optional[int] = -1) -> bytes: + data = f_read(size) + pbar.update(len(data)) + return data + + f.read = _inner_read # type: ignore + + yield f + + pbar.close() diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d4a765f30fdd1c9ab471dcc447f0f3127e656ae1 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/__pycache__/__main__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/__pycache__/__main__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a8767838067183a524d93472353f994396a56596 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/__pycache__/__main__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/__pycache__/exceptions.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/__pycache__/exceptions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..87d0a088e5460ef954ff043c8ac3934641dabf28 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/__pycache__/exceptions.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/__pycache__/localization.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/__pycache__/localization.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f3d35bbe954f8bea3e2eb128e43398508a358e66 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/__pycache__/localization.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/__pycache__/plugins.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/__pycache__/plugins.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac93cdbc2f57667449058e7eccf386f50d9ba26e Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/__pycache__/plugins.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/__pycache__/theme.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/__pycache__/theme.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4a406088d33448ddb54ec49bab5d6ae0e4f2d1cf Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/__pycache__/theme.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/commands/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/commands/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/commands/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/commands/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e98a4db9057d39e7b74ef6f689e282d961021e89 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/commands/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/commands/__pycache__/build.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/commands/__pycache__/build.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..753336456d3d3cffaa2b6eabede68ae9a140cc42 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/commands/__pycache__/build.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/commands/__pycache__/get_deps.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/commands/__pycache__/get_deps.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d9697d4d030dd653abad86249a510c9628afbc0 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/commands/__pycache__/get_deps.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/commands/__pycache__/gh_deploy.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/commands/__pycache__/gh_deploy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..64047c77f6fd436618a96aa8747dbcd1c653f75f Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/commands/__pycache__/gh_deploy.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/commands/__pycache__/new.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/commands/__pycache__/new.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..022aa182ff2a4958ec4e3d3e07e746bcbd53e64b Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/commands/__pycache__/new.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/commands/__pycache__/serve.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/commands/__pycache__/serve.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..365ac82b06fe990bd548f1efddb0ab2e91c903fb Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/commands/__pycache__/serve.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/commands/build.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/commands/build.py new file mode 100644 index 0000000000000000000000000000000000000000..4596464405b166f31081703c2064ef2a7c65d85a --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/commands/build.py @@ -0,0 +1,378 @@ +from __future__ import annotations + +import gzip +import logging +import os +import time +from typing import TYPE_CHECKING, Sequence +from urllib.parse import urljoin, urlsplit + +import jinja2 +from jinja2.exceptions import TemplateNotFound + +import mkdocs +from mkdocs import utils +from mkdocs.exceptions import Abort, BuildError +from mkdocs.structure.files import File, Files, InclusionLevel, _set_exclusions, get_files +from mkdocs.structure.nav import Navigation, get_navigation +from mkdocs.structure.pages import Page +from mkdocs.utils import DuplicateFilter # noqa: F401 - legacy re-export +from mkdocs.utils import templates + +if TYPE_CHECKING: + from mkdocs.config.defaults import MkDocsConfig + +if TYPE_CHECKING: + from mkdocs.livereload import LiveReloadServer + +log = logging.getLogger(__name__) + + +def get_context( + nav: Navigation, + files: Sequence[File] | Files, + config: MkDocsConfig, + page: Page | None = None, + base_url: str = '', +) -> templates.TemplateContext: + """ + Return the template context for a given page or template. + """ + if page is not None: + base_url = utils.get_relative_url('.', page.url) + + extra_javascript = [ + utils.normalize_url(str(script), page, base_url) for script in config.extra_javascript + ] + extra_css = [utils.normalize_url(path, page, base_url) for path in config.extra_css] + + if isinstance(files, Files): + files = files.documentation_pages() + + return templates.TemplateContext( + nav=nav, + pages=files, + base_url=base_url, + extra_css=extra_css, + extra_javascript=extra_javascript, + mkdocs_version=mkdocs.__version__, + build_date_utc=utils.get_build_datetime(), + config=config, + page=page, + ) + + +def _build_template( + name: str, template: jinja2.Template, files: Files, config: MkDocsConfig, nav: Navigation +) -> str: + """ + Return rendered output for given template as a string. + """ + # Run `pre_template` plugin events. + template = config.plugins.on_pre_template(template, template_name=name, config=config) + + if utils.is_error_template(name): + # Force absolute URLs in the nav of error pages and account for the + # possibility that the docs root might be different than the server root. + # See https://github.com/mkdocs/mkdocs/issues/77. + # However, if site_url is not set, assume the docs root and server root + # are the same. See https://github.com/mkdocs/mkdocs/issues/1598. + base_url = urlsplit(config.site_url or '/').path + else: + base_url = utils.get_relative_url('.', name) + + context = get_context(nav, files, config, base_url=base_url) + + # Run `template_context` plugin events. + context = config.plugins.on_template_context(context, template_name=name, config=config) + + output = template.render(context) + + # Run `post_template` plugin events. + output = config.plugins.on_post_template(output, template_name=name, config=config) + + return output + + +def _build_theme_template( + template_name: str, env: jinja2.Environment, files: Files, config: MkDocsConfig, nav: Navigation +) -> None: + """Build a template using the theme environment.""" + + log.debug(f"Building theme template: {template_name}") + + try: + template = env.get_template(template_name) + except TemplateNotFound: + log.warning(f"Template skipped: '{template_name}' not found in theme directories.") + return + + output = _build_template(template_name, template, files, config, nav) + + if output.strip(): + output_path = os.path.join(config.site_dir, template_name) + utils.write_file(output.encode('utf-8'), output_path) + + if template_name == 'sitemap.xml': + log.debug(f"Gzipping template: {template_name}") + gz_filename = f'{output_path}.gz' + with open(gz_filename, 'wb') as f: + timestamp = utils.get_build_timestamp() + with gzip.GzipFile( + fileobj=f, filename=gz_filename, mode='wb', mtime=timestamp + ) as gz_buf: + gz_buf.write(output.encode('utf-8')) + else: + log.info(f"Template skipped: '{template_name}' generated empty output.") + + +def _build_extra_template(template_name: str, files: Files, config: MkDocsConfig, nav: Navigation): + """Build user templates which are not part of the theme.""" + + log.debug(f"Building extra template: {template_name}") + + file = files.get_file_from_path(template_name) + if file is None: + log.warning(f"Template skipped: '{template_name}' not found in docs_dir.") + return + + try: + with open(file.abs_src_path, encoding='utf-8', errors='strict') as f: + template = jinja2.Template(f.read()) + except Exception as e: + log.warning(f"Error reading template '{template_name}': {e}") + return + + output = _build_template(template_name, template, files, config, nav) + + if output.strip(): + utils.write_file(output.encode('utf-8'), file.abs_dest_path) + else: + log.info(f"Template skipped: '{template_name}' generated empty output.") + + +def _populate_page(page: Page, config: MkDocsConfig, files: Files, dirty: bool = False) -> None: + """Read page content from docs_dir and render Markdown.""" + + config._current_page = page + try: + # When --dirty is used, only read the page if the file has been modified since the + # previous build of the output. + if dirty and not page.file.is_modified(): + return + + # Run the `pre_page` plugin event + page = config.plugins.on_pre_page(page, config=config, files=files) + + page.read_source(config) + assert page.markdown is not None + + # Run `page_markdown` plugin events. + page.markdown = config.plugins.on_page_markdown( + page.markdown, page=page, config=config, files=files + ) + + page.render(config, files) + assert page.content is not None + + # Run `page_content` plugin events. + page.content = config.plugins.on_page_content( + page.content, page=page, config=config, files=files + ) + except Exception as e: + message = f"Error reading page '{page.file.src_uri}':" + # Prevent duplicated the error message because it will be printed immediately afterwards. + if not isinstance(e, BuildError): + message += f" {e}" + log.error(message) + raise + finally: + config._current_page = None + + +def _build_page( + page: Page, + config: MkDocsConfig, + doc_files: Sequence[File], + nav: Navigation, + env: jinja2.Environment, + dirty: bool = False, + excluded: bool = False, +) -> None: + """Pass a Page to theme template and write output to site_dir.""" + + config._current_page = page + try: + # When --dirty is used, only build the page if the file has been modified since the + # previous build of the output. + if dirty and not page.file.is_modified(): + return + + log.debug(f"Building page {page.file.src_uri}") + + # Activate page. Signals to theme that this is the current page. + page.active = True + + context = get_context(nav, doc_files, config, page) + + # Allow 'template:' override in md source files. + template = env.get_template(page.meta.get('template', 'main.html')) + + # Run `page_context` plugin events. + context = config.plugins.on_page_context(context, page=page, config=config, nav=nav) + + if excluded: + page.content = ( + '
' + 'DRAFT' + '
' + (page.content or '') + ) + + # Render the template. + output = template.render(context) + + # Run `post_page` plugin events. + output = config.plugins.on_post_page(output, page=page, config=config) + + # Write the output file. + if output.strip(): + utils.write_file( + output.encode('utf-8', errors='xmlcharrefreplace'), page.file.abs_dest_path + ) + else: + log.info(f"Page skipped: '{page.file.src_uri}'. Generated empty output.") + + except Exception as e: + message = f"Error building page '{page.file.src_uri}':" + # Prevent duplicated the error message because it will be printed immediately afterwards. + if not isinstance(e, BuildError): + message += f" {e}" + log.error(message) + raise + finally: + # Deactivate page + page.active = False + config._current_page = None + + +def build( + config: MkDocsConfig, live_server: LiveReloadServer | None = None, dirty: bool = False +) -> None: + """Perform a full site build.""" + + logger = logging.getLogger('mkdocs') + + # Add CountHandler for strict mode + warning_counter = utils.CountHandler() + warning_counter.setLevel(logging.WARNING) + if config.strict: + logging.getLogger('mkdocs').addHandler(warning_counter) + + inclusion = InclusionLevel.all if live_server else InclusionLevel.is_included + + try: + start = time.monotonic() + + # Run `config` plugin events. + config = config.plugins.on_config(config) + + # Run `pre_build` plugin events. + config.plugins.on_pre_build(config=config) + + if not dirty: + log.info("Cleaning site directory") + utils.clean_directory(config.site_dir) + else: # pragma: no cover + # Warn user about problems that may occur with --dirty option + log.warning( + "A 'dirty' build is being performed, this will likely lead to inaccurate navigation and other" + " links within your site. This option is designed for site development purposes only." + ) + + if not live_server: # pragma: no cover + log.info(f"Building documentation to directory: {config.site_dir}") + if dirty and site_directory_contains_stale_files(config.site_dir): + log.info("The directory contains stale files. Use --clean to remove them.") + + # First gather all data from all files/pages to ensure all data is consistent across all pages. + + files = get_files(config) + env = config.theme.get_env() + files.add_files_from_theme(env, config) + + # Run `files` plugin events. + files = config.plugins.on_files(files, config=config) + # If plugins have added files but haven't set their inclusion level, calculate it again. + _set_exclusions(files._files, config) + + nav = get_navigation(files, config) + + # Run `nav` plugin events. + nav = config.plugins.on_nav(nav, config=config, files=files) + + log.debug("Reading markdown pages.") + excluded = [] + for file in files.documentation_pages(inclusion=inclusion): + log.debug(f"Reading: {file.src_uri}") + if file.page is None and file.inclusion.is_excluded(): + if live_server: + excluded.append(urljoin(live_server.url, file.url)) + Page(None, file, config) + assert file.page is not None + _populate_page(file.page, config, files, dirty) + if excluded: + log.info( + "The following pages are being built only for the preview " + "but will be excluded from `mkdocs build` per `exclude_docs`:\n - " + + "\n - ".join(excluded) + ) + + # Run `env` plugin events. + env = config.plugins.on_env(env, config=config, files=files) + + # Start writing files to site_dir now that all data is gathered. Note that order matters. Files + # with lower precedence get written first so that files with higher precedence can overwrite them. + + log.debug("Copying static assets.") + files.copy_static_files(dirty=dirty, inclusion=inclusion) + + for template in config.theme.static_templates: + _build_theme_template(template, env, files, config, nav) + + for template in config.extra_templates: + _build_extra_template(template, files, config, nav) + + log.debug("Building markdown pages.") + doc_files = files.documentation_pages(inclusion=inclusion) + for file in doc_files: + assert file.page is not None + _build_page( + file.page, config, doc_files, nav, env, dirty, excluded=file.inclusion.is_excluded() + ) + + # Run `post_build` plugin events. + config.plugins.on_post_build(config=config) + + counts = warning_counter.get_counts() + if counts: + msg = ', '.join(f'{v} {k.lower()}s' for k, v in counts) + raise Abort(f'Aborted with {msg} in strict mode!') + + log.info(f'Documentation built in {time.monotonic() - start:.2f} seconds') + + except Exception as e: + # Run `build_error` plugin events. + config.plugins.on_build_error(error=e) + if isinstance(e, BuildError): + log.error(str(e)) + raise Abort('Aborted with a BuildError!') + raise + + finally: + logger.removeHandler(warning_counter) + + +def site_directory_contains_stale_files(site_directory: str) -> bool: + """Check if the site directory contains stale files from a previous build.""" + + return bool(os.path.exists(site_directory) and os.listdir(site_directory)) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/commands/get_deps.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/commands/get_deps.py new file mode 100644 index 0000000000000000000000000000000000000000..0d2e1c3928dae62490746dd4d390e6138904f7a9 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/commands/get_deps.py @@ -0,0 +1,178 @@ +from __future__ import annotations + +import dataclasses +import datetime +import functools +import logging +import sys +from typing import Mapping, Sequence + +if sys.version_info >= (3, 10): + from importlib.metadata import EntryPoint, entry_points +else: + from importlib_metadata import EntryPoint, entry_points + +import yaml + +from mkdocs import utils +from mkdocs.config.base import _open_config_file +from mkdocs.utils.cache import download_and_cache_url + +log = logging.getLogger(__name__) + +# Note: do not rely on functions in this module, it is not public API. + + +class YamlLoader(yaml.SafeLoader): + pass + + +# Prevent errors from trying to access external modules which may not be installed yet. +YamlLoader.add_constructor("!ENV", lambda loader, node: None) # type: ignore +YamlLoader.add_constructor("!relative", lambda loader, node: None) # type: ignore +YamlLoader.add_multi_constructor( + "tag:yaml.org,2002:python/name:", lambda loader, suffix, node: None +) +YamlLoader.add_multi_constructor( + "tag:yaml.org,2002:python/object/apply:", lambda loader, suffix, node: None +) + +NotFound = () + + +def dig(cfg, keys: str): + """Receives a string such as 'foo.bar' and returns `cfg['foo']['bar']`, or `NotFound`. + + A list of single-item dicts gets converted to a flat dict. This is intended for `plugins` config. + """ + key, _, rest = keys.partition('.') + try: + cfg = cfg[key] + except (KeyError, TypeError): + return NotFound + if isinstance(cfg, list): + orig_cfg = cfg + cfg = {} + for item in reversed(orig_cfg): + if isinstance(item, dict) and len(item) == 1: + cfg.update(item) + elif isinstance(item, str): + cfg[item] = {} + if not rest: + return cfg + return dig(cfg, rest) + + +def strings(obj) -> Sequence[str]: + if isinstance(obj, str): + return (obj,) + else: + return tuple(obj) + + +@functools.lru_cache() +def _entry_points(group: str) -> Mapping[str, EntryPoint]: + eps = {ep.name: ep for ep in entry_points(group=group)} + log.debug(f"Available '{group}' entry points: {sorted(eps)}") + return eps + + +@dataclasses.dataclass(frozen=True) +class PluginKind: + projects_key: str + entry_points_key: str + + def __str__(self) -> str: + return self.projects_key.rpartition('_')[-1] + + +def get_deps(projects_file_url: str, config_file_path: str | None = None) -> None: + """ + Print PyPI package dependencies inferred from a mkdocs.yml file based on a reverse mapping of known projects. + + Parameters: + projects_file_url: URL or local path of the registry file that declares all known MkDocs-related projects. + The file is in YAML format and contains `projects: [{mkdocs_theme:, mkdocs_plugin:, markdown_extension:}] + config_file_path: Non-default path to mkdocs.yml. + """ + with _open_config_file(config_file_path) as f: + cfg = utils.yaml_load(f, loader=YamlLoader) # type: ignore + + packages_to_install = set() + + if all(c not in cfg for c in ('site_name', 'theme', 'plugins', 'markdown_extensions')): + log.warning("The passed config file doesn't seem to be a mkdocs.yml config file") + else: + if dig(cfg, 'theme.locale') not in (NotFound, 'en'): + packages_to_install.add('mkdocs[i18n]') + else: + packages_to_install.add('mkdocs') + + try: + theme = cfg['theme']['name'] + except (KeyError, TypeError): + theme = cfg.get('theme') + themes = {theme} if theme else set() + + plugins = set(strings(dig(cfg, 'plugins'))) + extensions = set(strings(dig(cfg, 'markdown_extensions'))) + + wanted_plugins = ( + (PluginKind('mkdocs_theme', 'mkdocs.themes'), themes - {'mkdocs', 'readthedocs'}), + (PluginKind('mkdocs_plugin', 'mkdocs.plugins'), plugins - {'search'}), + (PluginKind('markdown_extension', 'markdown.extensions'), extensions), + ) + for kind, wanted in wanted_plugins: + log.debug(f'Wanted {kind}s: {sorted(wanted)}') + + content = download_and_cache_url(projects_file_url, datetime.timedelta(days=7)) + projects = yaml.safe_load(content)['projects'] + + for project in projects: + for kind, wanted in wanted_plugins: + available = strings(project.get(kind.projects_key, ())) + for entry_name in available: + if ( # Also check theme-namespaced plugin names against the current theme. + '/' in entry_name + and theme is not None + and kind.projects_key == 'mkdocs_plugin' + and entry_name.startswith(f'{theme}/') + and entry_name[len(theme) + 1 :] in wanted + and entry_name not in wanted + ): + entry_name = entry_name[len(theme) + 1 :] + if entry_name in wanted: + if 'pypi_id' in project: + install_name = project['pypi_id'] + elif 'github_id' in project: + install_name = 'git+https://github.com/{github_id}'.format_map(project) + else: + log.error( + f"Can't find how to install {kind} '{entry_name}' although it was identified as {project}" + ) + continue + packages_to_install.add(install_name) + for extra_key, extra_pkgs in project.get('extra_dependencies', {}).items(): + if dig(cfg, extra_key) is not NotFound: + packages_to_install.update(strings(extra_pkgs)) + + wanted.remove(entry_name) + + for kind, wanted in wanted_plugins: + for entry_name in sorted(wanted): + dist_name = None + ep = _entry_points(kind.entry_points_key).get(entry_name) + if ep is not None and ep.dist is not None: + dist_name = ep.dist.name + if dist_name not in ('mkdocs', 'Markdown'): + warning = f"{str(kind).capitalize()} '{entry_name}' is not provided by any registered project" + if ep is not None: + warning += " but is installed locally" + if dist_name: + warning += f" from '{dist_name}'" + log.info(warning) + else: + log.warning(warning) + + for pkg in sorted(packages_to_install): + print(pkg) # noqa: T201 diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/commands/gh_deploy.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/commands/gh_deploy.py new file mode 100644 index 0000000000000000000000000000000000000000..f6e5fa05f1366a7b75f01aec6f19af0d252b71e2 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/commands/gh_deploy.py @@ -0,0 +1,169 @@ +from __future__ import annotations + +import logging +import os +import re +import subprocess +from typing import TYPE_CHECKING + +import ghp_import +from packaging import version + +import mkdocs +from mkdocs.exceptions import Abort + +if TYPE_CHECKING: + from mkdocs.config.defaults import MkDocsConfig + +log = logging.getLogger(__name__) + +default_message = """Deployed {sha} with MkDocs version: {version}""" + + +def _is_cwd_git_repo() -> bool: + try: + proc = subprocess.Popen( + ['git', 'rev-parse', '--is-inside-work-tree'], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + ) + except FileNotFoundError: + log.error("Could not find git - is it installed and on your path?") + raise Abort('Deployment Aborted!') + proc.communicate() + return proc.wait() == 0 + + +def _get_current_sha(repo_path) -> str: + proc = subprocess.Popen( + ['git', 'rev-parse', '--short', 'HEAD'], + cwd=repo_path or None, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + ) + + stdout, _ = proc.communicate() + sha = stdout.decode('utf-8').strip() + return sha + + +def _get_remote_url(remote_name: str) -> tuple[str, str] | tuple[None, None]: + # No CNAME found. We will use the origin URL to determine the GitHub + # Pages location. + remote = f"remote.{remote_name}.url" + proc = subprocess.Popen( + ["git", "config", "--get", remote], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + ) + + stdout, _ = proc.communicate() + url = stdout.decode('utf-8').strip() + + if 'github.com/' in url: + host, path = url.split('github.com/', 1) + elif 'github.com:' in url: + host, path = url.split('github.com:', 1) + else: + return None, None + return host, path + + +def _check_version(branch: str) -> None: + proc = subprocess.Popen( + ['git', 'show', '-s', '--format=%s', f'refs/heads/{branch}'], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + ) + + stdout, _ = proc.communicate() + msg = stdout.decode('utf-8').strip() + m = re.search(r'\d+(\.\d+)+((a|b|rc)\d+)?(\.post\d+)?(\.dev\d+)?', msg, re.X | re.I) + previousv = version.parse(m.group()) if m else None + currentv = version.parse(mkdocs.__version__) + if not previousv: + log.warning('Version check skipped: No version specified in previous deployment.') + elif currentv > previousv: + log.info( + f'Previous deployment was done with MkDocs version {previousv}; ' + f'you are deploying with a newer version ({currentv})' + ) + elif currentv < previousv: + log.error( + f'Deployment terminated: Previous deployment was made with MkDocs version {previousv}; ' + f'you are attempting to deploy with an older version ({currentv}). Use --ignore-version ' + 'to deploy anyway.' + ) + raise Abort('Deployment Aborted!') + + +def gh_deploy( + config: MkDocsConfig, + message: str | None = None, + force=False, + no_history=False, + ignore_version=False, + shell=False, +) -> None: + if not _is_cwd_git_repo(): + log.error('Cannot deploy - this directory does not appear to be a git repository') + + remote_branch = config.remote_branch + remote_name = config.remote_name + + if not ignore_version: + _check_version(remote_branch) + + if message is None: + message = default_message + sha = _get_current_sha(os.path.dirname(config.config_file_path)) + message = message.format(version=mkdocs.__version__, sha=sha) + + log.info( + "Copying '%s' to '%s' branch and pushing to GitHub.", + config.site_dir, + config.remote_branch, + ) + + try: + ghp_import.ghp_import( + config.site_dir, + mesg=message, + remote=remote_name, + branch=remote_branch, + push=True, + force=force, + use_shell=shell, + no_history=no_history, + nojekyll=True, + ) + except ghp_import.GhpError as e: + log.error(f"Failed to deploy to GitHub with error: \n{e.message}") + raise Abort('Deployment Aborted!') + + cname_file = os.path.join(config.site_dir, 'CNAME') + # Does this repository have a CNAME set for GitHub Pages? + if os.path.isfile(cname_file): + # This GitHub Pages repository has a CNAME configured. + with open(cname_file) as f: + cname_host = f.read().strip() + log.info( + f'Based on your CNAME file, your documentation should be ' + f'available shortly at: http://{cname_host}' + ) + log.info( + 'NOTE: Your DNS records must be configured appropriately for your CNAME URL to work.' + ) + return + + host, path = _get_remote_url(remote_name) + + if host is None or path is None: + # This could be a GitHub Enterprise deployment. + log.info('Your documentation should be available shortly.') + else: + username, repo = path.split('/', 1) + if repo.endswith('.git'): + repo = repo[: -len('.git')] + url = f'https://{username}.github.io/{repo}/' + log.info(f"Your documentation should shortly be available at: {url}") diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/commands/new.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/commands/new.py new file mode 100644 index 0000000000000000000000000000000000000000..38c3068d8fa77c19d5b34059f009466d8d636793 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/commands/new.py @@ -0,0 +1,53 @@ +from __future__ import annotations + +import logging +import os + +config_text = 'site_name: My Docs\n' +index_text = """# Welcome to MkDocs + +For full documentation visit [mkdocs.org](https://www.mkdocs.org). + +## Commands + +* `mkdocs new [dir-name]` - Create a new project. +* `mkdocs serve` - Start the live-reloading docs server. +* `mkdocs build` - Build the documentation site. +* `mkdocs -h` - Print help message and exit. + +## Project layout + + mkdocs.yml # The configuration file. + docs/ + index.md # The documentation homepage. + ... # Other markdown pages, images and other files. +""" + +log = logging.getLogger(__name__) + + +def new(output_dir: str) -> None: + docs_dir = os.path.join(output_dir, 'docs') + config_path = os.path.join(output_dir, 'mkdocs.yml') + index_path = os.path.join(docs_dir, 'index.md') + + if os.path.exists(config_path): + log.info('Project already exists.') + return + + if not os.path.exists(output_dir): + log.info(f'Creating project directory: {output_dir}') + os.mkdir(output_dir) + + log.info(f'Writing config file: {config_path}') + with open(config_path, 'w', encoding='utf-8') as f: + f.write(config_text) + + if os.path.exists(index_path): + return + + log.info(f'Writing initial docs: {index_path}') + if not os.path.exists(docs_dir): + os.mkdir(docs_dir) + with open(index_path, 'w', encoding='utf-8') as f: + f.write(index_text) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/commands/serve.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/commands/serve.py new file mode 100644 index 0000000000000000000000000000000000000000..c5ae98bf7afcc95e4a5af27e11a8efa80bba7852 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/commands/serve.py @@ -0,0 +1,119 @@ +from __future__ import annotations + +import logging +import shutil +import tempfile +from os.path import isdir, isfile, join +from typing import TYPE_CHECKING +from urllib.parse import urlsplit + +import jinja2.exceptions + +from mkdocs.commands.build import build +from mkdocs.config import load_config +from mkdocs.exceptions import Abort +from mkdocs.livereload import LiveReloadServer + +if TYPE_CHECKING: + from mkdocs.config.defaults import MkDocsConfig + +log = logging.getLogger(__name__) + + +def serve( + config_file: str | None = None, + livereload: bool = True, + build_type: str | None = None, + watch_theme: bool = False, + watch: list[str] = [], + **kwargs, +) -> None: + """ + Start the MkDocs development server + + By default it will serve the documentation on http://localhost:8000/ and + it will rebuild the documentation and refresh the page automatically + whenever a file is edited. + """ + # Create a temporary build directory, and set some options to serve it + # PY2 returns a byte string by default. The Unicode prefix ensures a Unicode + # string is returned. And it makes MkDocs temp dirs easier to identify. + site_dir = tempfile.mkdtemp(prefix='mkdocs_') + + def mount_path(config: MkDocsConfig): + return urlsplit(config.site_url or '/').path + + def get_config(): + config = load_config( + config_file=config_file, + site_dir=site_dir, + **kwargs, + ) + config.watch.extend(watch) + config.site_url = f'http://{config.dev_addr}{mount_path(config)}' + return config + + is_clean = build_type == 'clean' + is_dirty = build_type == 'dirty' + + config = get_config() + config.plugins.on_startup(command=('build' if is_clean else 'serve'), dirty=is_dirty) + + def builder(config: MkDocsConfig | None = None): + log.info("Building documentation...") + if config is None: + config = get_config() + + build(config, live_server=None if is_clean else server, dirty=is_dirty) + + host, port = config.dev_addr + server = LiveReloadServer( + builder=builder, host=host, port=port, root=site_dir, mount_path=mount_path(config) + ) + + def error_handler(code) -> bytes | None: + if code in (404, 500): + error_page = join(site_dir, f'{code}.html') + if isfile(error_page): + with open(error_page, 'rb') as f: + return f.read() + return None + + server.error_handler = error_handler + + try: + # Perform the initial build + builder(config) + + if livereload: + # Watch the documentation files, the config file and the theme files. + server.watch(config.docs_dir) + if config.config_file_path: + server.watch(config.config_file_path) + + if watch_theme: + for d in config.theme.dirs: + server.watch(d) + + # Run `serve` plugin events. + server = config.plugins.on_serve(server, config=config, builder=builder) + + for item in config.watch: + server.watch(item) + + try: + server.serve() + except KeyboardInterrupt: + log.info("Shutting down...") + finally: + server.shutdown() + except jinja2.exceptions.TemplateError: + # This is a subclass of OSError, but shouldn't be suppressed. + raise + except OSError as e: # pragma: no cover + # Avoid ugly, unhelpful traceback + raise Abort(f'{type(e).__name__}: {e}') + finally: + config.plugins.on_shutdown() + if isdir(site_dir): + shutil.rmtree(site_dir) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/config/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/config/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3fa69c6bff6bd117b428155ef53d759d8470cec4 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/config/__init__.py @@ -0,0 +1,3 @@ +from mkdocs.config.base import Config, load_config + +__all__ = ['load_config', 'Config'] diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/config/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/config/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..21a47ed9b56c67348c3d68844b0f09bf1cccb921 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/config/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/config/__pycache__/base.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/config/__pycache__/base.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a7698c6e275f2d390da377fb11a7bd0fe113dd1f Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/config/__pycache__/base.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/config/__pycache__/config_options.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/config/__pycache__/config_options.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e2617a27b36f2cd43dfcf6cb5430dc4c94ce1813 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/config/__pycache__/config_options.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/config/__pycache__/defaults.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/config/__pycache__/defaults.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5ceca110a814c4faa8920bb5796d94a76b6c9a02 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/config/__pycache__/defaults.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/config/base.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/config/base.py new file mode 100644 index 0000000000000000000000000000000000000000..cee32e319e0d159949e4f5c68255f6cf080378b4 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/config/base.py @@ -0,0 +1,396 @@ +from __future__ import annotations + +import functools +import logging +import os +import sys +import warnings +from collections import UserDict +from contextlib import contextmanager +from typing import ( + IO, + TYPE_CHECKING, + Any, + Generic, + Iterator, + List, + Mapping, + Sequence, + Tuple, + TypeVar, + overload, +) + +from mkdocs import exceptions, utils +from mkdocs.utils import weak_property + +if TYPE_CHECKING: + from mkdocs.config.defaults import MkDocsConfig + + +log = logging.getLogger('mkdocs.config') + + +T = TypeVar('T') + + +class BaseConfigOption(Generic[T]): + def __init__(self) -> None: + self.warnings: list[str] = [] + self.default = None + + @property + def default(self): + try: + # ensure no mutable values are assigned + return self._default.copy() + except AttributeError: + return self._default + + @default.setter + def default(self, value): + self._default = value + + def validate(self, value: object) -> T: + return self.run_validation(value) + + def reset_warnings(self) -> None: + self.warnings = [] + + def pre_validation(self, config: Config, key_name: str) -> None: + """ + Before all options are validated, perform a pre-validation process. + + The pre-validation process method should be implemented by subclasses. + """ + + def run_validation(self, value: object): + """ + Perform validation for a value. + + The run_validation method should be implemented by subclasses. + """ + return value + + def post_validation(self, config: Config, key_name: str) -> None: + """ + After all options have passed validation, perform a post-validation + process to do any additional changes dependent on other config values. + + The post-validation process method should be implemented by subclasses. + """ + + def __set_name__(self, owner, name): + if name.endswith('_') and not name.startswith('_'): + name = name[:-1] + self._name = name + + @overload + def __get__(self, obj: Config, type=None) -> T: + ... + + @overload + def __get__(self, obj, type=None) -> BaseConfigOption: + ... + + def __get__(self, obj, type=None): + if not isinstance(obj, Config): + return self + return obj[self._name] + + def __set__(self, obj, value: T): + if not isinstance(obj, Config): + raise AttributeError( + f"can't set attribute ({self._name}) because the parent is a {type(obj)} not a {Config}" + ) + obj[self._name] = value + + +class ValidationError(Exception): + """Raised during the validation process of the config on errors.""" + + def __eq__(self, other): + return type(self) is type(other) and str(self) == str(other) + + +PlainConfigSchemaItem = Tuple[str, BaseConfigOption] +PlainConfigSchema = Sequence[PlainConfigSchemaItem] + +ConfigErrors = List[Tuple[str, Exception]] +ConfigWarnings = List[Tuple[str, str]] + + +class Config(UserDict): + """ + Base class for MkDocs configuration, plugin configuration (and sub-configuration) objects. + + It should be subclassed and have `ConfigOption`s defined as attributes. + For examples, see mkdocs/contrib/search/__init__.py and mkdocs/config/defaults.py. + + Behavior as it was prior to MkDocs 1.4 is now handled by LegacyConfig. + """ + + _schema: PlainConfigSchema + config_file_path: str + + def __init_subclass__(cls): + schema = dict(getattr(cls, '_schema', ())) + for attr_name, attr in cls.__dict__.items(): + if isinstance(attr, BaseConfigOption): + schema[getattr(attr, '_name', attr_name)] = attr + cls._schema = tuple(schema.items()) + + for attr_name, attr in cls._schema: + attr.required = True + if getattr(attr, '_legacy_required', None) is not None: + raise TypeError( + f"{cls.__name__}.{attr_name}: " + "Setting 'required' is unsupported in class-based configs. " + "All values are required, or can be wrapped into config_options.Optional" + ) + + def __new__(cls, *args, **kwargs) -> Config: + """Compatibility: allow referring to `LegacyConfig(...)` constructor as `Config(...)`.""" + if cls is Config: + return LegacyConfig(*args, **kwargs) + return super().__new__(cls) + + def __init__(self, config_file_path: str | bytes | None = None): + super().__init__() + self.__user_configs: list[dict] = [] + self.set_defaults() + + self._schema_keys = {k for k, v in self._schema} + # Ensure config_file_path is a Unicode string + if config_file_path is not None and not isinstance(config_file_path, str): + try: + # Assume config_file_path is encoded with the file system encoding. + config_file_path = config_file_path.decode(encoding=sys.getfilesystemencoding()) + except UnicodeDecodeError: + raise ValidationError("config_file_path is not a Unicode string.") + self.config_file_path = config_file_path or '' + + def set_defaults(self) -> None: + """ + Set the base config by going through each validator and getting the + default if it has one. + """ + for key, config_option in self._schema: + self[key] = config_option.default + + def _validate(self) -> tuple[ConfigErrors, ConfigWarnings]: + failed: ConfigErrors = [] + warnings: ConfigWarnings = [] + + for key, config_option in self._schema: + try: + value = self.get(key) + self[key] = config_option.validate(value) + warnings.extend((key, w) for w in config_option.warnings) + config_option.reset_warnings() + except ValidationError as e: + failed.append((key, e)) + + for key in set(self.keys()) - self._schema_keys: + warnings.append((key, f"Unrecognised configuration name: {key}")) + + return failed, warnings + + def _pre_validate(self) -> tuple[ConfigErrors, ConfigWarnings]: + failed: ConfigErrors = [] + warnings: ConfigWarnings = [] + + for key, config_option in self._schema: + try: + config_option.pre_validation(self, key_name=key) + warnings.extend((key, w) for w in config_option.warnings) + config_option.reset_warnings() + except ValidationError as e: + failed.append((key, e)) + + return failed, warnings + + def _post_validate(self) -> tuple[ConfigErrors, ConfigWarnings]: + failed: ConfigErrors = [] + warnings: ConfigWarnings = [] + + for key, config_option in self._schema: + try: + config_option.post_validation(self, key_name=key) + warnings.extend((key, w) for w in config_option.warnings) + config_option.reset_warnings() + except ValidationError as e: + failed.append((key, e)) + + return failed, warnings + + def validate(self) -> tuple[ConfigErrors, ConfigWarnings]: + failed, warnings = self._pre_validate() + + run_failed, run_warnings = self._validate() + + failed.extend(run_failed) + warnings.extend(run_warnings) + + # Only run the post validation steps if there are no failures, warnings + # are okay. + if len(failed) == 0: + post_failed, post_warnings = self._post_validate() + failed.extend(post_failed) + warnings.extend(post_warnings) + + return failed, warnings + + def load_dict(self, patch: dict) -> None: + """Load config options from a dictionary.""" + + if not isinstance(patch, dict): + raise exceptions.ConfigurationError( + "The configuration is invalid. Expected a key-" + f"value mapping (dict) but received: {type(patch)}" + ) + + self.__user_configs.append(patch) + self.update(patch) + + def load_file(self, config_file: IO) -> None: + """Load config options from the open file descriptor of a YAML file.""" + warnings.warn( + "Config.load_file is not used since MkDocs 1.5 and will be removed soon. " + "Use MkDocsConfig.load_file instead", + DeprecationWarning, + ) + return self.load_dict(utils.yaml_load(config_file)) + + @weak_property + def user_configs(self) -> Sequence[Mapping[str, Any]]: + warnings.warn( + "user_configs is never used in MkDocs and will be removed soon.", DeprecationWarning + ) + return self.__user_configs + + +@functools.lru_cache(maxsize=None) +def get_schema(cls: type) -> PlainConfigSchema: + """ + Extract ConfigOptions defined in a class (used just as a container) and put them into a schema tuple. + """ + if issubclass(cls, Config): + return cls._schema + return tuple((k, v) for k, v in cls.__dict__.items() if isinstance(v, BaseConfigOption)) + + +class LegacyConfig(Config): + """ + A configuration object for plugins, as just a dict without type-safe attribute access. + """ + + def __init__(self, schema: PlainConfigSchema, config_file_path: str | None = None): + self._schema = tuple((k, v) for k, v in schema) # Re-create just for validation + super().__init__(config_file_path) + + +@contextmanager +def _open_config_file(config_file: str | IO | None) -> Iterator[IO]: + """ + A context manager which yields an open file descriptor ready to be read. + + Accepts a filename as a string, an open or closed file descriptor, or None. + When None, it defaults to `mkdocs.yml` in the CWD. If a closed file descriptor + is received, a new file descriptor is opened for the same file. + + The file descriptor is automatically closed when the context manager block is existed. + """ + # Default to the standard config filename. + if config_file is None: + paths_to_try = ['mkdocs.yml', 'mkdocs.yaml'] + # If it is a string, we can assume it is a path and attempt to open it. + elif isinstance(config_file, str): + paths_to_try = [config_file] + # If closed file descriptor, get file path to reopen later. + elif getattr(config_file, 'closed', False): + paths_to_try = [config_file.name] + else: + result_config_file = config_file + paths_to_try = None + + if paths_to_try: + # config_file is not a file descriptor, so open it as a path. + for path in paths_to_try: + path = os.path.abspath(path) + log.debug(f"Loading configuration file: {path}") + try: + result_config_file = open(path, 'rb') + break + except FileNotFoundError: + continue + else: + raise exceptions.ConfigurationError(f"Config file '{paths_to_try[0]}' does not exist.") + else: + log.debug(f"Loading configuration file: {result_config_file}") + # Ensure file descriptor is at beginning + try: + result_config_file.seek(0) + except OSError: + pass + + try: + yield result_config_file + finally: + if hasattr(result_config_file, 'close'): + result_config_file.close() + + +def load_config( + config_file: str | IO | None = None, *, config_file_path: str | None = None, **kwargs +) -> MkDocsConfig: + """ + Load the configuration for a given file object or name + + The config_file can either be a file object, string or None. If it is None + the default `mkdocs.yml` filename will loaded. + + Extra kwargs are passed to the configuration to replace any default values + unless they themselves are None. + """ + options = kwargs.copy() + + # Filter None values from the options. This usually happens with optional + # parameters from Click. + for key, value in options.copy().items(): + if value is None: + options.pop(key) + + with _open_config_file(config_file) as fd: + # Initialize the config with the default schema. + from mkdocs.config.defaults import MkDocsConfig + + if config_file_path is None: + if fd is not sys.stdin.buffer: + config_file_path = getattr(fd, 'name', None) + cfg = MkDocsConfig(config_file_path=config_file_path) + # load the config file + cfg.load_file(fd) + + # Then load the options to overwrite anything in the config. + cfg.load_dict(options) + + errors, warnings = cfg.validate() + + for config_name, warning in warnings: + log.warning(f"Config value '{config_name}': {warning}") + + for config_name, error in errors: + log.error(f"Config value '{config_name}': {error}") + + for key, value in cfg.items(): + log.debug(f"Config value '{key}' = {value!r}") + + if len(errors) > 0: + raise exceptions.Abort(f"Aborted with {len(errors)} configuration errors!") + elif cfg.strict and len(warnings) > 0: + raise exceptions.Abort( + f"Aborted with {len(warnings)} configuration warnings in 'strict' mode!" + ) + + return cfg diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/config/config_options.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/config/config_options.py new file mode 100644 index 0000000000000000000000000000000000000000..070731251a7561712bcf44011815138a353ffbe1 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/config/config_options.py @@ -0,0 +1,1223 @@ +from __future__ import annotations + +import functools +import ipaddress +import logging +import os +import string +import sys +import traceback +import types +import warnings +from collections import Counter, UserString +from typing import ( + Any, + Callable, + Collection, + Dict, + Generic, + Iterator, + List, + Mapping, + MutableMapping, + NamedTuple, + TypeVar, + Union, + overload, +) +from urllib.parse import quote as urlquote +from urllib.parse import urlsplit, urlunsplit + +import markdown +import pathspec +import pathspec.gitignore + +from mkdocs import plugins, theme, utils +from mkdocs.config.base import ( + BaseConfigOption, + Config, + LegacyConfig, + PlainConfigSchemaItem, + ValidationError, +) +from mkdocs.exceptions import ConfigurationError + +T = TypeVar('T') +SomeConfig = TypeVar('SomeConfig', bound=Config) + + +class SubConfig(Generic[SomeConfig], BaseConfigOption[SomeConfig]): + """ + Subconfig Config Option + + New: If targeting MkDocs 1.4+, please pass a subclass of Config to the + constructor, instead of the old style of a sequence of ConfigOption instances. + Validation is then enabled by default. + + A set of `config_options` grouped under a single config option. + By default, validation errors and warnings resulting from validating + `config_options` are ignored (`validate=False`). Users should typically + enable validation with `validate=True`. + """ + + _config_file_path: str | None = None + config_class: type[SomeConfig] + + @overload + def __init__( + self: SubConfig[SomeConfig], config_class: type[SomeConfig], *, validate: bool = True + ): + """Create a sub-config in a type-safe way, using fields defined in a Config subclass.""" + + @overload + def __init__( + self: SubConfig[LegacyConfig], + *config_options: PlainConfigSchemaItem, + validate: bool = False, + ): + """Create an untyped sub-config, using directly passed fields.""" + + def __init__(self, *config_options, validate=None): + super().__init__() + self.default = {} + self._do_validation = True if validate is None else validate + if type(self) is SubConfig: + if ( + len(config_options) == 1 + and isinstance(config_options[0], type) + and issubclass(config_options[0], Config) + ): + (self.config_class,) = config_options + else: + self.config_class = functools.partial(LegacyConfig, config_options) + self._do_validation = False if validate is None else validate + + def __class_getitem__(cls, config_class: type[Config]): + """Eliminates the need to write `config_class = FooConfig` when subclassing SubConfig[FooConfig]""" + name = f'{cls.__name__}[{config_class.__name__}]' + return type(name, (cls,), dict(config_class=config_class)) + + def pre_validation(self, config: Config, key_name: str): + self._config_file_path = config.config_file_path + + def run_validation(self, value: object) -> SomeConfig: + config = self.config_class(config_file_path=self._config_file_path) + try: + config.load_dict(value) # type: ignore + failed, warnings = config.validate() + except ConfigurationError as e: + raise ValidationError(str(e)) + + if self._do_validation: + # Capture errors and warnings + self.warnings.extend(f"Sub-option '{key}': {msg}" for key, msg in warnings) + if failed: + # Get the first failing one + key, err = failed[0] + raise ValidationError(f"Sub-option '{key}': {err}") + + return config + + +class PropagatingSubConfig(SubConfig[SomeConfig], Generic[SomeConfig]): + """A SubConfig that must consist of SubConfigs with defined schemas. + + Any value set on the top config gets moved to sub-configs with matching keys. + """ + + def run_validation(self, value: object): + if isinstance(value, dict): + to_discard = set() + for k1, v1 in self.config_class._schema: + if isinstance(v1, SubConfig): + for k2, _ in v1.config_class._schema: + if k2 in value: + subdict = value.setdefault(k1, {}) + if isinstance(subdict, dict): + to_discard.add(k2) + subdict.setdefault(k2, value[k2]) + for k in to_discard: + del value[k] + return super().run_validation(value) + + +class OptionallyRequired(Generic[T], BaseConfigOption[T]): + """ + Soft-deprecated, do not use. + + A subclass of BaseConfigOption that adds support for default values and + required values. It is a base class for config options. + """ + + @overload + def __init__(self, default=None): + ... + + @overload + def __init__(self, default=None, *, required: bool): + ... + + def __init__(self, default=None, required=None): + super().__init__() + self.default = default + self._legacy_required = required + self.required = bool(required) + + def validate(self, value): + """ + Perform some initial validation. + + If the option is empty (None) and isn't required, leave it as such. If + it is empty but has a default, use that. Finally, call the + run_validation method on the subclass unless. + """ + if value is None: + if self.default is not None: + value = self.default + elif not self.required: + return None + elif self.required: + raise ValidationError("Required configuration not provided.") + + return self.run_validation(value) + + +class ListOfItems(Generic[T], BaseConfigOption[List[T]]): + """ + Validates a homogeneous list of items. + + E.g. for `config_options.ListOfItems(config_options.Type(int))` a valid item is `[1, 2, 3]`. + """ + + required: bool | None = None # Only for subclasses to set. + + def __init__(self, option_type: BaseConfigOption[T], default=None) -> None: + super().__init__() + self.default = default + self.option_type = option_type + self.option_type.warnings = self.warnings + + def __repr__(self) -> str: + return f'{type(self).__name__}: {self.option_type}' + + def pre_validation(self, config: Config, key_name: str): + self._config = config + self._key_name = key_name + + def run_validation(self, value: object) -> list[T]: + if value is None: + if self.required or self.default is None: + raise ValidationError("Required configuration not provided.") + value = self.default + if not isinstance(value, list): + raise ValidationError(f'Expected a list of items, but a {type(value)} was given.') + if not value: # Optimization for empty list + return value + + fake_config = LegacyConfig(()) + try: + fake_config.config_file_path = self._config.config_file_path + except AttributeError: + pass + + # Emulate a config-like environment for pre_validation and post_validation. + parent_key_name = getattr(self, '_key_name', '') + fake_keys = [f'{parent_key_name}[{i}]' for i in range(len(value))] + fake_config.data = dict(zip(fake_keys, value)) + + self.option_type.warnings = self.warnings + for key_name in fake_config: + self.option_type.pre_validation(fake_config, key_name) + for key_name in fake_config: + # Specifically not running `validate` to avoid the OptionallyRequired effect. + fake_config[key_name] = self.option_type.run_validation(fake_config[key_name]) + for key_name in fake_config: + self.option_type.post_validation(fake_config, key_name) + + return [fake_config[k] for k in fake_keys] + + +class DictOfItems(Generic[T], BaseConfigOption[Dict[str, T]]): + """ + Validates a dict of items. Keys are always strings. + + E.g. for `config_options.DictOfItems(config_options.Type(int))` a valid item is `{"a": 1, "b": 2}`. + """ + + required: bool | None = None # Only for subclasses to set. + + def __init__(self, option_type: BaseConfigOption[T], default=None) -> None: + super().__init__() + self.default = default + self.option_type = option_type + self.option_type.warnings = self.warnings + + def __repr__(self) -> str: + return f"{type(self).__name__}: {self.option_type}" + + def pre_validation(self, config: Config, key_name: str): + self._config = config + self._key_name = key_name + + def run_validation(self, value: object) -> dict[str, T]: + if value is None: + if self.required or self.default is None: + raise ValidationError("Required configuration not provided.") + value = self.default + if not isinstance(value, dict): + raise ValidationError(f"Expected a dict of items, but a {type(value)} was given.") + if not value: # Optimization for empty list + return value + + fake_config = LegacyConfig(()) + try: + fake_config.config_file_path = self._config.config_file_path + except AttributeError: + pass + + # Emulate a config-like environment for pre_validation and post_validation. + fake_config.data = value + + for key in fake_config: + self.option_type.pre_validation(fake_config, key) + for key in fake_config: + if not isinstance(key, str): + raise ValidationError( + f"Expected type: {str} for keys, but received: {type(key)} (key={key})" + ) + for key in fake_config: + # Specifically not running `validate` to avoid the OptionallyRequired effect. + fake_config[key] = self.option_type.run_validation(fake_config[key]) + for key in fake_config: + self.option_type.post_validation(fake_config, key) + + return value + + +class ConfigItems(ListOfItems[LegacyConfig]): + """ + Deprecated: Use `ListOfItems(SubConfig(...))` instead of `ConfigItems(...)`. + + Validates a list of mappings that all must match the same set of + options. + """ + + @overload + def __init__(self, *config_options: PlainConfigSchemaItem): + ... + + @overload + def __init__(self, *config_options: PlainConfigSchemaItem, required: bool): + ... + + def __init__(self, *config_options: PlainConfigSchemaItem, required=None) -> None: + super().__init__(SubConfig(*config_options), default=[]) + self._legacy_required = required + self.required = bool(required) + + +class Type(Generic[T], OptionallyRequired[T]): + """ + Type Config Option + + Validate the type of a config option against a given Python type. + """ + + @overload + def __init__(self, type_: type[T], length: int | None = None, **kwargs): + ... + + @overload + def __init__(self, type_: tuple[type[T], ...], length: int | None = None, **kwargs): + ... + + def __init__(self, type_, length=None, **kwargs) -> None: + super().__init__(**kwargs) + self._type = type_ + self.length = length + + def run_validation(self, value: object) -> T: + if not isinstance(value, self._type): + msg = f"Expected type: {self._type} but received: {type(value)}" + elif self.length is not None and len(value) != self.length: + msg = ( + f"Expected type: {self._type} with length {self.length}" + f" but received: {value!r} with length {len(value)}" + ) + else: + return value + + raise ValidationError(msg) + + +class Choice(Generic[T], OptionallyRequired[T]): + """ + Choice Config Option + + Validate the config option against a strict set of values. + """ + + def __init__(self, choices: Collection[T], default: T | None = None, **kwargs) -> None: + super().__init__(default=default, **kwargs) + try: + length = len(choices) + except TypeError: + length = 0 + + if not length or isinstance(choices, str): + raise ValueError(f'Expected iterable of choices, got {choices}') + if default is not None and default not in choices: + raise ValueError(f'{default!r} is not one of {choices!r}') + + self.choices = choices + + def run_validation(self, value: object) -> T: + if value not in self.choices: + raise ValidationError(f"Expected one of: {self.choices} but received: {value!r}") + return value # type: ignore + + +class Deprecated(BaseConfigOption): + """ + Deprecated Config Option + + Raises a warning as the option is deprecated. Uses `message` for the + warning. If `move_to` is set to the name of a new config option, the value + is moved to the new option on pre_validation. If `option_type` is set to a + ConfigOption instance, then the value is validated against that type. + """ + + def __init__( + self, + moved_to: str | None = None, + message: str | None = None, + removed: bool = False, + option_type: BaseConfigOption | None = None, + ) -> None: + super().__init__() + self.default = None + self.moved_to = moved_to + if not message: + if removed: + message = "The configuration option '{}' was removed from MkDocs." + else: + message = ( + "The configuration option '{}' has been deprecated and " + "will be removed in a future release." + ) + if moved_to: + message += f" Use '{moved_to}' instead." + + self.message = message + self.removed = removed + self.option = option_type or BaseConfigOption() + + self.warnings = self.option.warnings + + def pre_validation(self, config: Config, key_name: str): + self.option.pre_validation(config, key_name) + + if config.get(key_name) is not None: + if self.removed: + raise ValidationError(self.message.format(key_name)) + self.warnings.append(self.message.format(key_name)) + + if self.moved_to is not None: + *parent_keys, target_key = self.moved_to.split('.') + target: Any = config + + for key in parent_keys: + if target.get(key) is None: + target[key] = {} + target = target[key] + + if not isinstance(target, dict): + # We can't move it for the user + return + + target[target_key] = config.pop(key_name) + + def validate(self, value): + return self.option.validate(value) + + def post_validation(self, config: Config, key_name: str): + self.option.post_validation(config, key_name) + + def reset_warnings(self): + self.option.reset_warnings() + self.warnings = self.option.warnings + + +class _IpAddressValue(NamedTuple): + host: str + port: int + + def __str__(self) -> str: + return f'{self.host}:{self.port}' + + +class IpAddress(OptionallyRequired[_IpAddressValue]): + """ + IpAddress Config Option + + Validate that an IP address is in an appropriate format + """ + + def run_validation(self, value: object) -> _IpAddressValue: + if not isinstance(value, str) or ':' not in value: + raise ValidationError("Must be a string of format 'IP:PORT'") + host, port_str = value.rsplit(':', 1) + + if host != 'localhost': + if host.startswith('[') and host.endswith(']'): + host = host[1:-1] + try: + # Validate and normalize IP Address + host = str(ipaddress.ip_address(host)) + except ValueError as e: + raise ValidationError(e) + + try: + port = int(port_str) + except Exception: + raise ValidationError(f"'{port_str}' is not a valid port") + + return _IpAddressValue(host, port) + + def post_validation(self, config: Config, key_name: str): + host = config[key_name].host + if key_name == 'dev_addr' and host in ['0.0.0.0', '::']: + self.warnings.append( + f"The use of the IP address '{host}' suggests a production environment " + "or the use of a proxy to connect to the MkDocs server. However, " + "the MkDocs' server is intended for local development purposes only. " + "Please use a third party production-ready server instead." + ) + + +class URL(OptionallyRequired[str]): + """ + URL Config Option + + Validate a URL by requiring a scheme is present. + """ + + @overload + def __init__(self, default=None, *, is_dir: bool = False): + ... + + @overload + def __init__(self, default=None, *, required: bool, is_dir: bool = False): + ... + + def __init__(self, default=None, required=None, is_dir: bool = False) -> None: + self.is_dir = is_dir + super().__init__(default, required=required) + + def run_validation(self, value: object) -> str: + if not isinstance(value, str): + raise ValidationError(f"Expected a string, got {type(value)}") + if value == '': + return value + try: + parsed_url = urlsplit(value) + except (AttributeError, TypeError): + raise ValidationError("Unable to parse the URL.") + + if parsed_url.scheme and parsed_url.netloc: + if self.is_dir and not parsed_url.path.endswith('/'): + parsed_url = parsed_url._replace(path=f'{parsed_url.path}/') + return urlunsplit(parsed_url) + + raise ValidationError("The URL isn't valid, it should include the http:// (scheme)") + + +class Optional(Generic[T], BaseConfigOption[Union[T, None]]): + """Wraps a field and makes a None value possible for it when no value is set. + + E.g. `my_field = config_options.Optional(config_options.Type(str))` + """ + + def __init__(self, config_option: BaseConfigOption[T]) -> None: + if config_option.default is not None: + raise ValueError( + f"This option already has a default ({config_option.default!r}) " + f"and doesn't need to be wrapped into Optional" + ) + super().__init__() + self.option = config_option + self.warnings = config_option.warnings + + def __getattr__(self, key): + if key in ('option', 'warnings'): + raise AttributeError + return getattr(self.option, key) + + def pre_validation(self, config: Config, key_name: str): + return self.option.pre_validation(config, key_name) + + def run_validation(self, value: object) -> T | None: + if value is None: + return None + return self.option.validate(value) + + def post_validation(self, config: Config, key_name: str): + result = self.option.post_validation(config, key_name) # type: ignore + self.warnings = self.option.warnings + return result + + def reset_warnings(self): + self.option.reset_warnings() + self.warnings = self.option.warnings + + +class RepoURL(URL): + def __init__(self, *args, **kwargs): + warnings.warn( + "RepoURL is no longer used in MkDocs and will be removed.", DeprecationWarning + ) + super().__init__(*args, **kwargs) + + def post_validation(self, config: Config, key_name: str): + repo_host = urlsplit(config['repo_url']).netloc.lower() + edit_uri = config.get('edit_uri') + + # derive repo_name from repo_url if unset + if config['repo_url'] is not None and config.get('repo_name') is None: + if repo_host == 'github.com': + config['repo_name'] = 'GitHub' + elif repo_host == 'bitbucket.org': + config['repo_name'] = 'Bitbucket' + elif repo_host == 'gitlab.com': + config['repo_name'] = 'GitLab' + else: + config['repo_name'] = repo_host.split('.')[0].title() + + # derive edit_uri from repo_name if unset + if config['repo_url'] is not None and edit_uri is None: + if repo_host == 'github.com' or repo_host == 'gitlab.com': + edit_uri = 'edit/master/docs/' + elif repo_host == 'bitbucket.org': + edit_uri = 'src/default/docs/' + else: + edit_uri = '' + + # ensure a well-formed edit_uri + if edit_uri and not edit_uri.endswith('/'): + edit_uri += '/' + + config['edit_uri'] = edit_uri + + +class EditURI(Type[str]): + def __init__(self, repo_url_key: str) -> None: + super().__init__(str) + self.repo_url_key = repo_url_key + + def post_validation(self, config: Config, key_name: str): + edit_uri = config.get(key_name) + repo_url = config.get(self.repo_url_key) + + if edit_uri is None and repo_url is not None: + repo_host = urlsplit(repo_url).netloc.lower() + if repo_host == 'github.com' or repo_host == 'gitlab.com': + edit_uri = 'edit/master/docs/' + elif repo_host == 'bitbucket.org': + edit_uri = 'src/default/docs/' + + # ensure a well-formed edit_uri + if edit_uri and not edit_uri.endswith('/'): + edit_uri += '/' + + config[key_name] = edit_uri + + +class EditURITemplate(BaseConfigOption[str]): + class Formatter(string.Formatter): + def convert_field(self, value, conversion): + if conversion == 'q': + return urlquote(value, safe='') + return super().convert_field(value, conversion) + + class Template(UserString): + def __init__(self, formatter, data) -> None: + super().__init__(data) + self.formatter = formatter + try: + self.format('', '') + except KeyError as e: + raise ValueError(f"Unknown template substitute: {e}") + + def format(self, path, path_noext): + return self.formatter.format(self.data, path=path, path_noext=path_noext) + + def __init__(self, edit_uri_key: str | None = None) -> None: + super().__init__() + self.edit_uri_key = edit_uri_key + + def run_validation(self, value: object): + try: + return self.Template(self.Formatter(), value) + except Exception as e: + raise ValidationError(e) + + def post_validation(self, config: Config, key_name: str): + if self.edit_uri_key and config.get(key_name) and config.get(self.edit_uri_key): + self.warnings.append( + f"The option '{self.edit_uri_key}' has no effect when '{key_name}' is set." + ) + + +class RepoName(Type[str]): + def __init__(self, repo_url_key: str) -> None: + super().__init__(str) + self.repo_url_key = repo_url_key + + def post_validation(self, config: Config, key_name: str): + repo_name = config.get(key_name) + repo_url = config.get(self.repo_url_key) + + # derive repo_name from repo_url if unset + if repo_url is not None and repo_name is None: + repo_host = urlsplit(config['repo_url']).netloc.lower() + if repo_host == 'github.com': + repo_name = 'GitHub' + elif repo_host == 'bitbucket.org': + repo_name = 'Bitbucket' + elif repo_host == 'gitlab.com': + repo_name = 'GitLab' + else: + repo_name = repo_host.split('.')[0].title() + config[key_name] = repo_name + + +class FilesystemObject(Type[str]): + """ + Base class for options that point to filesystem objects. + """ + + existence_test: Callable[[str], bool] = staticmethod(os.path.exists) + name = 'file or directory' + + def __init__(self, exists: bool = False, **kwargs) -> None: + super().__init__(type_=str, **kwargs) + self.exists = exists + self.config_dir: str | None = None + + def pre_validation(self, config: Config, key_name: str): + self.config_dir = ( + os.path.dirname(config.config_file_path) if config.config_file_path else None + ) + + def run_validation(self, value: object) -> str: + value = super().run_validation(value) + if self.config_dir and not os.path.isabs(value): + value = os.path.join(self.config_dir, value) + if self.exists and not self.existence_test(value): + raise ValidationError(f"The path '{value}' isn't an existing {self.name}.") + return os.path.abspath(value) + + +class Dir(FilesystemObject): + """ + Dir Config Option + + Validate a path to a directory, optionally verifying that it exists. + """ + + existence_test = staticmethod(os.path.isdir) + name = 'directory' + + +class DocsDir(Dir): + def post_validation(self, config: Config, key_name: str): + if not config.config_file_path: + return + + # Validate that the dir is not the parent dir of the config file. + if os.path.dirname(config.config_file_path) == config[key_name]: + raise ValidationError( + f"The '{key_name}' should not be the parent directory of the" + f" config file. Use a child directory instead so that the" + f" '{key_name}' is a sibling of the config file." + ) + + +class File(FilesystemObject): + """ + File Config Option + + Validate a path to a file, optionally verifying that it exists. + """ + + existence_test = staticmethod(os.path.isfile) + name = 'file' + + +class ListOfPaths(ListOfItems[str]): + """ + List of Paths Config Option + + A list of file system paths. Raises an error if one of the paths does not exist. + + For greater flexibility, prefer ListOfItems, e.g. to require files specifically: + + config_options.ListOfItems(config_options.File(exists=True)) + """ + + @overload + def __init__(self, default=[]): + ... + + @overload + def __init__(self, default=[], *, required: bool): + ... + + def __init__(self, default=[], required=None) -> None: + super().__init__(FilesystemObject(exists=True), default) + self.required = required + + +class SiteDir(Dir): + """ + SiteDir Config Option + + Validates the site_dir and docs_dir directories do not contain each other. + """ + + def post_validation(self, config: Config, key_name: str): + super().post_validation(config, key_name) + docs_dir = config['docs_dir'] + site_dir = config['site_dir'] + + # Validate that the docs_dir and site_dir don't contain the + # other as this will lead to copying back and forth on each + # and eventually make a deep nested mess. + if (docs_dir + os.sep).startswith(site_dir.rstrip(os.sep) + os.sep): + raise ValidationError( + f"The 'docs_dir' should not be within the 'site_dir' as this " + f"can mean the source files are overwritten by the output or " + f"it will be deleted if --clean is passed to mkdocs build. " + f"(site_dir: '{site_dir}', docs_dir: '{docs_dir}')" + ) + elif (site_dir + os.sep).startswith(docs_dir.rstrip(os.sep) + os.sep): + raise ValidationError( + f"The 'site_dir' should not be within the 'docs_dir' as this " + f"leads to the build directory being copied into itself and " + f"duplicate nested files in the 'site_dir'. " + f"(site_dir: '{site_dir}', docs_dir: '{docs_dir}')" + ) + + +class Theme(BaseConfigOption[theme.Theme]): + """ + Theme Config Option + + Validate that the theme exists and build Theme instance. + """ + + def __init__(self, default=None) -> None: + super().__init__() + self.default = default + + def pre_validation(self, config: Config, key_name: str): + self.config_file_path = config.config_file_path + + def run_validation(self, value: object) -> theme.Theme: + if value is None and self.default is not None: + theme_config = {'name': self.default} + elif isinstance(value, str): + theme_config = {'name': value} + elif isinstance(value, dict): + if 'name' not in value: + raise ValidationError("No theme name set.") + theme_config = value + else: + raise ValidationError( + f'Invalid type {type(value)}. Expected a string or key/value pairs.' + ) + + themes = utils.get_theme_names() + if theme_config['name'] is not None and theme_config['name'] not in themes: + raise ValidationError( + f"Unrecognised theme name: '{theme_config['name']}'. " + f"The available installed themes are: {', '.join(themes)}" + ) + + if not theme_config['name'] and 'custom_dir' not in theme_config: + raise ValidationError("At least one of 'name' or 'custom_dir' must be defined.") + + # Ensure custom_dir is an absolute path + if 'custom_dir' in theme_config and not os.path.isabs(theme_config['custom_dir']): + config_dir = os.path.dirname(self.config_file_path) + theme_config['custom_dir'] = os.path.join(config_dir, theme_config['custom_dir']) + + if 'custom_dir' in theme_config and not os.path.isdir(theme_config['custom_dir']): + raise ValidationError( + "The path set in custom_dir ('{path}') does not exist.".format( + path=theme_config['custom_dir'] + ) + ) + + if 'locale' in theme_config and not isinstance(theme_config['locale'], str): + raise ValidationError("'locale' must be a string.") + + return theme.Theme(**theme_config) + + +class Nav(OptionallyRequired): + """ + Nav Config Option + + Validate the Nav config. + """ + + def run_validation(self, value: object, *, top=True): + if isinstance(value, list): + for subitem in value: + self._validate_nav_item(subitem) + if top and not value: + value = None + elif isinstance(value, dict) and value and not top: + # TODO: this should be an error. + self.warnings.append(f"Expected nav to be a list, got {self._repr_item(value)}") + for subitem in value.values(): + self.run_validation(subitem, top=False) + elif isinstance(value, str) and not top: + pass + else: + raise ValidationError(f"Expected nav to be a list, got {self._repr_item(value)}") + return value + + def _validate_nav_item(self, value): + if isinstance(value, str): + pass + elif isinstance(value, dict): + if len(value) != 1: + raise ValidationError( + f"Expected nav item to be a dict of size 1, got {self._repr_item(value)}" + ) + for subnav in value.values(): + self.run_validation(subnav, top=False) + else: + raise ValidationError( + f"Expected nav item to be a string or dict, got {self._repr_item(value)}" + ) + + @classmethod + def _repr_item(cls, value) -> str: + if isinstance(value, dict) and value: + return f"dict with keys {tuple(value.keys())}" + elif isinstance(value, (str, type(None))): + return repr(value) + else: + return f"a {type(value).__name__}: {value!r}" + + +class Private(Generic[T], BaseConfigOption[T]): + """A config option that can only be populated programmatically. Raises an error if set by the user.""" + + def run_validation(self, value: object) -> None: + if value is not None: + raise ValidationError('For internal use only.') + + +class ExtraScriptValue(Config): + """An extra script to be added to the page. The `extra_javascript` config is a list of these.""" + + path = Type(str) + """The value of the `src` tag of the script.""" + type = Type(str, default='') + """The value of the `type` tag of the script.""" + defer = Type(bool, default=False) + """Whether to add the `defer` tag to the script.""" + async_ = Type(bool, default=False) + """Whether to add the `async` tag to the script.""" + + def __init__(self, path: str = '', config_file_path=None): + super().__init__(config_file_path=config_file_path) + self.path = path + + def __str__(self): + return self.path + + def __fspath__(self): + return self.path + + +class ExtraScript(BaseConfigOption[Union[ExtraScriptValue, str]]): + def __init__(self): + super().__init__() + self.option_type = SubConfig[ExtraScriptValue]() + + def run_validation(self, value: object) -> ExtraScriptValue | str: + self.option_type.warnings = self.warnings + if isinstance(value, str): + if value.endswith('.mjs'): + return self.option_type.run_validation({'path': value, 'type': 'module'}) + return value + return self.option_type.run_validation(value) + + +class MarkdownExtensions(OptionallyRequired[List[str]]): + """ + Markdown Extensions Config Option + + A list or dict of extensions. Each list item may contain either a string or a one item dict. + A string must be a valid Markdown extension name with no config options defined. The key of + a dict item must be a valid Markdown extension name and the value must be a dict of config + options for that extension. Extension configs are set on the private setting passed to + `configkey`. The `builtins` keyword accepts a list of extensions which cannot be overridden by + the user. However, builtins can be duplicated to define config options for them if desired.""" + + def __init__( + self, + builtins: list[str] | None = None, + configkey: str = 'mdx_configs', + default: list[str] = [], + **kwargs, + ) -> None: + super().__init__(default=default, **kwargs) + self.builtins = builtins or [] + self.configkey = configkey + + def validate_ext_cfg(self, ext: object, cfg: object) -> None: + if not isinstance(ext, str): + raise ValidationError(f"'{ext}' is not a valid Markdown Extension name.") + if not cfg: + return + if not isinstance(cfg, dict): + raise ValidationError(f"Invalid config options for Markdown Extension '{ext}'.") + self.configdata[ext] = cfg + + def run_validation(self, value: object) -> list[str]: + self.configdata: dict[str, dict] = {} + if not isinstance(value, (list, tuple, dict)): + raise ValidationError('Invalid Markdown Extensions configuration') + extensions = [] + if isinstance(value, dict): + for ext, cfg in value.items(): + self.validate_ext_cfg(ext, cfg) + extensions.append(ext) + else: + for item in value: + if isinstance(item, dict): + if len(item) > 1: + raise ValidationError('Invalid Markdown Extensions configuration') + ext, cfg = item.popitem() + self.validate_ext_cfg(ext, cfg) + extensions.append(ext) + elif isinstance(item, str): + extensions.append(item) + else: + raise ValidationError('Invalid Markdown Extensions configuration') + + extensions = utils.reduce_list(self.builtins + extensions) + + # Confirm that Markdown considers extensions to be valid + md = markdown.Markdown() + for ext in extensions: + try: + md.registerExtensions((ext,), self.configdata) + except Exception as e: + stack: list = [] + for frame in reversed(traceback.extract_tb(sys.exc_info()[2])): + if not frame.line: # Ignore frames before + break + stack.insert(0, frame) + tb = ''.join(traceback.format_list(stack)) + + raise ValidationError( + f"Failed to load extension '{ext}'.\n{tb}{type(e).__name__}: {e}" + ) + + return extensions + + def post_validation(self, config: Config, key_name: str): + config[self.configkey] = self.configdata + + +class Plugins(OptionallyRequired[plugins.PluginCollection]): + """ + Plugins config option. + + A list or dict of plugins. If a plugin defines config options those are used when + initializing the plugin class. + """ + + def __init__(self, theme_key: str | None = None, **kwargs) -> None: + super().__init__(**kwargs) + self.installed_plugins = plugins.get_plugins() + self.theme_key = theme_key + self._config: Config | None = None + self.plugin_cache: dict[str, plugins.BasePlugin] = {} + + def pre_validation(self, config, key_name): + self._config = config + + def run_validation(self, value: object) -> plugins.PluginCollection: + if not isinstance(value, (list, tuple, dict)): + raise ValidationError('Invalid Plugins configuration. Expected a list or dict.') + self.plugins = plugins.PluginCollection() + self._instance_counter: MutableMapping[str, int] = Counter() + for name, cfg in self._parse_configs(value): + self.load_plugin_with_namespace(name, cfg) + return self.plugins + + @classmethod + def _parse_configs(cls, value: list | tuple | dict) -> Iterator[tuple[str, dict]]: + if isinstance(value, dict): + for name, cfg in value.items(): + if not isinstance(name, str): + raise ValidationError(f"'{name}' is not a valid plugin name.") + yield name, cfg + else: + for item in value: + if isinstance(item, dict): + if len(item) != 1: + raise ValidationError('Invalid Plugins configuration') + name, cfg = item.popitem() + else: + name = item + cfg = {} + if not isinstance(name, str): + raise ValidationError(f"'{name}' is not a valid plugin name.") + yield name, cfg + + def load_plugin_with_namespace(self, name: str, config) -> tuple[str, plugins.BasePlugin]: + if '/' in name: # It's already specified with a namespace. + # Special case: allow to explicitly skip namespaced loading: + if name.startswith('/'): + name = name[1:] + else: + # Attempt to load with prepended namespace for the current theme. + if self.theme_key and self._config: + current_theme = self._config[self.theme_key] + if not isinstance(current_theme, str): + current_theme = current_theme['name'] + if current_theme: + expanded_name = f'{current_theme}/{name}' + if expanded_name in self.installed_plugins: + name = expanded_name + return (name, self.load_plugin(name, config)) + + def load_plugin(self, name: str, config) -> plugins.BasePlugin: + if name not in self.installed_plugins: + raise ValidationError(f'The "{name}" plugin is not installed') + + config = config or {} # Users may define a null (None) config + if not isinstance(config, dict): + raise ValidationError(f"Invalid config options for the '{name}' plugin.") + + self._instance_counter[name] += 1 + inst_number = self._instance_counter[name] + inst_name = name + if inst_number > 1: + inst_name += f' #{inst_number}' + + plugin = self.plugin_cache.get(inst_name) + if plugin is None: + plugin_cls = self.installed_plugins[name].load() + + if not issubclass(plugin_cls, plugins.BasePlugin): + raise ValidationError( + f'{plugin_cls.__module__}.{plugin_cls.__name__} must be a subclass of' + f' {plugins.BasePlugin.__module__}.{plugins.BasePlugin.__name__}' + ) + + plugin = plugin_cls() + + if hasattr(plugin, 'on_startup') or hasattr(plugin, 'on_shutdown'): + self.plugin_cache[inst_name] = plugin + + if inst_number > 1 and not getattr(plugin, 'supports_multiple_instances', False): + self.warnings.append( + f"Plugin '{name}' was specified multiple times - this is likely a mistake, " + "because the plugin doesn't declare `supports_multiple_instances`." + ) + + errors, warns = plugin.load_config( + config, self._config.config_file_path if self._config else None + ) + for warning in warns: + if isinstance(warning, str): + self.warnings.append(f"Plugin '{inst_name}': {warning}") + else: + key, msg = warning + self.warnings.append(f"Plugin '{inst_name}' option '{key}': {msg}") + + errors_message = '\n'.join(f"Plugin '{name}' option '{key}': {msg}" for key, msg in errors) + if errors_message: + raise ValidationError(errors_message) + self.plugins[inst_name] = plugin + return plugin + + +class Hooks(BaseConfigOption[List[types.ModuleType]]): + """A list of Python scripts to be treated as instances of plugins.""" + + def __init__(self, plugins_key: str) -> None: + super().__init__() + self.default = [] + self.plugins_key = plugins_key + + def pre_validation(self, config: Config, key_name: str): + self._base_option = ListOfItems(File(exists=True)) + self._base_option.pre_validation(config, key_name) + + def run_validation(self, value: object) -> Mapping[str, Any]: + paths = self._base_option.validate(value) + self.warnings.extend(self._base_option.warnings) + assert isinstance(value, list) + + hooks = {} + for name, path in zip(value, paths): + hooks[name] = self._load_hook(name, path) + return hooks + + @functools.lru_cache(maxsize=None) + def _load_hook(self, name, path): + import importlib.util + + spec = importlib.util.spec_from_file_location(name, path) + if spec is None: + raise ValidationError(f"Cannot import path '{path}' as a Python module") + module = importlib.util.module_from_spec(spec) + sys.modules[name] = module + if spec.loader is None: + raise ValidationError(f"Cannot import path '{path}' as a Python module") + spec.loader.exec_module(module) + return module + + def post_validation(self, config: Config, key_name: str): + plugins = config[self.plugins_key] + for name, hook in config[key_name].items(): + plugins[name] = hook + + +class PathSpec(BaseConfigOption[pathspec.gitignore.GitIgnoreSpec]): + """A path pattern based on gitignore-like syntax.""" + + def run_validation(self, value: object) -> pathspec.gitignore.GitIgnoreSpec: + if not isinstance(value, str): + raise ValidationError(f'Expected a multiline string, but a {type(value)} was given.') + try: + return pathspec.gitignore.GitIgnoreSpec.from_lines(lines=value.splitlines()) + except ValueError as e: + raise ValidationError(str(e)) + + +class _LogLevel(OptionallyRequired[int]): + levels: Mapping[str, int] = { + "warn": logging.WARNING, + "info": logging.INFO, + "ignore": logging.DEBUG, + } + + def run_validation(self, value: object) -> int: + if not isinstance(value, str): + raise ValidationError(f'Expected a string, but a {type(value)} was given.') + try: + return self.levels[value] + except KeyError: + raise ValidationError(f'Expected one of {list(self.levels)}, got {value!r}') diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/config/defaults.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/config/defaults.py new file mode 100644 index 0000000000000000000000000000000000000000..e4b6df63830050c1a73816e011d988b6e20f6ef4 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/config/defaults.py @@ -0,0 +1,190 @@ +from __future__ import annotations + +from typing import IO, TYPE_CHECKING, Dict + +from mkdocs.config import base +from mkdocs.config import config_options as c +from mkdocs.utils.yaml import get_yaml_loader, yaml_load + +if TYPE_CHECKING: + import mkdocs.structure.pages + + +# NOTE: The order here is important. During validation some config options +# depend on others. So, if config option A depends on B, then A should be +# listed higher in the schema. +class MkDocsConfig(base.Config): + """The configuration of MkDocs itself (the root object of mkdocs.yml).""" + + config_file_path: str = c.Type(str) # type: ignore[assignment] + """The path to the mkdocs.yml config file. Can't be populated from the config.""" + + site_name = c.Type(str) + """The title to use for the documentation.""" + + nav = c.Optional(c.Nav()) + """Defines the structure of the navigation.""" + pages = c.Deprecated(removed=True, moved_to='nav') + + exclude_docs = c.Optional(c.PathSpec()) + """Gitignore-like patterns of files (relative to docs dir) to exclude from the site.""" + + not_in_nav = c.Optional(c.PathSpec()) + """Gitignore-like patterns of files (relative to docs dir) that are not intended to be in the nav. + + This marks doc files that are expected not to be in the nav, otherwise they will cause a log message + (see also `validation.nav.omitted_files`). + """ + + site_url = c.Optional(c.URL(is_dir=True)) + """The full URL to where the documentation will be hosted.""" + + site_description = c.Optional(c.Type(str)) + """A description for the documentation project that will be added to the + HTML meta tags.""" + site_author = c.Optional(c.Type(str)) + """The name of the author to add to the HTML meta tags.""" + + theme = c.Theme(default='mkdocs') + """The MkDocs theme for the documentation.""" + + docs_dir = c.DocsDir(default='docs', exists=True) + """The directory containing the documentation markdown.""" + + site_dir = c.SiteDir(default='site') + """The directory where the site will be built to""" + + copyright = c.Optional(c.Type(str)) + """A copyright notice to add to the footer of documentation.""" + + google_analytics = c.Deprecated( + message=( + 'The configuration option {} has been deprecated and ' + 'will be removed in a future release of MkDocs. See the ' + 'options available on your theme for an alternative.' + ), + option_type=c.Type(list, length=2), + ) + """set of values for Google analytics containing the account IO and domain + this should look like, ['UA-27795084-5', 'mkdocs.org']""" + + dev_addr = c.IpAddress(default='127.0.0.1:8000') + """The address on which to serve the live reloading docs server.""" + + use_directory_urls = c.Type(bool, default=True) + """If `True`, use `/index.hmtl` style files with hyperlinks to + the directory.If `False`, use `.html style file with + hyperlinks to the file. + True generates nicer URLs, but False is useful if browsing the output on + a filesystem.""" + + repo_url = c.Optional(c.URL()) + """Specify a link to the project source repo to be included + in the documentation pages.""" + + repo_name = c.Optional(c.RepoName('repo_url')) + """A name to use for the link to the project source repo. + Default, If repo_url is unset then None, otherwise + "GitHub", "Bitbucket" or "GitLab" for known url or Hostname + for unknown urls.""" + + edit_uri_template = c.Optional(c.EditURITemplate('edit_uri')) + edit_uri = c.Optional(c.EditURI('repo_url')) + """Specify a URI to the docs dir in the project source repo, relative to the + repo_url. When set, a link directly to the page in the source repo will + be added to the generated HTML. If repo_url is not set also, this option + is ignored.""" + + extra_css = c.Type(list, default=[]) + extra_javascript = c.ListOfItems(c.ExtraScript(), default=[]) + """Specify which css or javascript files from the docs directory should be + additionally included in the site.""" + + extra_templates = c.Type(list, default=[]) + """Similar to the above, but each template (HTML or XML) will be build with + Jinja2 and the global context.""" + + markdown_extensions = c.MarkdownExtensions( + builtins=['toc', 'tables', 'fenced_code'], configkey='mdx_configs' + ) + """PyMarkdown extension names.""" + + mdx_configs = c.Private[Dict[str, dict]]() + """PyMarkdown extension configs. Populated from `markdown_extensions`.""" + + strict = c.Type(bool, default=False) + """Enabling strict mode causes MkDocs to stop the build when a problem is + encountered rather than display an error.""" + + remote_branch = c.Type(str, default='gh-pages') + """The remote branch to commit to when using gh-deploy.""" + + remote_name = c.Type(str, default='origin') + """The remote name to push to when using gh-deploy.""" + + extra = c.SubConfig() + """extra is a mapping/dictionary of data that is passed to the template. + This allows template authors to require extra configuration that not + relevant to all themes and doesn't need to be explicitly supported by + MkDocs itself. A good example here would be including the current + project version.""" + + plugins = c.Plugins(theme_key='theme', default=['search']) + """A list of plugins. Each item may contain a string name or a key value pair. + A key value pair should be the string name (as the key) and a dict of config + options (as the value).""" + + hooks = c.Hooks('plugins') + """A list of filenames that will be imported as Python modules and used as + an instance of a plugin each.""" + + watch = c.ListOfPaths(default=[]) + """A list of extra paths to watch while running `mkdocs serve`.""" + + class Validation(base.Config): + class NavValidation(base.Config): + omitted_files = c._LogLevel(default='info') + """Warning level for when a doc file is never mentioned in the navigation. + For granular configuration, see `not_in_nav`.""" + + not_found = c._LogLevel(default='warn') + """Warning level for when the navigation links to a relative path that isn't an existing page on the site.""" + + absolute_links = c._LogLevel(default='info') + """Warning level for when the navigation links to an absolute path (starting with `/`).""" + + nav = c.SubConfig(NavValidation) + + class LinksValidation(base.Config): + not_found = c._LogLevel(default='warn') + """Warning level for when a Markdown doc links to a relative path that isn't an existing document on the site.""" + + absolute_links = c._LogLevel(default='info') + """Warning level for when a Markdown doc links to an absolute path (starting with `/`).""" + + unrecognized_links = c._LogLevel(default='info') + """Warning level for when a Markdown doc links to a relative path that doesn't look like + it could be a valid internal link. For example, if the link ends with `/`.""" + + links = c.SubConfig(LinksValidation) + + validation = c.PropagatingSubConfig[Validation]() + + _current_page: mkdocs.structure.pages.Page | None = None + """The currently rendered page. Please do not access this and instead + rely on the `page` argument to event handlers.""" + + def load_dict(self, patch: dict) -> None: + super().load_dict(patch) + if 'config_file_path' in patch: + raise base.ValidationError("Can't set config_file_path in config") + + def load_file(self, config_file: IO) -> None: + """Load config options from the open file descriptor of a YAML file.""" + loader = get_yaml_loader(config=self) + self.load_dict(yaml_load(config_file, loader)) + + +def get_schema() -> base.PlainConfigSchema: + """Soft-deprecated, do not use.""" + return MkDocsConfig._schema diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad27a7dd7163a9723231efe8d5b437f0e33cff04 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5b8f3d86242e1822dce5ce4ecfbc12080c5b8e27 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/__init__.py @@ -0,0 +1,119 @@ +from __future__ import annotations + +import logging +import os +from typing import TYPE_CHECKING, List + +from mkdocs import utils +from mkdocs.config import base +from mkdocs.config import config_options as c +from mkdocs.contrib.search.search_index import SearchIndex +from mkdocs.plugins import BasePlugin + +if TYPE_CHECKING: + from mkdocs.config.defaults import MkDocsConfig + from mkdocs.structure.pages import Page + from mkdocs.util.templates import TemplateContext + +log = logging.getLogger(__name__) +base_path = os.path.dirname(os.path.abspath(__file__)) + + +class LangOption(c.OptionallyRequired[List[str]]): + """Validate Language(s) provided in config are known languages.""" + + def get_lunr_supported_lang(self, lang): + fallback = {'uk': 'ru'} + for lang_part in lang.split("_"): + lang_part = lang_part.lower() + lang_part = fallback.get(lang_part, lang_part) + if os.path.isfile(os.path.join(base_path, 'lunr-language', f'lunr.{lang_part}.js')): + return lang_part + + def run_validation(self, value: object): + if isinstance(value, str): + value = [value] + if not isinstance(value, list): + raise c.ValidationError('Expected a list of language codes.') + for lang in value[:]: + if lang != 'en': + lang_detected = self.get_lunr_supported_lang(lang) + if not lang_detected: + log.info(f"Option search.lang '{lang}' is not supported, falling back to 'en'") + value.remove(lang) + if 'en' not in value: + value.append('en') + elif lang_detected != lang: + value.remove(lang) + value.append(lang_detected) + log.info(f"Option search.lang '{lang}' switched to '{lang_detected}'") + return value + + +class _PluginConfig(base.Config): + lang = c.Optional(LangOption()) + separator = c.Type(str, default=r'[\s\-]+') + min_search_length = c.Type(int, default=3) + prebuild_index = c.Choice((False, True, 'node', 'python'), default=False) + indexing = c.Choice(('full', 'sections', 'titles'), default='full') + + +class SearchPlugin(BasePlugin[_PluginConfig]): + """Add a search feature to MkDocs.""" + + def on_config(self, config: MkDocsConfig, **kwargs) -> MkDocsConfig: + "Add plugin templates and scripts to config." + if config.theme.get('include_search_page'): + config.theme.static_templates.add('search.html') + if not config.theme.get('search_index_only'): + path = os.path.join(base_path, 'templates') + config.theme.dirs.append(path) + if 'search/main.js' not in config.extra_javascript: + config.extra_javascript.append('search/main.js') # type: ignore + if self.config.lang is None: + # lang setting undefined. Set default based on theme locale + validate = _PluginConfig.lang.run_validation + self.config.lang = validate(config.theme.locale.language) + # The `python` method of `prebuild_index` is pending deprecation as of version 1.2. + # TODO: Raise a deprecation warning in a future release (1.3?). + if self.config.prebuild_index == 'python': + log.info( + "The 'python' method of the search plugin's 'prebuild_index' config option " + "is pending deprecation and will not be supported in a future release." + ) + return config + + def on_pre_build(self, config: MkDocsConfig, **kwargs) -> None: + "Create search index instance for later use." + self.search_index = SearchIndex(**self.config) + + def on_page_context(self, context: TemplateContext, page: Page, **kwargs) -> None: + "Add page to search index." + self.search_index.add_entry_from_context(page) + + def on_post_build(self, config: MkDocsConfig, **kwargs) -> None: + "Build search index." + output_base_path = os.path.join(config.site_dir, 'search') + search_index = self.search_index.generate_search_index() + json_output_path = os.path.join(output_base_path, 'search_index.json') + utils.write_file(search_index.encode('utf-8'), json_output_path) + + assert self.config.lang is not None + if not config.theme.get('search_index_only'): + # Include language support files in output. Copy them directly + # so that only the needed files are included. + files = [] + if len(self.config.lang) > 1 or 'en' not in self.config.lang: + files.append('lunr.stemmer.support.js') + if len(self.config.lang) > 1: + files.append('lunr.multi.js') + if 'ja' in self.config.lang or 'jp' in self.config.lang: + files.append('tinyseg.js') + for lang in self.config.lang: + if lang != 'en': + files.append(f'lunr.{lang}.js') + + for filename in files: + from_path = os.path.join(base_path, 'lunr-language', filename) + to_path = os.path.join(output_base_path, filename) + utils.copy_file(from_path, to_path) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..21094674bf40d48b60de73e1141de70689752743 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/__pycache__/search_index.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/__pycache__/search_index.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..764f8e0210f2c7d7724228d0b324de5b375f6702 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/__pycache__/search_index.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.ar.js b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.ar.js new file mode 100644 index 0000000000000000000000000000000000000000..1650ede56c9b15ee8ce73e158333417606ab487c --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.ar.js @@ -0,0 +1,381 @@ +/*! + * Lunr languages, `Arabic` language + * https://github.com/MihaiValentin/lunr-languages + * + * Copyright 2018, Dalia Al-Shahrabi + * http://www.mozilla.org/MPL/ + */ +/*! + * based on + * Kazem Taghva, Rania Elkhoury, and Jeffrey Coombs (2005) + * Meryeme Hadni, Abdelmonaime Lachkar, and S. Alaoui Ouatik (2012) + * + * Snowball JavaScript Library v0.3 + * http://code.google.com/p/urim/ + * http://snowball.tartarus.org/ + * + * Copyright 2010, Oleg Mazko + * http://www.mozilla.org/MPL/ + */ + +/** + * export the module via AMD, CommonJS or as a browser global + * Export code from https://github.com/umdjs/umd/blob/master/returnExports.js + */ +; +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(factory) + } else if (typeof exports === 'object') { + /** + * Node. Does not work with strict CommonJS, but + * only CommonJS-like environments that support module.exports, + * like Node. + */ + module.exports = factory() + } else { + // Browser globals (root is window) + factory()(root.lunr); + } +}(this, function() { + /** + * Just return a value to define the module export. + * This example returns an object, but the module + * can return a function as the exported value. + */ + return function(lunr) { + /* throw error if lunr is not yet included */ + if ('undefined' === typeof lunr) { + throw new Error('Lunr is not present. Please include / require Lunr before this script.'); + } + + /* throw error if lunr stemmer support is not yet included */ + if ('undefined' === typeof lunr.stemmerSupport) { + throw new Error('Lunr stemmer support is not present. Please include / require Lunr stemmer support before this script.'); + } + + /* register specific locale function */ + lunr.ar = function() { + this.pipeline.reset(); + this.pipeline.add( + lunr.ar.trimmer, + lunr.ar.stopWordFilter, + lunr.ar.stemmer + ); + + // for lunr version 2 + // this is necessary so that every searched word is also stemmed before + // in lunr <= 1 this is not needed, as it is done using the normal pipeline + if (this.searchPipeline) { + this.searchPipeline.reset(); + this.searchPipeline.add(lunr.ar.stemmer) + } + }; + + /* lunr trimmer function */ + lunr.ar.wordCharacters = "\u0621-\u065b\u0671\u0640"; + lunr.ar.trimmer = lunr.trimmerSupport.generateTrimmer(lunr.ar.wordCharacters); + + lunr.Pipeline.registerFunction(lunr.ar.trimmer, 'trimmer-ar'); + + /* lunr stemmer function */ + lunr.ar.stemmer = (function() { + var self = this; + var word = ''; + self.result = false; + self.preRemoved = false; + self.sufRemoved = false; + + //prefix data + self.pre = { + pre1: 'ف ك ب و س ل ن ا ي ت', + pre2: 'ال لل', + pre3: 'بال وال فال تال كال ولل', + pre4: 'فبال كبال وبال وكال' + }; + + //suffix data + self.suf = { + suf1: 'ه ك ت ن ا ي', + suf2: 'نك نه ها وك يا اه ون ين تن تم نا وا ان كم كن ني نن ما هم هن تك ته ات يه', + suf3: 'تين كهم نيه نهم ونه وها يهم ونا ونك وني وهم تكم تنا تها تني تهم كما كها ناه نكم هنا تان يها', + suf4: 'كموه ناها ونني ونهم تكما تموه تكاه كماه ناكم ناهم نيها وننا' + } + + //arabic language patterns and alternative mapping for patterns + self.patterns = JSON.parse('{"pt43":[{"pt":[{"c":"ا","l":1}]},{"pt":[{"c":"ا,ت,ن,ي","l":0}],"mPt":[{"c":"ف","l":0,"m":1},{"c":"ع","l":1,"m":2},{"c":"ل","l":2,"m":3}]},{"pt":[{"c":"و","l":2}],"mPt":[{"c":"ف","l":0,"m":0},{"c":"ع","l":1,"m":1},{"c":"ل","l":2,"m":3}]},{"pt":[{"c":"ا","l":2}]},{"pt":[{"c":"ي","l":2}],"mPt":[{"c":"ف","l":0,"m":0},{"c":"ع","l":1,"m":1},{"c":"ا","l":2},{"c":"ل","l":3,"m":3}]},{"pt":[{"c":"م","l":0}]}],"pt53":[{"pt":[{"c":"ت","l":0},{"c":"ا","l":2}]},{"pt":[{"c":"ا,ن,ت,ي","l":0},{"c":"ت","l":2}],"mPt":[{"c":"ا","l":0},{"c":"ف","l":1,"m":1},{"c":"ت","l":2},{"c":"ع","l":3,"m":3},{"c":"ا","l":4},{"c":"ل","l":5,"m":4}]},{"pt":[{"c":"ا","l":0},{"c":"ا","l":2}],"mPt":[{"c":"ا","l":0},{"c":"ف","l":1,"m":1},{"c":"ع","l":2,"m":3},{"c":"ل","l":3,"m":4},{"c":"ا","l":4},{"c":"ل","l":5,"m":4}]},{"pt":[{"c":"ا","l":0},{"c":"ا","l":3}],"mPt":[{"c":"ف","l":0,"m":1},{"c":"ع","l":1,"m":2},{"c":"ل","l":2,"m":4}]},{"pt":[{"c":"ا","l":3},{"c":"ن","l":4}]},{"pt":[{"c":"ت","l":0},{"c":"ي","l":3}]},{"pt":[{"c":"م","l":0},{"c":"و","l":3}]},{"pt":[{"c":"ا","l":1},{"c":"و","l":3}]},{"pt":[{"c":"و","l":1},{"c":"ا","l":2}]},{"pt":[{"c":"م","l":0},{"c":"ا","l":3}]},{"pt":[{"c":"م","l":0},{"c":"ي","l":3}]},{"pt":[{"c":"ا","l":2},{"c":"ن","l":3}]},{"pt":[{"c":"م","l":0},{"c":"ن","l":1}],"mPt":[{"c":"ا","l":0},{"c":"ن","l":1},{"c":"ف","l":2,"m":2},{"c":"ع","l":3,"m":3},{"c":"ا","l":4},{"c":"ل","l":5,"m":4}]},{"pt":[{"c":"م","l":0},{"c":"ت","l":2}],"mPt":[{"c":"ا","l":0},{"c":"ف","l":1,"m":1},{"c":"ت","l":2},{"c":"ع","l":3,"m":3},{"c":"ا","l":4},{"c":"ل","l":5,"m":4}]},{"pt":[{"c":"م","l":0},{"c":"ا","l":2}]},{"pt":[{"c":"م","l":1},{"c":"ا","l":3}]},{"pt":[{"c":"ي,ت,ا,ن","l":0},{"c":"ت","l":1}],"mPt":[{"c":"ف","l":0,"m":2},{"c":"ع","l":1,"m":3},{"c":"ا","l":2},{"c":"ل","l":3,"m":4}]},{"pt":[{"c":"ت,ي,ا,ن","l":0},{"c":"ت","l":2}],"mPt":[{"c":"ا","l":0},{"c":"ف","l":1,"m":1},{"c":"ت","l":2},{"c":"ع","l":3,"m":3},{"c":"ا","l":4},{"c":"ل","l":5,"m":4}]},{"pt":[{"c":"ا","l":2},{"c":"ي","l":3}]},{"pt":[{"c":"ا,ي,ت,ن","l":0},{"c":"ن","l":1}],"mPt":[{"c":"ا","l":0},{"c":"ن","l":1},{"c":"ف","l":2,"m":2},{"c":"ع","l":3,"m":3},{"c":"ا","l":4},{"c":"ل","l":5,"m":4}]},{"pt":[{"c":"ا","l":3},{"c":"ء","l":4}]}],"pt63":[{"pt":[{"c":"ا","l":0},{"c":"ت","l":2},{"c":"ا","l":4}]},{"pt":[{"c":"ا,ت,ن,ي","l":0},{"c":"س","l":1},{"c":"ت","l":2}],"mPt":[{"c":"ا","l":0},{"c":"س","l":1},{"c":"ت","l":2},{"c":"ف","l":3,"m":3},{"c":"ع","l":4,"m":4},{"c":"ا","l":5},{"c":"ل","l":6,"m":5}]},{"pt":[{"c":"ا,ن,ت,ي","l":0},{"c":"و","l":3}]},{"pt":[{"c":"م","l":0},{"c":"س","l":1},{"c":"ت","l":2}],"mPt":[{"c":"ا","l":0},{"c":"س","l":1},{"c":"ت","l":2},{"c":"ف","l":3,"m":3},{"c":"ع","l":4,"m":4},{"c":"ا","l":5},{"c":"ل","l":6,"m":5}]},{"pt":[{"c":"ي","l":1},{"c":"ي","l":3},{"c":"ا","l":4},{"c":"ء","l":5}]},{"pt":[{"c":"ا","l":0},{"c":"ن","l":1},{"c":"ا","l":4}]}],"pt54":[{"pt":[{"c":"ت","l":0}]},{"pt":[{"c":"ا,ي,ت,ن","l":0}],"mPt":[{"c":"ا","l":0},{"c":"ف","l":1,"m":1},{"c":"ع","l":2,"m":2},{"c":"ل","l":3,"m":3},{"c":"ر","l":4,"m":4},{"c":"ا","l":5},{"c":"ر","l":6,"m":4}]},{"pt":[{"c":"م","l":0}],"mPt":[{"c":"ا","l":0},{"c":"ف","l":1,"m":1},{"c":"ع","l":2,"m":2},{"c":"ل","l":3,"m":3},{"c":"ر","l":4,"m":4},{"c":"ا","l":5},{"c":"ر","l":6,"m":4}]},{"pt":[{"c":"ا","l":2}]},{"pt":[{"c":"ا","l":0},{"c":"ن","l":2}]}],"pt64":[{"pt":[{"c":"ا","l":0},{"c":"ا","l":4}]},{"pt":[{"c":"م","l":0},{"c":"ت","l":1}]}],"pt73":[{"pt":[{"c":"ا","l":0},{"c":"س","l":1},{"c":"ت","l":2},{"c":"ا","l":5}]}],"pt75":[{"pt":[{"c":"ا","l":0},{"c":"ا","l":5}]}]}'); + + self.execArray = [ + 'cleanWord', + 'removeDiacritics', + 'cleanAlef', + 'removeStopWords', + 'normalizeHamzaAndAlef', + 'removeStartWaw', + 'removePre432', + 'removeEndTaa', + 'wordCheck' + ]; + + self.stem = function() { + var counter = 0; + self.result = false; + self.preRemoved = false; + self.sufRemoved = false; + while (counter < self.execArray.length && self.result != true) { + self.result = self[self.execArray[counter]](); + counter++; + } + } + + self.setCurrent = function(word) { + self.word = word; + } + + self.getCurrent = function() { + return self.word + } + + /*remove elongating character and test that the word does not contain non-arabic characters. + If the word contains special characters, don't stem. */ + self.cleanWord = function() { + var wordCharacters = "\u0621-\u065b\u0671\u0640"; + var testRegex = new RegExp("[^" + wordCharacters + "]"); + self.word = self.word + .replace(new RegExp('\u0640', 'g'), ''); + if (testRegex.test(word)) { + return true; + } + return false; + } + + self.removeDiacritics = function() { + var diacriticsRegex = new RegExp("[\u064b-\u065b]"); + self.word = self.word.replace(/[\u064b-\u065b]/gi, ''); + return false; + } + + /*Replace all variations of alef (آأإٱى) to a plain alef (ا)*/ + self.cleanAlef = function() { + var alefRegex = new RegExp("[\u0622\u0623\u0625\u0671\u0649]"); + self.word = self.word.replace(alefRegex, "\u0627"); + return false; + } + + /* if the word is a stop word, don't stem*/ + self.removeStopWords = function() { + var stopWords = '، اض امين اه اها اي ا اب اجل اجمع اخ اخذ اصبح اضحى اقبل اقل اكثر الا ام اما امامك امامك امسى اما ان انا انت انتم انتما انتن انت انشا انى او اوشك اولئك اولئكم اولاء اولالك اوه اي ايا اين اينما اي ان اي اف اذ اذا اذا اذما اذن الى اليكم اليكما اليكن اليك اليك الا اما ان انما اي اياك اياكم اياكما اياكن ايانا اياه اياها اياهم اياهما اياهن اياي ايه ان ا ابتدا اثر اجل احد اخرى اخلولق اذا اربعة ارتد استحال اطار اعادة اعلنت اف اكثر اكد الالاء الالى الا الاخيرة الان الاول الاولى التى التي الثاني الثانية الذاتي الذى الذي الذين السابق الف اللائي اللاتي اللتان اللتيا اللتين اللذان اللذين اللواتي الماضي المقبل الوقت الى اليوم اما امام امس ان انبرى انقلب انه انها او اول اي ايار ايام ايضا ب بات باسم بان بخ برس بسبب بس بشكل بضع بطان بعد بعض بك بكم بكما بكن بل بلى بما بماذا بمن بن بنا به بها بي بيد بين بس بله بئس تان تانك تبدل تجاه تحول تلقاء تلك تلكم تلكما تم تينك تين ته تي ثلاثة ثم ثم ثمة ثم جعل جلل جميع جير حار حاشا حاليا حاي حتى حرى حسب حم حوالى حول حيث حيثما حين حي حبذا حتى حذار خلا خلال دون دونك ذا ذات ذاك ذانك ذان ذلك ذلكم ذلكما ذلكن ذو ذوا ذواتا ذواتي ذيت ذينك ذين ذه ذي راح رجع رويدك ريث رب زيارة سبحان سرعان سنة سنوات سوف سوى ساء ساءما شبه شخصا شرع شتان صار صباح صفر صه صه ضد ضمن طاق طالما طفق طق ظل عاد عام عاما عامة عدا عدة عدد عدم عسى عشر عشرة علق على عليك عليه عليها عل عن عند عندما عوض عين عدس عما غدا غير ف فان فلان فو فى في فيم فيما فيه فيها قال قام قبل قد قط قلما قوة كانما كاين كاي كاين كاد كان كانت كذا كذلك كرب كل كلا كلاهما كلتا كلم كليكما كليهما كلما كلا كم كما كي كيت كيف كيفما كان كخ لئن لا لات لاسيما لدن لدى لعمر لقاء لك لكم لكما لكن لكنما لكي لكيلا للامم لم لما لما لن لنا له لها لو لوكالة لولا لوما لي لست لست لستم لستما لستن لست لسن لعل لكن ليت ليس ليسا ليستا ليست ليسوا لسنا ما ماانفك مابرح مادام ماذا مازال مافتئ مايو متى مثل مذ مساء مع معاذ مقابل مكانكم مكانكما مكانكن مكانك مليار مليون مما ممن من منذ منها مه مهما من من نحن نحو نعم نفس نفسه نهاية نخ نعما نعم ها هاؤم هاك هاهنا هب هذا هذه هكذا هل هلم هلا هم هما هن هنا هناك هنالك هو هي هيا هيت هيا هؤلاء هاتان هاتين هاته هاتي هج هذا هذان هذين هذه هذي هيهات و وا واحد واضاف واضافت واكد وان واها واوضح وراءك وفي وقال وقالت وقد وقف وكان وكانت ولا ولم ومن وهو وهي ويكان وي وشكان يكون يمكن يوم ايان'.split(' '); + if (stopWords.indexOf(self.word) >= 0) { + return true; + } + } + + /* changes ؤ ئ to ء and removes alef if at the end of the word*/ + self.normalizeHamzaAndAlef = function() { + self.word = self.word.replace('\u0624', '\u0621'); + self.word = self.word.replace('\u0626', '\u0621'); + self.word = self.word.replace(/([\u0627])\1+/gi, '\u0627'); + return false; + } + + /*remove end taa marboota ة*/ + self.removeEndTaa = function() { + if (self.word.length > 2) { + self.word = self.word.replace(/[\u0627]$/, ''); + self.word = self.word.replace('\u0629', ''); + return false; + } else return true; + } + + /* if the word starts with double waw وو keep only one of them */ + self.removeStartWaw = function() { + if (self.word.length > 3 && self.word[0] == '\u0648' && self.word[1] == '\u0648') { + self.word = self.word.slice(1); + } + return false; + } + + /* remove prefixes of size 4, 3 and 2 characters */ + self.removePre432 = function() { + var word = self.word; + if (self.word.length >= 7) { + var pre4Regex = new RegExp('^(' + self.pre.pre4.split(' ').join('|') + ')') + self.word = self.word.replace(pre4Regex, ''); + } + if (self.word == word && self.word.length >= 6) { + var pre3Regex = new RegExp('^(' + self.pre.pre3.split(' ').join('|') + ')') + self.word = self.word.replace(pre3Regex, ''); + } + if (self.word == word && self.word.length >= 5) { + var pre2Regex = new RegExp('^(' + self.pre.pre2.split(' ').join('|') + ')') + self.word = self.word.replace(pre2Regex, ''); + } + if (word != self.word) self.preRemoved = true; + return false; + } + + /* check the word against word patterns. If the word matches a pattern, map it to the + alternative pattern if available then stop stemming. */ + self.patternCheck = function(pattern) { + var patternMatch = false; + for (var i = 0; i < pattern.length; i++) { + var currentPatternCheck = true; + for (var j = 0; j < pattern[i].pt.length; j++) { + var chars = pattern[i].pt[j].c.split(','); + var charMatch = false; + chars.forEach(function(el) { + if (self.word[pattern[i].pt[j].l] == el) { + charMatch = true; + } + }) + if (!charMatch) { + currentPatternCheck = false; + break; + } + } + if (currentPatternCheck == true) { + if (pattern[i].mPt) { + var newWord = []; + for (var k = 0; k < pattern[i].mPt.length; k++) { + if (pattern[i].mPt[k].m != null) { + newWord[pattern[i].mPt[k].l] = self.word[pattern[i].mPt[k].m] + } else { + newWord[pattern[i].mPt[k].l] = pattern[i].mPt[k].c + } + } + self.word = newWord.join(''); + } + self.result = true; + break; + } + } + } + + /* remove prefixes of size 1 char*/ + self.removePre1 = function() { + var word = self.word; + if (self.preRemoved == false) + if (self.word.length > 3) { + var pre1Regex = new RegExp('^(' + self.pre.pre1.split(' ').join('|') + ')') + self.word = self.word.replace(pre1Regex, ''); + } + if (word != self.word) self.preRemoved = true; + return false; + } + + /*remove suffixes of size 1 char */ + self.removeSuf1 = function() { + var word = self.word; + if (self.sufRemoved == false) + if (self.word.length > 3) { + var suf1Regex = new RegExp('(' + self.suf.suf1.split(' ').join('|') + ')$') + self.word = self.word.replace(suf1Regex, ''); + } + if (word != self.word) self.sufRemoved = true; + return false; + } + + /*remove suffixes of size 4, 3 and 2 chars*/ + self.removeSuf432 = function() { + var word = self.word; + if (self.word.length >= 6) { + var suf4Regex = new RegExp('(' + self.suf.suf4.split(' ').join('|') + ')$') + self.word = self.word.replace(suf4Regex, ''); + } + if (self.word == word && self.word.length >= 5) { + var suf3Regex = new RegExp('(' + self.suf.suf3.split(' ').join('|') + ')$') + self.word = self.word.replace(suf3Regex, ''); + } + if (self.word == word && self.word.length >= 4) { + var suf2Regex = new RegExp('(' + self.suf.suf2.split(' ').join('|') + ')$') + self.word = self.word.replace(suf2Regex, ''); + } + if (word != self.word) self.sufRemoved = true; + return false; + } + + /*check the word length and decide what is the next step accordingly*/ + self.wordCheck = function() { + var word = self.word; + var word7Exec = [self.removeSuf432, self.removeSuf1, self.removePre1] + var counter = 0; + var patternChecked = false; + while (self.word.length >= 7 && !self.result && counter < word7Exec.length) { + if (self.word.length == 7 && !patternChecked) { + self.checkPattern73(); + patternChecked = true; + } else { + word7Exec[counter](); + counter++; + patternChecked = false; + } + } + + var word6Exec = [self.checkPattern63, self.removeSuf432, self.removeSuf1, self.removePre1, self.checkPattern64]; + counter = 0; + while (self.word.length == 6 && !self.result && counter < word6Exec.length) { + word6Exec[counter](); + counter++; + } + + var word5Exec = [self.checkPattern53, self.removeSuf432, self.removeSuf1, self.removePre1, self.checkPattern54]; + counter = 0; + while (self.word.length == 5 && !self.result && counter < word5Exec.length) { + word5Exec[counter](); + counter++; + } + + var word4Exec = [self.checkPattern43, self.removeSuf1, self.removePre1, self.removeSuf432]; + counter = 0; + while (self.word.length == 4 && !self.result && counter < word4Exec.length) { + word4Exec[counter](); + counter++; + } + return true; + } + + self.checkPattern43 = function() { + self.patternCheck(self.patterns.pt43) + } + self.checkPattern53 = function() { + self.patternCheck(self.patterns.pt53) + } + self.checkPattern54 = function() { + self.patternCheck(self.patterns.pt54) + } + self.checkPattern63 = function() { + self.patternCheck(self.patterns.pt63) + } + self.checkPattern64 = function() { + self.patternCheck(self.patterns.pt64) + } + self.checkPattern73 = function() { + self.patternCheck(self.patterns.pt73) + } + + /* and return a function that stems a word for the current locale */ + return function(token) { + // for lunr version 2 + if (typeof token.update === "function") { + return token.update(function(word) { + self.setCurrent(word); + self.stem(); + return self.getCurrent(); + }) + } else { // for lunr version <= 1 + self.setCurrent(token); + self.stem(); + return self.getCurrent(); + } + + } + })(); + + lunr.Pipeline.registerFunction(lunr.ar.stemmer, 'stemmer-ar'); + + lunr.ar.stopWordFilter = lunr.generateStopWordFilter('، اض امين اه اها اي ا اب اجل اجمع اخ اخذ اصبح اضحى اقبل اقل اكثر الا ام اما امامك امامك امسى اما ان انا انت انتم انتما انتن انت انشا انى او اوشك اولئك اولئكم اولاء اولالك اوه اي ايا اين اينما اي ان اي اف اذ اذا اذا اذما اذن الى اليكم اليكما اليكن اليك اليك الا اما ان انما اي اياك اياكم اياكما اياكن ايانا اياه اياها اياهم اياهما اياهن اياي ايه ان ا ابتدا اثر اجل احد اخرى اخلولق اذا اربعة ارتد استحال اطار اعادة اعلنت اف اكثر اكد الالاء الالى الا الاخيرة الان الاول الاولى التى التي الثاني الثانية الذاتي الذى الذي الذين السابق الف اللائي اللاتي اللتان اللتيا اللتين اللذان اللذين اللواتي الماضي المقبل الوقت الى اليوم اما امام امس ان انبرى انقلب انه انها او اول اي ايار ايام ايضا ب بات باسم بان بخ برس بسبب بس بشكل بضع بطان بعد بعض بك بكم بكما بكن بل بلى بما بماذا بمن بن بنا به بها بي بيد بين بس بله بئس تان تانك تبدل تجاه تحول تلقاء تلك تلكم تلكما تم تينك تين ته تي ثلاثة ثم ثم ثمة ثم جعل جلل جميع جير حار حاشا حاليا حاي حتى حرى حسب حم حوالى حول حيث حيثما حين حي حبذا حتى حذار خلا خلال دون دونك ذا ذات ذاك ذانك ذان ذلك ذلكم ذلكما ذلكن ذو ذوا ذواتا ذواتي ذيت ذينك ذين ذه ذي راح رجع رويدك ريث رب زيارة سبحان سرعان سنة سنوات سوف سوى ساء ساءما شبه شخصا شرع شتان صار صباح صفر صه صه ضد ضمن طاق طالما طفق طق ظل عاد عام عاما عامة عدا عدة عدد عدم عسى عشر عشرة علق على عليك عليه عليها عل عن عند عندما عوض عين عدس عما غدا غير ف فان فلان فو فى في فيم فيما فيه فيها قال قام قبل قد قط قلما قوة كانما كاين كاي كاين كاد كان كانت كذا كذلك كرب كل كلا كلاهما كلتا كلم كليكما كليهما كلما كلا كم كما كي كيت كيف كيفما كان كخ لئن لا لات لاسيما لدن لدى لعمر لقاء لك لكم لكما لكن لكنما لكي لكيلا للامم لم لما لما لن لنا له لها لو لوكالة لولا لوما لي لست لست لستم لستما لستن لست لسن لعل لكن ليت ليس ليسا ليستا ليست ليسوا لسنا ما ماانفك مابرح مادام ماذا مازال مافتئ مايو متى مثل مذ مساء مع معاذ مقابل مكانكم مكانكما مكانكن مكانك مليار مليون مما ممن من منذ منها مه مهما من من نحن نحو نعم نفس نفسه نهاية نخ نعما نعم ها هاؤم هاك هاهنا هب هذا هذه هكذا هل هلم هلا هم هما هن هنا هناك هنالك هو هي هيا هيت هيا هؤلاء هاتان هاتين هاته هاتي هج هذا هذان هذين هذه هذي هيهات وا واحد واضاف واضافت واكد وان واها واوضح وراءك وفي وقال وقالت وقد وقف وكان وكانت ولا ولم ومن وهو وهي ويكان وي وشكان يكون يمكن يوم ايان'.split(' ')); + + lunr.Pipeline.registerFunction(lunr.ar.stopWordFilter, 'stopWordFilter-ar'); + }; +})) \ No newline at end of file diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.da.js b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.da.js new file mode 100644 index 0000000000000000000000000000000000000000..28b5c2d5d8e9119187166d25a07b510355f6ecf7 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.da.js @@ -0,0 +1,284 @@ +/*! + * Lunr languages, `Danish` language + * https://github.com/MihaiValentin/lunr-languages + * + * Copyright 2014, Mihai Valentin + * http://www.mozilla.org/MPL/ + */ +/*! + * based on + * Snowball JavaScript Library v0.3 + * http://code.google.com/p/urim/ + * http://snowball.tartarus.org/ + * + * Copyright 2010, Oleg Mazko + * http://www.mozilla.org/MPL/ + */ + +/** + * export the module via AMD, CommonJS or as a browser global + * Export code from https://github.com/umdjs/umd/blob/master/returnExports.js + */ +; +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(factory) + } else if (typeof exports === 'object') { + /** + * Node. Does not work with strict CommonJS, but + * only CommonJS-like environments that support module.exports, + * like Node. + */ + module.exports = factory() + } else { + // Browser globals (root is window) + factory()(root.lunr); + } +}(this, function() { + /** + * Just return a value to define the module export. + * This example returns an object, but the module + * can return a function as the exported value. + */ + return function(lunr) { + /* throw error if lunr is not yet included */ + if ('undefined' === typeof lunr) { + throw new Error('Lunr is not present. Please include / require Lunr before this script.'); + } + + /* throw error if lunr stemmer support is not yet included */ + if ('undefined' === typeof lunr.stemmerSupport) { + throw new Error('Lunr stemmer support is not present. Please include / require Lunr stemmer support before this script.'); + } + + /* register specific locale function */ + lunr.da = function() { + this.pipeline.reset(); + this.pipeline.add( + lunr.da.trimmer, + lunr.da.stopWordFilter, + lunr.da.stemmer + ); + + // for lunr version 2 + // this is necessary so that every searched word is also stemmed before + // in lunr <= 1 this is not needed, as it is done using the normal pipeline + if (this.searchPipeline) { + this.searchPipeline.reset(); + this.searchPipeline.add(lunr.da.stemmer) + } + }; + + /* lunr trimmer function */ + lunr.da.wordCharacters = "A-Za-z\xAA\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02B8\u02E0-\u02E4\u1D00-\u1D25\u1D2C-\u1D5C\u1D62-\u1D65\u1D6B-\u1D77\u1D79-\u1DBE\u1E00-\u1EFF\u2071\u207F\u2090-\u209C\u212A\u212B\u2132\u214E\u2160-\u2188\u2C60-\u2C7F\uA722-\uA787\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA7FF\uAB30-\uAB5A\uAB5C-\uAB64\uFB00-\uFB06\uFF21-\uFF3A\uFF41-\uFF5A"; + lunr.da.trimmer = lunr.trimmerSupport.generateTrimmer(lunr.da.wordCharacters); + + lunr.Pipeline.registerFunction(lunr.da.trimmer, 'trimmer-da'); + + /* lunr stemmer function */ + lunr.da.stemmer = (function() { + /* create the wrapped stemmer object */ + var Among = lunr.stemmerSupport.Among, + SnowballProgram = lunr.stemmerSupport.SnowballProgram, + st = new function DanishStemmer() { + var a_0 = [new Among("hed", -1, 1), new Among("ethed", 0, 1), + new Among("ered", -1, 1), new Among("e", -1, 1), + new Among("erede", 3, 1), new Among("ende", 3, 1), + new Among("erende", 5, 1), new Among("ene", 3, 1), + new Among("erne", 3, 1), new Among("ere", 3, 1), + new Among("en", -1, 1), new Among("heden", 10, 1), + new Among("eren", 10, 1), new Among("er", -1, 1), + new Among("heder", 13, 1), new Among("erer", 13, 1), + new Among("s", -1, 2), new Among("heds", 16, 1), + new Among("es", 16, 1), new Among("endes", 18, 1), + new Among("erendes", 19, 1), new Among("enes", 18, 1), + new Among("ernes", 18, 1), new Among("eres", 18, 1), + new Among("ens", 16, 1), new Among("hedens", 24, 1), + new Among("erens", 24, 1), new Among("ers", 16, 1), + new Among("ets", 16, 1), new Among("erets", 28, 1), + new Among("et", -1, 1), new Among("eret", 30, 1) + ], + a_1 = [ + new Among("gd", -1, -1), new Among("dt", -1, -1), + new Among("gt", -1, -1), new Among("kt", -1, -1) + ], + a_2 = [ + new Among("ig", -1, 1), new Among("lig", 0, 1), + new Among("elig", 1, 1), new Among("els", -1, 1), + new Among("l\u00F8st", -1, 2) + ], + g_v = [17, 65, 16, 1, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 48, 0, 128 + ], + g_s_ending = [239, 254, 42, 3, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16 + ], + I_x, I_p1, S_ch, sbp = new SnowballProgram(); + this.setCurrent = function(word) { + sbp.setCurrent(word); + }; + this.getCurrent = function() { + return sbp.getCurrent(); + }; + + function r_mark_regions() { + var v_1, c = sbp.cursor + 3; + I_p1 = sbp.limit; + if (0 <= c && c <= sbp.limit) { + I_x = c; + while (true) { + v_1 = sbp.cursor; + if (sbp.in_grouping(g_v, 97, 248)) { + sbp.cursor = v_1; + break; + } + sbp.cursor = v_1; + if (v_1 >= sbp.limit) + return; + sbp.cursor++; + } + while (!sbp.out_grouping(g_v, 97, 248)) { + if (sbp.cursor >= sbp.limit) + return; + sbp.cursor++; + } + I_p1 = sbp.cursor; + if (I_p1 < I_x) + I_p1 = I_x; + } + } + + function r_main_suffix() { + var among_var, v_1; + if (sbp.cursor >= I_p1) { + v_1 = sbp.limit_backward; + sbp.limit_backward = I_p1; + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_0, 32); + sbp.limit_backward = v_1; + if (among_var) { + sbp.bra = sbp.cursor; + switch (among_var) { + case 1: + sbp.slice_del(); + break; + case 2: + if (sbp.in_grouping_b(g_s_ending, 97, 229)) + sbp.slice_del(); + break; + } + } + } + } + + function r_consonant_pair() { + var v_1 = sbp.limit - sbp.cursor, + v_2; + if (sbp.cursor >= I_p1) { + v_2 = sbp.limit_backward; + sbp.limit_backward = I_p1; + sbp.ket = sbp.cursor; + if (sbp.find_among_b(a_1, 4)) { + sbp.bra = sbp.cursor; + sbp.limit_backward = v_2; + sbp.cursor = sbp.limit - v_1; + if (sbp.cursor > sbp.limit_backward) { + sbp.cursor--; + sbp.bra = sbp.cursor; + sbp.slice_del(); + } + } else + sbp.limit_backward = v_2; + } + } + + function r_other_suffix() { + var among_var, v_1 = sbp.limit - sbp.cursor, + v_2, v_3; + sbp.ket = sbp.cursor; + if (sbp.eq_s_b(2, "st")) { + sbp.bra = sbp.cursor; + if (sbp.eq_s_b(2, "ig")) + sbp.slice_del(); + } + sbp.cursor = sbp.limit - v_1; + if (sbp.cursor >= I_p1) { + v_2 = sbp.limit_backward; + sbp.limit_backward = I_p1; + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_2, 5); + sbp.limit_backward = v_2; + if (among_var) { + sbp.bra = sbp.cursor; + switch (among_var) { + case 1: + sbp.slice_del(); + v_3 = sbp.limit - sbp.cursor; + r_consonant_pair(); + sbp.cursor = sbp.limit - v_3; + break; + case 2: + sbp.slice_from("l\u00F8s"); + break; + } + } + } + } + + function r_undouble() { + var v_1; + if (sbp.cursor >= I_p1) { + v_1 = sbp.limit_backward; + sbp.limit_backward = I_p1; + sbp.ket = sbp.cursor; + if (sbp.out_grouping_b(g_v, 97, 248)) { + sbp.bra = sbp.cursor; + S_ch = sbp.slice_to(S_ch); + sbp.limit_backward = v_1; + if (sbp.eq_v_b(S_ch)) + sbp.slice_del(); + } else + sbp.limit_backward = v_1; + } + } + this.stem = function() { + var v_1 = sbp.cursor; + r_mark_regions(); + sbp.limit_backward = v_1; + sbp.cursor = sbp.limit; + r_main_suffix(); + sbp.cursor = sbp.limit; + r_consonant_pair(); + sbp.cursor = sbp.limit; + r_other_suffix(); + sbp.cursor = sbp.limit; + r_undouble(); + return true; + } + }; + + /* and return a function that stems a word for the current locale */ + return function(token) { + // for lunr version 2 + if (typeof token.update === "function") { + return token.update(function(word) { + st.setCurrent(word); + st.stem(); + return st.getCurrent(); + }) + } else { // for lunr version <= 1 + st.setCurrent(token); + st.stem(); + return st.getCurrent(); + } + } + })(); + + lunr.Pipeline.registerFunction(lunr.da.stemmer, 'stemmer-da'); + + lunr.da.stopWordFilter = lunr.generateStopWordFilter('ad af alle alt anden at blev blive bliver da de dem den denne der deres det dette dig din disse dog du efter eller en end er et for fra ham han hans har havde have hende hendes her hos hun hvad hvis hvor i ikke ind jeg jer jo kunne man mange med meget men mig min mine mit mod ned noget nogle nu når og også om op os over på selv sig sin sine sit skal skulle som sådan thi til ud under var vi vil ville vor være været'.split(' ')); + + lunr.Pipeline.registerFunction(lunr.da.stopWordFilter, 'stopWordFilter-da'); + }; +})) \ No newline at end of file diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.de.js b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.de.js new file mode 100644 index 0000000000000000000000000000000000000000..9e32b0c397bfd16d843f20b05b3981b46e05e9bd --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.de.js @@ -0,0 +1,384 @@ +/*! + * Lunr languages, `German` language + * https://github.com/MihaiValentin/lunr-languages + * + * Copyright 2014, Mihai Valentin + * http://www.mozilla.org/MPL/ + */ +/*! + * based on + * Snowball JavaScript Library v0.3 + * http://code.google.com/p/urim/ + * http://snowball.tartarus.org/ + * + * Copyright 2010, Oleg Mazko + * http://www.mozilla.org/MPL/ + */ + +/** + * export the module via AMD, CommonJS or as a browser global + * Export code from https://github.com/umdjs/umd/blob/master/returnExports.js + */ +; +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(factory) + } else if (typeof exports === 'object') { + /** + * Node. Does not work with strict CommonJS, but + * only CommonJS-like environments that support module.exports, + * like Node. + */ + module.exports = factory() + } else { + // Browser globals (root is window) + factory()(root.lunr); + } +}(this, function() { + /** + * Just return a value to define the module export. + * This example returns an object, but the module + * can return a function as the exported value. + */ + return function(lunr) { + /* throw error if lunr is not yet included */ + if ('undefined' === typeof lunr) { + throw new Error('Lunr is not present. Please include / require Lunr before this script.'); + } + + /* throw error if lunr stemmer support is not yet included */ + if ('undefined' === typeof lunr.stemmerSupport) { + throw new Error('Lunr stemmer support is not present. Please include / require Lunr stemmer support before this script.'); + } + + /* register specific locale function */ + lunr.de = function() { + this.pipeline.reset(); + this.pipeline.add( + lunr.de.trimmer, + lunr.de.stopWordFilter, + lunr.de.stemmer + ); + + // for lunr version 2 + // this is necessary so that every searched word is also stemmed before + // in lunr <= 1 this is not needed, as it is done using the normal pipeline + if (this.searchPipeline) { + this.searchPipeline.reset(); + this.searchPipeline.add(lunr.de.stemmer) + } + }; + + /* lunr trimmer function */ + lunr.de.wordCharacters = "A-Za-z\xAA\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02B8\u02E0-\u02E4\u1D00-\u1D25\u1D2C-\u1D5C\u1D62-\u1D65\u1D6B-\u1D77\u1D79-\u1DBE\u1E00-\u1EFF\u2071\u207F\u2090-\u209C\u212A\u212B\u2132\u214E\u2160-\u2188\u2C60-\u2C7F\uA722-\uA787\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA7FF\uAB30-\uAB5A\uAB5C-\uAB64\uFB00-\uFB06\uFF21-\uFF3A\uFF41-\uFF5A"; + lunr.de.trimmer = lunr.trimmerSupport.generateTrimmer(lunr.de.wordCharacters); + + lunr.Pipeline.registerFunction(lunr.de.trimmer, 'trimmer-de'); + + /* lunr stemmer function */ + lunr.de.stemmer = (function() { + /* create the wrapped stemmer object */ + var Among = lunr.stemmerSupport.Among, + SnowballProgram = lunr.stemmerSupport.SnowballProgram, + st = new function GermanStemmer() { + var a_0 = [new Among("", -1, 6), new Among("U", 0, 2), + new Among("Y", 0, 1), new Among("\u00E4", 0, 3), + new Among("\u00F6", 0, 4), new Among("\u00FC", 0, 5) + ], + a_1 = [ + new Among("e", -1, 2), new Among("em", -1, 1), + new Among("en", -1, 2), new Among("ern", -1, 1), + new Among("er", -1, 1), new Among("s", -1, 3), + new Among("es", 5, 2) + ], + a_2 = [new Among("en", -1, 1), + new Among("er", -1, 1), new Among("st", -1, 2), + new Among("est", 2, 1) + ], + a_3 = [new Among("ig", -1, 1), + new Among("lich", -1, 1) + ], + a_4 = [new Among("end", -1, 1), + new Among("ig", -1, 2), new Among("ung", -1, 1), + new Among("lich", -1, 3), new Among("isch", -1, 2), + new Among("ik", -1, 2), new Among("heit", -1, 3), + new Among("keit", -1, 4) + ], + g_v = [17, 65, 16, 1, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 8, 0, 32, 8 + ], + g_s_ending = [117, 30, 5], + g_st_ending = [ + 117, 30, 4 + ], + I_x, I_p2, I_p1, sbp = new SnowballProgram(); + this.setCurrent = function(word) { + sbp.setCurrent(word); + }; + this.getCurrent = function() { + return sbp.getCurrent(); + }; + + function habr1(c1, c2, v_1) { + if (sbp.eq_s(1, c1)) { + sbp.ket = sbp.cursor; + if (sbp.in_grouping(g_v, 97, 252)) { + sbp.slice_from(c2); + sbp.cursor = v_1; + return true; + } + } + return false; + } + + function r_prelude() { + var v_1 = sbp.cursor, + v_2, v_3, v_4, v_5; + while (true) { + v_2 = sbp.cursor; + sbp.bra = v_2; + if (sbp.eq_s(1, "\u00DF")) { + sbp.ket = sbp.cursor; + sbp.slice_from("ss"); + } else { + if (v_2 >= sbp.limit) + break; + sbp.cursor = v_2 + 1; + } + } + sbp.cursor = v_1; + while (true) { + v_3 = sbp.cursor; + while (true) { + v_4 = sbp.cursor; + if (sbp.in_grouping(g_v, 97, 252)) { + v_5 = sbp.cursor; + sbp.bra = v_5; + if (habr1("u", "U", v_4)) + break; + sbp.cursor = v_5; + if (habr1("y", "Y", v_4)) + break; + } + if (v_4 >= sbp.limit) { + sbp.cursor = v_3; + return; + } + sbp.cursor = v_4 + 1; + } + } + } + + function habr2() { + while (!sbp.in_grouping(g_v, 97, 252)) { + if (sbp.cursor >= sbp.limit) + return true; + sbp.cursor++; + } + while (!sbp.out_grouping(g_v, 97, 252)) { + if (sbp.cursor >= sbp.limit) + return true; + sbp.cursor++; + } + return false; + } + + function r_mark_regions() { + I_p1 = sbp.limit; + I_p2 = I_p1; + var c = sbp.cursor + 3; + if (0 <= c && c <= sbp.limit) { + I_x = c; + if (!habr2()) { + I_p1 = sbp.cursor; + if (I_p1 < I_x) + I_p1 = I_x; + if (!habr2()) + I_p2 = sbp.cursor; + } + } + } + + function r_postlude() { + var among_var, v_1; + while (true) { + v_1 = sbp.cursor; + sbp.bra = v_1; + among_var = sbp.find_among(a_0, 6); + if (!among_var) + return; + sbp.ket = sbp.cursor; + switch (among_var) { + case 1: + sbp.slice_from("y"); + break; + case 2: + case 5: + sbp.slice_from("u"); + break; + case 3: + sbp.slice_from("a"); + break; + case 4: + sbp.slice_from("o"); + break; + case 6: + if (sbp.cursor >= sbp.limit) + return; + sbp.cursor++; + break; + } + } + } + + function r_R1() { + return I_p1 <= sbp.cursor; + } + + function r_R2() { + return I_p2 <= sbp.cursor; + } + + function r_standard_suffix() { + var among_var, v_1 = sbp.limit - sbp.cursor, + v_2, v_3, v_4; + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_1, 7); + if (among_var) { + sbp.bra = sbp.cursor; + if (r_R1()) { + switch (among_var) { + case 1: + sbp.slice_del(); + break; + case 2: + sbp.slice_del(); + sbp.ket = sbp.cursor; + if (sbp.eq_s_b(1, "s")) { + sbp.bra = sbp.cursor; + if (sbp.eq_s_b(3, "nis")) + sbp.slice_del(); + } + break; + case 3: + if (sbp.in_grouping_b(g_s_ending, 98, 116)) + sbp.slice_del(); + break; + } + } + } + sbp.cursor = sbp.limit - v_1; + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_2, 4); + if (among_var) { + sbp.bra = sbp.cursor; + if (r_R1()) { + switch (among_var) { + case 1: + sbp.slice_del(); + break; + case 2: + if (sbp.in_grouping_b(g_st_ending, 98, 116)) { + var c = sbp.cursor - 3; + if (sbp.limit_backward <= c && c <= sbp.limit) { + sbp.cursor = c; + sbp.slice_del(); + } + } + break; + } + } + } + sbp.cursor = sbp.limit - v_1; + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_4, 8); + if (among_var) { + sbp.bra = sbp.cursor; + if (r_R2()) { + switch (among_var) { + case 1: + sbp.slice_del(); + sbp.ket = sbp.cursor; + if (sbp.eq_s_b(2, "ig")) { + sbp.bra = sbp.cursor; + v_2 = sbp.limit - sbp.cursor; + if (!sbp.eq_s_b(1, "e")) { + sbp.cursor = sbp.limit - v_2; + if (r_R2()) + sbp.slice_del(); + } + } + break; + case 2: + v_3 = sbp.limit - sbp.cursor; + if (!sbp.eq_s_b(1, "e")) { + sbp.cursor = sbp.limit - v_3; + sbp.slice_del(); + } + break; + case 3: + sbp.slice_del(); + sbp.ket = sbp.cursor; + v_4 = sbp.limit - sbp.cursor; + if (!sbp.eq_s_b(2, "er")) { + sbp.cursor = sbp.limit - v_4; + if (!sbp.eq_s_b(2, "en")) + break; + } + sbp.bra = sbp.cursor; + if (r_R1()) + sbp.slice_del(); + break; + case 4: + sbp.slice_del(); + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_3, 2); + if (among_var) { + sbp.bra = sbp.cursor; + if (r_R2() && among_var == 1) + sbp.slice_del(); + } + break; + } + } + } + } + this.stem = function() { + var v_1 = sbp.cursor; + r_prelude(); + sbp.cursor = v_1; + r_mark_regions(); + sbp.limit_backward = v_1; + sbp.cursor = sbp.limit; + r_standard_suffix(); + sbp.cursor = sbp.limit_backward; + r_postlude(); + return true; + } + }; + + /* and return a function that stems a word for the current locale */ + return function(token) { + // for lunr version 2 + if (typeof token.update === "function") { + return token.update(function(word) { + st.setCurrent(word); + st.stem(); + return st.getCurrent(); + }) + } else { // for lunr version <= 1 + st.setCurrent(token); + st.stem(); + return st.getCurrent(); + } + } + })(); + + lunr.Pipeline.registerFunction(lunr.de.stemmer, 'stemmer-de'); + + lunr.de.stopWordFilter = lunr.generateStopWordFilter('aber alle allem allen aller alles als also am an ander andere anderem anderen anderer anderes anderm andern anderr anders auch auf aus bei bin bis bist da damit dann das dasselbe dazu daß dein deine deinem deinen deiner deines dem demselben den denn denselben der derer derselbe derselben des desselben dessen dich die dies diese dieselbe dieselben diesem diesen dieser dieses dir doch dort du durch ein eine einem einen einer eines einig einige einigem einigen einiger einiges einmal er es etwas euch euer eure eurem euren eurer eures für gegen gewesen hab habe haben hat hatte hatten hier hin hinter ich ihm ihn ihnen ihr ihre ihrem ihren ihrer ihres im in indem ins ist jede jedem jeden jeder jedes jene jenem jenen jener jenes jetzt kann kein keine keinem keinen keiner keines können könnte machen man manche manchem manchen mancher manches mein meine meinem meinen meiner meines mich mir mit muss musste nach nicht nichts noch nun nur ob oder ohne sehr sein seine seinem seinen seiner seines selbst sich sie sind so solche solchem solchen solcher solches soll sollte sondern sonst um und uns unse unsem unsen unser unses unter viel vom von vor war waren warst was weg weil weiter welche welchem welchen welcher welches wenn werde werden wie wieder will wir wird wirst wo wollen wollte während würde würden zu zum zur zwar zwischen über'.split(' ')); + + lunr.Pipeline.registerFunction(lunr.de.stopWordFilter, 'stopWordFilter-de'); + }; +})) \ No newline at end of file diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.du.js b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.du.js new file mode 100644 index 0000000000000000000000000000000000000000..18edeb8e1b41e5dbb3496437fcb9442c984979c2 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.du.js @@ -0,0 +1,450 @@ +/*! + * Lunr languages, `Dutch` language + * https://github.com/MihaiValentin/lunr-languages + * + * Copyright 2014, Mihai Valentin + * http://www.mozilla.org/MPL/ + */ +/*! + * based on + * Snowball JavaScript Library v0.3 + * http://code.google.com/p/urim/ + * http://snowball.tartarus.org/ + * + * Copyright 2010, Oleg Mazko + * http://www.mozilla.org/MPL/ + */ + +/** + * export the module via AMD, CommonJS or as a browser global + * Export code from https://github.com/umdjs/umd/blob/master/returnExports.js + */ +; +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(factory) + } else if (typeof exports === 'object') { + /** + * Node. Does not work with strict CommonJS, but + * only CommonJS-like environments that support module.exports, + * like Node. + */ + module.exports = factory() + } else { + // Browser globals (root is window) + factory()(root.lunr); + } +}(this, function() { + /** + * Just return a value to define the module export. + * This example returns an object, but the module + * can return a function as the exported value. + */ + return function(lunr) { + /* throw error if lunr is not yet included */ + if ('undefined' === typeof lunr) { + throw new Error('Lunr is not present. Please include / require Lunr before this script.'); + } + + /* throw error if lunr stemmer support is not yet included */ + if ('undefined' === typeof lunr.stemmerSupport) { + throw new Error('Lunr stemmer support is not present. Please include / require Lunr stemmer support before this script.'); + } + + console.warn("[Lunr Languages] Please use the \"nl\" instead of the \"du\". The \"nl\" code is the standard code for Dutch language, and \"du\" will be removed in the next major versions."); + + /* register specific locale function */ + lunr.du = function() { + this.pipeline.reset(); + this.pipeline.add( + lunr.du.trimmer, + lunr.du.stopWordFilter, + lunr.du.stemmer + ); + + // for lunr version 2 + // this is necessary so that every searched word is also stemmed before + // in lunr <= 1 this is not needed, as it is done using the normal pipeline + if (this.searchPipeline) { + this.searchPipeline.reset(); + this.searchPipeline.add(lunr.du.stemmer) + } + }; + + /* lunr trimmer function */ + lunr.du.wordCharacters = "A-Za-z\xAA\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02B8\u02E0-\u02E4\u1D00-\u1D25\u1D2C-\u1D5C\u1D62-\u1D65\u1D6B-\u1D77\u1D79-\u1DBE\u1E00-\u1EFF\u2071\u207F\u2090-\u209C\u212A\u212B\u2132\u214E\u2160-\u2188\u2C60-\u2C7F\uA722-\uA787\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA7FF\uAB30-\uAB5A\uAB5C-\uAB64\uFB00-\uFB06\uFF21-\uFF3A\uFF41-\uFF5A"; + lunr.du.trimmer = lunr.trimmerSupport.generateTrimmer(lunr.du.wordCharacters); + + lunr.Pipeline.registerFunction(lunr.du.trimmer, 'trimmer-du'); + + /* lunr stemmer function */ + lunr.du.stemmer = (function() { + /* create the wrapped stemmer object */ + var Among = lunr.stemmerSupport.Among, + SnowballProgram = lunr.stemmerSupport.SnowballProgram, + st = new function DutchStemmer() { + var a_0 = [new Among("", -1, 6), new Among("\u00E1", 0, 1), + new Among("\u00E4", 0, 1), new Among("\u00E9", 0, 2), + new Among("\u00EB", 0, 2), new Among("\u00ED", 0, 3), + new Among("\u00EF", 0, 3), new Among("\u00F3", 0, 4), + new Among("\u00F6", 0, 4), new Among("\u00FA", 0, 5), + new Among("\u00FC", 0, 5) + ], + a_1 = [new Among("", -1, 3), + new Among("I", 0, 2), new Among("Y", 0, 1) + ], + a_2 = [ + new Among("dd", -1, -1), new Among("kk", -1, -1), + new Among("tt", -1, -1) + ], + a_3 = [new Among("ene", -1, 2), + new Among("se", -1, 3), new Among("en", -1, 2), + new Among("heden", 2, 1), new Among("s", -1, 3) + ], + a_4 = [ + new Among("end", -1, 1), new Among("ig", -1, 2), + new Among("ing", -1, 1), new Among("lijk", -1, 3), + new Among("baar", -1, 4), new Among("bar", -1, 5) + ], + a_5 = [ + new Among("aa", -1, -1), new Among("ee", -1, -1), + new Among("oo", -1, -1), new Among("uu", -1, -1) + ], + g_v = [17, 65, + 16, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128 + ], + g_v_I = [1, 0, 0, + 17, 65, 16, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128 + ], + g_v_j = [ + 17, 67, 16, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128 + ], + I_p2, I_p1, B_e_found, sbp = new SnowballProgram(); + this.setCurrent = function(word) { + sbp.setCurrent(word); + }; + this.getCurrent = function() { + return sbp.getCurrent(); + }; + + function r_prelude() { + var among_var, v_1 = sbp.cursor, + v_2, v_3; + while (true) { + sbp.bra = sbp.cursor; + among_var = sbp.find_among(a_0, 11); + if (among_var) { + sbp.ket = sbp.cursor; + switch (among_var) { + case 1: + sbp.slice_from("a"); + continue; + case 2: + sbp.slice_from("e"); + continue; + case 3: + sbp.slice_from("i"); + continue; + case 4: + sbp.slice_from("o"); + continue; + case 5: + sbp.slice_from("u"); + continue; + case 6: + if (sbp.cursor >= sbp.limit) + break; + sbp.cursor++; + continue; + } + } + break; + } + sbp.cursor = v_1; + sbp.bra = v_1; + if (sbp.eq_s(1, "y")) { + sbp.ket = sbp.cursor; + sbp.slice_from("Y"); + } else + sbp.cursor = v_1; + while (true) { + v_2 = sbp.cursor; + if (sbp.in_grouping(g_v, 97, 232)) { + v_3 = sbp.cursor; + sbp.bra = v_3; + if (sbp.eq_s(1, "i")) { + sbp.ket = sbp.cursor; + if (sbp.in_grouping(g_v, 97, 232)) { + sbp.slice_from("I"); + sbp.cursor = v_2; + } + } else { + sbp.cursor = v_3; + if (sbp.eq_s(1, "y")) { + sbp.ket = sbp.cursor; + sbp.slice_from("Y"); + sbp.cursor = v_2; + } else if (habr1(v_2)) + break; + } + } else if (habr1(v_2)) + break; + } + } + + function habr1(v_1) { + sbp.cursor = v_1; + if (v_1 >= sbp.limit) + return true; + sbp.cursor++; + return false; + } + + function r_mark_regions() { + I_p1 = sbp.limit; + I_p2 = I_p1; + if (!habr2()) { + I_p1 = sbp.cursor; + if (I_p1 < 3) + I_p1 = 3; + if (!habr2()) + I_p2 = sbp.cursor; + } + } + + function habr2() { + while (!sbp.in_grouping(g_v, 97, 232)) { + if (sbp.cursor >= sbp.limit) + return true; + sbp.cursor++; + } + while (!sbp.out_grouping(g_v, 97, 232)) { + if (sbp.cursor >= sbp.limit) + return true; + sbp.cursor++; + } + return false; + } + + function r_postlude() { + var among_var; + while (true) { + sbp.bra = sbp.cursor; + among_var = sbp.find_among(a_1, 3); + if (among_var) { + sbp.ket = sbp.cursor; + switch (among_var) { + case 1: + sbp.slice_from("y"); + break; + case 2: + sbp.slice_from("i"); + break; + case 3: + if (sbp.cursor >= sbp.limit) + return; + sbp.cursor++; + break; + } + } + } + } + + function r_R1() { + return I_p1 <= sbp.cursor; + } + + function r_R2() { + return I_p2 <= sbp.cursor; + } + + function r_undouble() { + var v_1 = sbp.limit - sbp.cursor; + if (sbp.find_among_b(a_2, 3)) { + sbp.cursor = sbp.limit - v_1; + sbp.ket = sbp.cursor; + if (sbp.cursor > sbp.limit_backward) { + sbp.cursor--; + sbp.bra = sbp.cursor; + sbp.slice_del(); + } + } + } + + function r_e_ending() { + var v_1; + B_e_found = false; + sbp.ket = sbp.cursor; + if (sbp.eq_s_b(1, "e")) { + sbp.bra = sbp.cursor; + if (r_R1()) { + v_1 = sbp.limit - sbp.cursor; + if (sbp.out_grouping_b(g_v, 97, 232)) { + sbp.cursor = sbp.limit - v_1; + sbp.slice_del(); + B_e_found = true; + r_undouble(); + } + } + } + } + + function r_en_ending() { + var v_1; + if (r_R1()) { + v_1 = sbp.limit - sbp.cursor; + if (sbp.out_grouping_b(g_v, 97, 232)) { + sbp.cursor = sbp.limit - v_1; + if (!sbp.eq_s_b(3, "gem")) { + sbp.cursor = sbp.limit - v_1; + sbp.slice_del(); + r_undouble(); + } + } + } + } + + function r_standard_suffix() { + var among_var, v_1 = sbp.limit - sbp.cursor, + v_2, v_3, v_4, v_5, v_6; + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_3, 5); + if (among_var) { + sbp.bra = sbp.cursor; + switch (among_var) { + case 1: + if (r_R1()) + sbp.slice_from("heid"); + break; + case 2: + r_en_ending(); + break; + case 3: + if (r_R1() && sbp.out_grouping_b(g_v_j, 97, 232)) + sbp.slice_del(); + break; + } + } + sbp.cursor = sbp.limit - v_1; + r_e_ending(); + sbp.cursor = sbp.limit - v_1; + sbp.ket = sbp.cursor; + if (sbp.eq_s_b(4, "heid")) { + sbp.bra = sbp.cursor; + if (r_R2()) { + v_2 = sbp.limit - sbp.cursor; + if (!sbp.eq_s_b(1, "c")) { + sbp.cursor = sbp.limit - v_2; + sbp.slice_del(); + sbp.ket = sbp.cursor; + if (sbp.eq_s_b(2, "en")) { + sbp.bra = sbp.cursor; + r_en_ending(); + } + } + } + } + sbp.cursor = sbp.limit - v_1; + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_4, 6); + if (among_var) { + sbp.bra = sbp.cursor; + switch (among_var) { + case 1: + if (r_R2()) { + sbp.slice_del(); + v_3 = sbp.limit - sbp.cursor; + sbp.ket = sbp.cursor; + if (sbp.eq_s_b(2, "ig")) { + sbp.bra = sbp.cursor; + if (r_R2()) { + v_4 = sbp.limit - sbp.cursor; + if (!sbp.eq_s_b(1, "e")) { + sbp.cursor = sbp.limit - v_4; + sbp.slice_del(); + break; + } + } + } + sbp.cursor = sbp.limit - v_3; + r_undouble(); + } + break; + case 2: + if (r_R2()) { + v_5 = sbp.limit - sbp.cursor; + if (!sbp.eq_s_b(1, "e")) { + sbp.cursor = sbp.limit - v_5; + sbp.slice_del(); + } + } + break; + case 3: + if (r_R2()) { + sbp.slice_del(); + r_e_ending(); + } + break; + case 4: + if (r_R2()) + sbp.slice_del(); + break; + case 5: + if (r_R2() && B_e_found) + sbp.slice_del(); + break; + } + } + sbp.cursor = sbp.limit - v_1; + if (sbp.out_grouping_b(g_v_I, 73, 232)) { + v_6 = sbp.limit - sbp.cursor; + if (sbp.find_among_b(a_5, 4) && sbp.out_grouping_b(g_v, 97, 232)) { + sbp.cursor = sbp.limit - v_6; + sbp.ket = sbp.cursor; + if (sbp.cursor > sbp.limit_backward) { + sbp.cursor--; + sbp.bra = sbp.cursor; + sbp.slice_del(); + } + } + } + } + this.stem = function() { + var v_1 = sbp.cursor; + r_prelude(); + sbp.cursor = v_1; + r_mark_regions(); + sbp.limit_backward = v_1; + sbp.cursor = sbp.limit; + r_standard_suffix(); + sbp.cursor = sbp.limit_backward; + r_postlude(); + return true; + } + }; + + /* and return a function that stems a word for the current locale */ + return function(token) { + // for lunr version 2 + if (typeof token.update === "function") { + return token.update(function(word) { + st.setCurrent(word); + st.stem(); + return st.getCurrent(); + }) + } else { // for lunr version <= 1 + st.setCurrent(token); + st.stem(); + return st.getCurrent(); + } + } + })(); + + lunr.Pipeline.registerFunction(lunr.du.stemmer, 'stemmer-du'); + + lunr.du.stopWordFilter = lunr.generateStopWordFilter(' aan al alles als altijd andere ben bij daar dan dat de der deze die dit doch doen door dus een eens en er ge geen geweest haar had heb hebben heeft hem het hier hij hoe hun iemand iets ik in is ja je kan kon kunnen maar me meer men met mij mijn moet na naar niet niets nog nu of om omdat onder ons ook op over reeds te tegen toch toen tot u uit uw van veel voor want waren was wat werd wezen wie wil worden wordt zal ze zelf zich zij zijn zo zonder zou'.split(' ')); + + lunr.Pipeline.registerFunction(lunr.du.stopWordFilter, 'stopWordFilter-du'); + }; +})) \ No newline at end of file diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.es.js b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.es.js new file mode 100644 index 0000000000000000000000000000000000000000..46cbc36070f333cc1342ac2317d30b4235d52e4a --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.es.js @@ -0,0 +1,599 @@ +/*! + * Lunr languages, `Spanish` language + * https://github.com/MihaiValentin/lunr-languages + * + * Copyright 2014, Mihai Valentin + * http://www.mozilla.org/MPL/ + */ +/*! + * based on + * Snowball JavaScript Library v0.3 + * http://code.google.com/p/urim/ + * http://snowball.tartarus.org/ + * + * Copyright 2010, Oleg Mazko + * http://www.mozilla.org/MPL/ + */ + +/** + * export the module via AMD, CommonJS or as a browser global + * Export code from https://github.com/umdjs/umd/blob/master/returnExports.js + */ +; +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(factory) + } else if (typeof exports === 'object') { + /** + * Node. Does not work with strict CommonJS, but + * only CommonJS-like environments that support module.exports, + * like Node. + */ + module.exports = factory() + } else { + // Browser globals (root is window) + factory()(root.lunr); + } +}(this, function() { + /** + * Just return a value to define the module export. + * This example returns an object, but the module + * can return a function as the exported value. + */ + return function(lunr) { + /* throw error if lunr is not yet included */ + if ('undefined' === typeof lunr) { + throw new Error('Lunr is not present. Please include / require Lunr before this script.'); + } + + /* throw error if lunr stemmer support is not yet included */ + if ('undefined' === typeof lunr.stemmerSupport) { + throw new Error('Lunr stemmer support is not present. Please include / require Lunr stemmer support before this script.'); + } + + /* register specific locale function */ + lunr.es = function() { + this.pipeline.reset(); + this.pipeline.add( + lunr.es.trimmer, + lunr.es.stopWordFilter, + lunr.es.stemmer + ); + + // for lunr version 2 + // this is necessary so that every searched word is also stemmed before + // in lunr <= 1 this is not needed, as it is done using the normal pipeline + if (this.searchPipeline) { + this.searchPipeline.reset(); + this.searchPipeline.add(lunr.es.stemmer) + } + }; + + /* lunr trimmer function */ + lunr.es.wordCharacters = "A-Za-z\xAA\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02B8\u02E0-\u02E4\u1D00-\u1D25\u1D2C-\u1D5C\u1D62-\u1D65\u1D6B-\u1D77\u1D79-\u1DBE\u1E00-\u1EFF\u2071\u207F\u2090-\u209C\u212A\u212B\u2132\u214E\u2160-\u2188\u2C60-\u2C7F\uA722-\uA787\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA7FF\uAB30-\uAB5A\uAB5C-\uAB64\uFB00-\uFB06\uFF21-\uFF3A\uFF41-\uFF5A"; + lunr.es.trimmer = lunr.trimmerSupport.generateTrimmer(lunr.es.wordCharacters); + + lunr.Pipeline.registerFunction(lunr.es.trimmer, 'trimmer-es'); + + /* lunr stemmer function */ + lunr.es.stemmer = (function() { + /* create the wrapped stemmer object */ + var Among = lunr.stemmerSupport.Among, + SnowballProgram = lunr.stemmerSupport.SnowballProgram, + st = new function SpanishStemmer() { + var a_0 = [new Among("", -1, 6), new Among("\u00E1", 0, 1), + new Among("\u00E9", 0, 2), new Among("\u00ED", 0, 3), + new Among("\u00F3", 0, 4), new Among("\u00FA", 0, 5) + ], + a_1 = [ + new Among("la", -1, -1), new Among("sela", 0, -1), + new Among("le", -1, -1), new Among("me", -1, -1), + new Among("se", -1, -1), new Among("lo", -1, -1), + new Among("selo", 5, -1), new Among("las", -1, -1), + new Among("selas", 7, -1), new Among("les", -1, -1), + new Among("los", -1, -1), new Among("selos", 10, -1), + new Among("nos", -1, -1) + ], + a_2 = [new Among("ando", -1, 6), + new Among("iendo", -1, 6), new Among("yendo", -1, 7), + new Among("\u00E1ndo", -1, 2), new Among("i\u00E9ndo", -1, 1), + new Among("ar", -1, 6), new Among("er", -1, 6), + new Among("ir", -1, 6), new Among("\u00E1r", -1, 3), + new Among("\u00E9r", -1, 4), new Among("\u00EDr", -1, 5) + ], + a_3 = [ + new Among("ic", -1, -1), new Among("ad", -1, -1), + new Among("os", -1, -1), new Among("iv", -1, 1) + ], + a_4 = [ + new Among("able", -1, 1), new Among("ible", -1, 1), + new Among("ante", -1, 1) + ], + a_5 = [new Among("ic", -1, 1), + new Among("abil", -1, 1), new Among("iv", -1, 1) + ], + a_6 = [ + new Among("ica", -1, 1), new Among("ancia", -1, 2), + new Among("encia", -1, 5), new Among("adora", -1, 2), + new Among("osa", -1, 1), new Among("ista", -1, 1), + new Among("iva", -1, 9), new Among("anza", -1, 1), + new Among("log\u00EDa", -1, 3), new Among("idad", -1, 8), + new Among("able", -1, 1), new Among("ible", -1, 1), + new Among("ante", -1, 2), new Among("mente", -1, 7), + new Among("amente", 13, 6), new Among("aci\u00F3n", -1, 2), + new Among("uci\u00F3n", -1, 4), new Among("ico", -1, 1), + new Among("ismo", -1, 1), new Among("oso", -1, 1), + new Among("amiento", -1, 1), new Among("imiento", -1, 1), + new Among("ivo", -1, 9), new Among("ador", -1, 2), + new Among("icas", -1, 1), new Among("ancias", -1, 2), + new Among("encias", -1, 5), new Among("adoras", -1, 2), + new Among("osas", -1, 1), new Among("istas", -1, 1), + new Among("ivas", -1, 9), new Among("anzas", -1, 1), + new Among("log\u00EDas", -1, 3), new Among("idades", -1, 8), + new Among("ables", -1, 1), new Among("ibles", -1, 1), + new Among("aciones", -1, 2), new Among("uciones", -1, 4), + new Among("adores", -1, 2), new Among("antes", -1, 2), + new Among("icos", -1, 1), new Among("ismos", -1, 1), + new Among("osos", -1, 1), new Among("amientos", -1, 1), + new Among("imientos", -1, 1), new Among("ivos", -1, 9) + ], + a_7 = [ + new Among("ya", -1, 1), new Among("ye", -1, 1), + new Among("yan", -1, 1), new Among("yen", -1, 1), + new Among("yeron", -1, 1), new Among("yendo", -1, 1), + new Among("yo", -1, 1), new Among("yas", -1, 1), + new Among("yes", -1, 1), new Among("yais", -1, 1), + new Among("yamos", -1, 1), new Among("y\u00F3", -1, 1) + ], + a_8 = [ + new Among("aba", -1, 2), new Among("ada", -1, 2), + new Among("ida", -1, 2), new Among("ara", -1, 2), + new Among("iera", -1, 2), new Among("\u00EDa", -1, 2), + new Among("ar\u00EDa", 5, 2), new Among("er\u00EDa", 5, 2), + new Among("ir\u00EDa", 5, 2), new Among("ad", -1, 2), + new Among("ed", -1, 2), new Among("id", -1, 2), + new Among("ase", -1, 2), new Among("iese", -1, 2), + new Among("aste", -1, 2), new Among("iste", -1, 2), + new Among("an", -1, 2), new Among("aban", 16, 2), + new Among("aran", 16, 2), new Among("ieran", 16, 2), + new Among("\u00EDan", 16, 2), new Among("ar\u00EDan", 20, 2), + new Among("er\u00EDan", 20, 2), new Among("ir\u00EDan", 20, 2), + new Among("en", -1, 1), new Among("asen", 24, 2), + new Among("iesen", 24, 2), new Among("aron", -1, 2), + new Among("ieron", -1, 2), new Among("ar\u00E1n", -1, 2), + new Among("er\u00E1n", -1, 2), new Among("ir\u00E1n", -1, 2), + new Among("ado", -1, 2), new Among("ido", -1, 2), + new Among("ando", -1, 2), new Among("iendo", -1, 2), + new Among("ar", -1, 2), new Among("er", -1, 2), + new Among("ir", -1, 2), new Among("as", -1, 2), + new Among("abas", 39, 2), new Among("adas", 39, 2), + new Among("idas", 39, 2), new Among("aras", 39, 2), + new Among("ieras", 39, 2), new Among("\u00EDas", 39, 2), + new Among("ar\u00EDas", 45, 2), new Among("er\u00EDas", 45, 2), + new Among("ir\u00EDas", 45, 2), new Among("es", -1, 1), + new Among("ases", 49, 2), new Among("ieses", 49, 2), + new Among("abais", -1, 2), new Among("arais", -1, 2), + new Among("ierais", -1, 2), new Among("\u00EDais", -1, 2), + new Among("ar\u00EDais", 55, 2), new Among("er\u00EDais", 55, 2), + new Among("ir\u00EDais", 55, 2), new Among("aseis", -1, 2), + new Among("ieseis", -1, 2), new Among("asteis", -1, 2), + new Among("isteis", -1, 2), new Among("\u00E1is", -1, 2), + new Among("\u00E9is", -1, 1), new Among("ar\u00E9is", 64, 2), + new Among("er\u00E9is", 64, 2), new Among("ir\u00E9is", 64, 2), + new Among("ados", -1, 2), new Among("idos", -1, 2), + new Among("amos", -1, 2), new Among("\u00E1bamos", 70, 2), + new Among("\u00E1ramos", 70, 2), new Among("i\u00E9ramos", 70, 2), + new Among("\u00EDamos", 70, 2), new Among("ar\u00EDamos", 74, 2), + new Among("er\u00EDamos", 74, 2), new Among("ir\u00EDamos", 74, 2), + new Among("emos", -1, 1), new Among("aremos", 78, 2), + new Among("eremos", 78, 2), new Among("iremos", 78, 2), + new Among("\u00E1semos", 78, 2), new Among("i\u00E9semos", 78, 2), + new Among("imos", -1, 2), new Among("ar\u00E1s", -1, 2), + new Among("er\u00E1s", -1, 2), new Among("ir\u00E1s", -1, 2), + new Among("\u00EDs", -1, 2), new Among("ar\u00E1", -1, 2), + new Among("er\u00E1", -1, 2), new Among("ir\u00E1", -1, 2), + new Among("ar\u00E9", -1, 2), new Among("er\u00E9", -1, 2), + new Among("ir\u00E9", -1, 2), new Among("i\u00F3", -1, 2) + ], + a_9 = [ + new Among("a", -1, 1), new Among("e", -1, 2), + new Among("o", -1, 1), new Among("os", -1, 1), + new Among("\u00E1", -1, 1), new Among("\u00E9", -1, 2), + new Among("\u00ED", -1, 1), new Among("\u00F3", -1, 1) + ], + g_v = [17, + 65, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 17, 4, 10 + ], + I_p2, I_p1, I_pV, sbp = new SnowballProgram(); + this.setCurrent = function(word) { + sbp.setCurrent(word); + }; + this.getCurrent = function() { + return sbp.getCurrent(); + }; + + function habr1() { + if (sbp.out_grouping(g_v, 97, 252)) { + while (!sbp.in_grouping(g_v, 97, 252)) { + if (sbp.cursor >= sbp.limit) + return true; + sbp.cursor++; + } + return false; + } + return true; + } + + function habr2() { + if (sbp.in_grouping(g_v, 97, 252)) { + var v_1 = sbp.cursor; + if (habr1()) { + sbp.cursor = v_1; + if (!sbp.in_grouping(g_v, 97, 252)) + return true; + while (!sbp.out_grouping(g_v, 97, 252)) { + if (sbp.cursor >= sbp.limit) + return true; + sbp.cursor++; + } + } + return false; + } + return true; + } + + function habr3() { + var v_1 = sbp.cursor, + v_2; + if (habr2()) { + sbp.cursor = v_1; + if (!sbp.out_grouping(g_v, 97, 252)) + return; + v_2 = sbp.cursor; + if (habr1()) { + sbp.cursor = v_2; + if (!sbp.in_grouping(g_v, 97, 252) || sbp.cursor >= sbp.limit) + return; + sbp.cursor++; + } + } + I_pV = sbp.cursor; + } + + function habr4() { + while (!sbp.in_grouping(g_v, 97, 252)) { + if (sbp.cursor >= sbp.limit) + return false; + sbp.cursor++; + } + while (!sbp.out_grouping(g_v, 97, 252)) { + if (sbp.cursor >= sbp.limit) + return false; + sbp.cursor++; + } + return true; + } + + function r_mark_regions() { + var v_1 = sbp.cursor; + I_pV = sbp.limit; + I_p1 = I_pV; + I_p2 = I_pV; + habr3(); + sbp.cursor = v_1; + if (habr4()) { + I_p1 = sbp.cursor; + if (habr4()) + I_p2 = sbp.cursor; + } + } + + function r_postlude() { + var among_var; + while (true) { + sbp.bra = sbp.cursor; + among_var = sbp.find_among(a_0, 6); + if (among_var) { + sbp.ket = sbp.cursor; + switch (among_var) { + case 1: + sbp.slice_from("a"); + continue; + case 2: + sbp.slice_from("e"); + continue; + case 3: + sbp.slice_from("i"); + continue; + case 4: + sbp.slice_from("o"); + continue; + case 5: + sbp.slice_from("u"); + continue; + case 6: + if (sbp.cursor >= sbp.limit) + break; + sbp.cursor++; + continue; + } + } + break; + } + } + + function r_RV() { + return I_pV <= sbp.cursor; + } + + function r_R1() { + return I_p1 <= sbp.cursor; + } + + function r_R2() { + return I_p2 <= sbp.cursor; + } + + function r_attached_pronoun() { + var among_var; + sbp.ket = sbp.cursor; + if (sbp.find_among_b(a_1, 13)) { + sbp.bra = sbp.cursor; + among_var = sbp.find_among_b(a_2, 11); + if (among_var && r_RV()) + switch (among_var) { + case 1: + sbp.bra = sbp.cursor; + sbp.slice_from("iendo"); + break; + case 2: + sbp.bra = sbp.cursor; + sbp.slice_from("ando"); + break; + case 3: + sbp.bra = sbp.cursor; + sbp.slice_from("ar"); + break; + case 4: + sbp.bra = sbp.cursor; + sbp.slice_from("er"); + break; + case 5: + sbp.bra = sbp.cursor; + sbp.slice_from("ir"); + break; + case 6: + sbp.slice_del(); + break; + case 7: + if (sbp.eq_s_b(1, "u")) + sbp.slice_del(); + break; + } + } + } + + function habr5(a, n) { + if (!r_R2()) + return true; + sbp.slice_del(); + sbp.ket = sbp.cursor; + var among_var = sbp.find_among_b(a, n); + if (among_var) { + sbp.bra = sbp.cursor; + if (among_var == 1 && r_R2()) + sbp.slice_del(); + } + return false; + } + + function habr6(c1) { + if (!r_R2()) + return true; + sbp.slice_del(); + sbp.ket = sbp.cursor; + if (sbp.eq_s_b(2, c1)) { + sbp.bra = sbp.cursor; + if (r_R2()) + sbp.slice_del(); + } + return false; + } + + function r_standard_suffix() { + var among_var; + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_6, 46); + if (among_var) { + sbp.bra = sbp.cursor; + switch (among_var) { + case 1: + if (!r_R2()) + return false; + sbp.slice_del(); + break; + case 2: + if (habr6("ic")) + return false; + break; + case 3: + if (!r_R2()) + return false; + sbp.slice_from("log"); + break; + case 4: + if (!r_R2()) + return false; + sbp.slice_from("u"); + break; + case 5: + if (!r_R2()) + return false; + sbp.slice_from("ente"); + break; + case 6: + if (!r_R1()) + return false; + sbp.slice_del(); + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_3, 4); + if (among_var) { + sbp.bra = sbp.cursor; + if (r_R2()) { + sbp.slice_del(); + if (among_var == 1) { + sbp.ket = sbp.cursor; + if (sbp.eq_s_b(2, "at")) { + sbp.bra = sbp.cursor; + if (r_R2()) + sbp.slice_del(); + } + } + } + } + break; + case 7: + if (habr5(a_4, 3)) + return false; + break; + case 8: + if (habr5(a_5, 3)) + return false; + break; + case 9: + if (habr6("at")) + return false; + break; + } + return true; + } + return false; + } + + function r_y_verb_suffix() { + var among_var, v_1; + if (sbp.cursor >= I_pV) { + v_1 = sbp.limit_backward; + sbp.limit_backward = I_pV; + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_7, 12); + sbp.limit_backward = v_1; + if (among_var) { + sbp.bra = sbp.cursor; + if (among_var == 1) { + if (!sbp.eq_s_b(1, "u")) + return false; + sbp.slice_del(); + } + return true; + } + } + return false; + } + + function r_verb_suffix() { + var among_var, v_1, v_2, v_3; + if (sbp.cursor >= I_pV) { + v_1 = sbp.limit_backward; + sbp.limit_backward = I_pV; + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_8, 96); + sbp.limit_backward = v_1; + if (among_var) { + sbp.bra = sbp.cursor; + switch (among_var) { + case 1: + v_2 = sbp.limit - sbp.cursor; + if (sbp.eq_s_b(1, "u")) { + v_3 = sbp.limit - sbp.cursor; + if (sbp.eq_s_b(1, "g")) + sbp.cursor = sbp.limit - v_3; + else + sbp.cursor = sbp.limit - v_2; + } else + sbp.cursor = sbp.limit - v_2; + sbp.bra = sbp.cursor; + case 2: + sbp.slice_del(); + break; + } + } + } + } + + function r_residual_suffix() { + var among_var, v_1; + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_9, 8); + if (among_var) { + sbp.bra = sbp.cursor; + switch (among_var) { + case 1: + if (r_RV()) + sbp.slice_del(); + break; + case 2: + if (r_RV()) { + sbp.slice_del(); + sbp.ket = sbp.cursor; + if (sbp.eq_s_b(1, "u")) { + sbp.bra = sbp.cursor; + v_1 = sbp.limit - sbp.cursor; + if (sbp.eq_s_b(1, "g")) { + sbp.cursor = sbp.limit - v_1; + if (r_RV()) + sbp.slice_del(); + } + } + } + break; + } + } + } + this.stem = function() { + var v_1 = sbp.cursor; + r_mark_regions(); + sbp.limit_backward = v_1; + sbp.cursor = sbp.limit; + r_attached_pronoun(); + sbp.cursor = sbp.limit; + if (!r_standard_suffix()) { + sbp.cursor = sbp.limit; + if (!r_y_verb_suffix()) { + sbp.cursor = sbp.limit; + r_verb_suffix(); + } + } + sbp.cursor = sbp.limit; + r_residual_suffix(); + sbp.cursor = sbp.limit_backward; + r_postlude(); + return true; + } + }; + + /* and return a function that stems a word for the current locale */ + return function(token) { + // for lunr version 2 + if (typeof token.update === "function") { + return token.update(function(word) { + st.setCurrent(word); + st.stem(); + return st.getCurrent(); + }) + } else { // for lunr version <= 1 + st.setCurrent(token); + st.stem(); + return st.getCurrent(); + } + } + })(); + + lunr.Pipeline.registerFunction(lunr.es.stemmer, 'stemmer-es'); + + lunr.es.stopWordFilter = lunr.generateStopWordFilter('a al algo algunas algunos ante antes como con contra cual cuando de del desde donde durante e el ella ellas ellos en entre era erais eran eras eres es esa esas ese eso esos esta estaba estabais estaban estabas estad estada estadas estado estados estamos estando estar estaremos estará estarán estarás estaré estaréis estaría estaríais estaríamos estarían estarías estas este estemos esto estos estoy estuve estuviera estuvierais estuvieran estuvieras estuvieron estuviese estuvieseis estuviesen estuvieses estuvimos estuviste estuvisteis estuviéramos estuviésemos estuvo está estábamos estáis están estás esté estéis estén estés fue fuera fuerais fueran fueras fueron fuese fueseis fuesen fueses fui fuimos fuiste fuisteis fuéramos fuésemos ha habida habidas habido habidos habiendo habremos habrá habrán habrás habré habréis habría habríais habríamos habrían habrías habéis había habíais habíamos habían habías han has hasta hay haya hayamos hayan hayas hayáis he hemos hube hubiera hubierais hubieran hubieras hubieron hubiese hubieseis hubiesen hubieses hubimos hubiste hubisteis hubiéramos hubiésemos hubo la las le les lo los me mi mis mucho muchos muy más mí mía mías mío míos nada ni no nos nosotras nosotros nuestra nuestras nuestro nuestros o os otra otras otro otros para pero poco por porque que quien quienes qué se sea seamos sean seas seremos será serán serás seré seréis sería seríais seríamos serían serías seáis sido siendo sin sobre sois somos son soy su sus suya suyas suyo suyos sí también tanto te tendremos tendrá tendrán tendrás tendré tendréis tendría tendríais tendríamos tendrían tendrías tened tenemos tenga tengamos tengan tengas tengo tengáis tenida tenidas tenido tenidos teniendo tenéis tenía teníais teníamos tenían tenías ti tiene tienen tienes todo todos tu tus tuve tuviera tuvierais tuvieran tuvieras tuvieron tuviese tuvieseis tuviesen tuvieses tuvimos tuviste tuvisteis tuviéramos tuviésemos tuvo tuya tuyas tuyo tuyos tú un una uno unos vosotras vosotros vuestra vuestras vuestro vuestros y ya yo él éramos'.split(' ')); + + lunr.Pipeline.registerFunction(lunr.es.stopWordFilter, 'stopWordFilter-es'); + }; +})) \ No newline at end of file diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.fi.js b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.fi.js new file mode 100644 index 0000000000000000000000000000000000000000..7ce9515404207fc92fcbeba94a26fafa052c05c9 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.fi.js @@ -0,0 +1,541 @@ +/*! + * Lunr languages, `Finnish` language + * https://github.com/MihaiValentin/lunr-languages + * + * Copyright 2014, Mihai Valentin + * http://www.mozilla.org/MPL/ + */ +/*! + * based on + * Snowball JavaScript Library v0.3 + * http://code.google.com/p/urim/ + * http://snowball.tartarus.org/ + * + * Copyright 2010, Oleg Mazko + * http://www.mozilla.org/MPL/ + */ + +/** + * export the module via AMD, CommonJS or as a browser global + * Export code from https://github.com/umdjs/umd/blob/master/returnExports.js + */ +; +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(factory) + } else if (typeof exports === 'object') { + /** + * Node. Does not work with strict CommonJS, but + * only CommonJS-like environments that support module.exports, + * like Node. + */ + module.exports = factory() + } else { + // Browser globals (root is window) + factory()(root.lunr); + } +}(this, function() { + /** + * Just return a value to define the module export. + * This example returns an object, but the module + * can return a function as the exported value. + */ + return function(lunr) { + /* throw error if lunr is not yet included */ + if ('undefined' === typeof lunr) { + throw new Error('Lunr is not present. Please include / require Lunr before this script.'); + } + + /* throw error if lunr stemmer support is not yet included */ + if ('undefined' === typeof lunr.stemmerSupport) { + throw new Error('Lunr stemmer support is not present. Please include / require Lunr stemmer support before this script.'); + } + + /* register specific locale function */ + lunr.fi = function() { + this.pipeline.reset(); + this.pipeline.add( + lunr.fi.trimmer, + lunr.fi.stopWordFilter, + lunr.fi.stemmer + ); + + // for lunr version 2 + // this is necessary so that every searched word is also stemmed before + // in lunr <= 1 this is not needed, as it is done using the normal pipeline + if (this.searchPipeline) { + this.searchPipeline.reset(); + this.searchPipeline.add(lunr.fi.stemmer) + } + }; + + /* lunr trimmer function */ + lunr.fi.wordCharacters = "A-Za-z\xAA\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02B8\u02E0-\u02E4\u1D00-\u1D25\u1D2C-\u1D5C\u1D62-\u1D65\u1D6B-\u1D77\u1D79-\u1DBE\u1E00-\u1EFF\u2071\u207F\u2090-\u209C\u212A\u212B\u2132\u214E\u2160-\u2188\u2C60-\u2C7F\uA722-\uA787\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA7FF\uAB30-\uAB5A\uAB5C-\uAB64\uFB00-\uFB06\uFF21-\uFF3A\uFF41-\uFF5A"; + lunr.fi.trimmer = lunr.trimmerSupport.generateTrimmer(lunr.fi.wordCharacters); + + lunr.Pipeline.registerFunction(lunr.fi.trimmer, 'trimmer-fi'); + + /* lunr stemmer function */ + lunr.fi.stemmer = (function() { + /* create the wrapped stemmer object */ + var Among = lunr.stemmerSupport.Among, + SnowballProgram = lunr.stemmerSupport.SnowballProgram, + st = new function FinnishStemmer() { + var a_0 = [new Among("pa", -1, 1), new Among("sti", -1, 2), + new Among("kaan", -1, 1), new Among("han", -1, 1), + new Among("kin", -1, 1), new Among("h\u00E4n", -1, 1), + new Among("k\u00E4\u00E4n", -1, 1), new Among("ko", -1, 1), + new Among("p\u00E4", -1, 1), new Among("k\u00F6", -1, 1) + ], + a_1 = [ + new Among("lla", -1, -1), new Among("na", -1, -1), + new Among("ssa", -1, -1), new Among("ta", -1, -1), + new Among("lta", 3, -1), new Among("sta", 3, -1) + ], + a_2 = [ + new Among("ll\u00E4", -1, -1), new Among("n\u00E4", -1, -1), + new Among("ss\u00E4", -1, -1), new Among("t\u00E4", -1, -1), + new Among("lt\u00E4", 3, -1), new Among("st\u00E4", 3, -1) + ], + a_3 = [ + new Among("lle", -1, -1), new Among("ine", -1, -1) + ], + a_4 = [ + new Among("nsa", -1, 3), new Among("mme", -1, 3), + new Among("nne", -1, 3), new Among("ni", -1, 2), + new Among("si", -1, 1), new Among("an", -1, 4), + new Among("en", -1, 6), new Among("\u00E4n", -1, 5), + new Among("ns\u00E4", -1, 3) + ], + a_5 = [new Among("aa", -1, -1), + new Among("ee", -1, -1), new Among("ii", -1, -1), + new Among("oo", -1, -1), new Among("uu", -1, -1), + new Among("\u00E4\u00E4", -1, -1), + new Among("\u00F6\u00F6", -1, -1) + ], + a_6 = [new Among("a", -1, 8), + new Among("lla", 0, -1), new Among("na", 0, -1), + new Among("ssa", 0, -1), new Among("ta", 0, -1), + new Among("lta", 4, -1), new Among("sta", 4, -1), + new Among("tta", 4, 9), new Among("lle", -1, -1), + new Among("ine", -1, -1), new Among("ksi", -1, -1), + new Among("n", -1, 7), new Among("han", 11, 1), + new Among("den", 11, -1, r_VI), new Among("seen", 11, -1, r_LONG), + new Among("hen", 11, 2), new Among("tten", 11, -1, r_VI), + new Among("hin", 11, 3), new Among("siin", 11, -1, r_VI), + new Among("hon", 11, 4), new Among("h\u00E4n", 11, 5), + new Among("h\u00F6n", 11, 6), new Among("\u00E4", -1, 8), + new Among("ll\u00E4", 22, -1), new Among("n\u00E4", 22, -1), + new Among("ss\u00E4", 22, -1), new Among("t\u00E4", 22, -1), + new Among("lt\u00E4", 26, -1), new Among("st\u00E4", 26, -1), + new Among("tt\u00E4", 26, 9) + ], + a_7 = [new Among("eja", -1, -1), + new Among("mma", -1, 1), new Among("imma", 1, -1), + new Among("mpa", -1, 1), new Among("impa", 3, -1), + new Among("mmi", -1, 1), new Among("immi", 5, -1), + new Among("mpi", -1, 1), new Among("impi", 7, -1), + new Among("ej\u00E4", -1, -1), new Among("mm\u00E4", -1, 1), + new Among("imm\u00E4", 10, -1), new Among("mp\u00E4", -1, 1), + new Among("imp\u00E4", 12, -1) + ], + a_8 = [new Among("i", -1, -1), + new Among("j", -1, -1) + ], + a_9 = [new Among("mma", -1, 1), + new Among("imma", 0, -1) + ], + g_AEI = [17, 1, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 8 + ], + g_V1 = [17, 65, 16, 1, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 8, 0, 32 + ], + g_V2 = [17, 65, 16, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 8, 0, 32 + ], + g_particle_end = [17, 97, 24, 1, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 32 + ], + B_ending_removed, S_x, I_p2, I_p1, sbp = new SnowballProgram(); + this.setCurrent = function(word) { + sbp.setCurrent(word); + }; + this.getCurrent = function() { + return sbp.getCurrent(); + }; + + function r_mark_regions() { + I_p1 = sbp.limit; + I_p2 = I_p1; + if (!habr1()) { + I_p1 = sbp.cursor; + if (!habr1()) + I_p2 = sbp.cursor; + } + } + + function habr1() { + var v_1; + while (true) { + v_1 = sbp.cursor; + if (sbp.in_grouping(g_V1, 97, 246)) + break; + sbp.cursor = v_1; + if (v_1 >= sbp.limit) + return true; + sbp.cursor++; + } + sbp.cursor = v_1; + while (!sbp.out_grouping(g_V1, 97, 246)) { + if (sbp.cursor >= sbp.limit) + return true; + sbp.cursor++; + } + return false; + } + + function r_R2() { + return I_p2 <= sbp.cursor; + } + + function r_particle_etc() { + var among_var, v_1; + if (sbp.cursor >= I_p1) { + v_1 = sbp.limit_backward; + sbp.limit_backward = I_p1; + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_0, 10); + if (among_var) { + sbp.bra = sbp.cursor; + sbp.limit_backward = v_1; + switch (among_var) { + case 1: + if (!sbp.in_grouping_b(g_particle_end, 97, 246)) + return; + break; + case 2: + if (!r_R2()) + return; + break; + } + sbp.slice_del(); + } else + sbp.limit_backward = v_1; + } + } + + function r_possessive() { + var among_var, v_1, v_2; + if (sbp.cursor >= I_p1) { + v_1 = sbp.limit_backward; + sbp.limit_backward = I_p1; + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_4, 9); + if (among_var) { + sbp.bra = sbp.cursor; + sbp.limit_backward = v_1; + switch (among_var) { + case 1: + v_2 = sbp.limit - sbp.cursor; + if (!sbp.eq_s_b(1, "k")) { + sbp.cursor = sbp.limit - v_2; + sbp.slice_del(); + } + break; + case 2: + sbp.slice_del(); + sbp.ket = sbp.cursor; + if (sbp.eq_s_b(3, "kse")) { + sbp.bra = sbp.cursor; + sbp.slice_from("ksi"); + } + break; + case 3: + sbp.slice_del(); + break; + case 4: + if (sbp.find_among_b(a_1, 6)) + sbp.slice_del(); + break; + case 5: + if (sbp.find_among_b(a_2, 6)) + sbp.slice_del(); + break; + case 6: + if (sbp.find_among_b(a_3, 2)) + sbp.slice_del(); + break; + } + } else + sbp.limit_backward = v_1; + } + } + + function r_LONG() { + return sbp.find_among_b(a_5, 7); + } + + function r_VI() { + return sbp.eq_s_b(1, "i") && sbp.in_grouping_b(g_V2, 97, 246); + } + + function r_case_ending() { + var among_var, v_1, v_2; + if (sbp.cursor >= I_p1) { + v_1 = sbp.limit_backward; + sbp.limit_backward = I_p1; + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_6, 30); + if (among_var) { + sbp.bra = sbp.cursor; + sbp.limit_backward = v_1; + switch (among_var) { + case 1: + if (!sbp.eq_s_b(1, "a")) + return; + break; + case 2: + case 9: + if (!sbp.eq_s_b(1, "e")) + return; + break; + case 3: + if (!sbp.eq_s_b(1, "i")) + return; + break; + case 4: + if (!sbp.eq_s_b(1, "o")) + return; + break; + case 5: + if (!sbp.eq_s_b(1, "\u00E4")) + return; + break; + case 6: + if (!sbp.eq_s_b(1, "\u00F6")) + return; + break; + case 7: + v_2 = sbp.limit - sbp.cursor; + if (!r_LONG()) { + sbp.cursor = sbp.limit - v_2; + if (!sbp.eq_s_b(2, "ie")) { + sbp.cursor = sbp.limit - v_2; + break; + } + } + sbp.cursor = sbp.limit - v_2; + if (sbp.cursor <= sbp.limit_backward) { + sbp.cursor = sbp.limit - v_2; + break; + } + sbp.cursor--; + sbp.bra = sbp.cursor; + break; + case 8: + if (!sbp.in_grouping_b(g_V1, 97, 246) || + !sbp.out_grouping_b(g_V1, 97, 246)) + return; + break; + } + sbp.slice_del(); + B_ending_removed = true; + } else + sbp.limit_backward = v_1; + } + } + + function r_other_endings() { + var among_var, v_1, v_2; + if (sbp.cursor >= I_p2) { + v_1 = sbp.limit_backward; + sbp.limit_backward = I_p2; + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_7, 14); + if (among_var) { + sbp.bra = sbp.cursor; + sbp.limit_backward = v_1; + if (among_var == 1) { + v_2 = sbp.limit - sbp.cursor; + if (sbp.eq_s_b(2, "po")) + return; + sbp.cursor = sbp.limit - v_2; + } + sbp.slice_del(); + } else + sbp.limit_backward = v_1; + } + } + + function r_i_plural() { + var v_1; + if (sbp.cursor >= I_p1) { + v_1 = sbp.limit_backward; + sbp.limit_backward = I_p1; + sbp.ket = sbp.cursor; + if (sbp.find_among_b(a_8, 2)) { + sbp.bra = sbp.cursor; + sbp.limit_backward = v_1; + sbp.slice_del(); + } else + sbp.limit_backward = v_1; + } + } + + function r_t_plural() { + var among_var, v_1, v_2, v_3, v_4, v_5; + if (sbp.cursor >= I_p1) { + v_1 = sbp.limit_backward; + sbp.limit_backward = I_p1; + sbp.ket = sbp.cursor; + if (sbp.eq_s_b(1, "t")) { + sbp.bra = sbp.cursor; + v_2 = sbp.limit - sbp.cursor; + if (sbp.in_grouping_b(g_V1, 97, 246)) { + sbp.cursor = sbp.limit - v_2; + sbp.slice_del(); + sbp.limit_backward = v_1; + v_3 = sbp.limit - sbp.cursor; + if (sbp.cursor >= I_p2) { + sbp.cursor = I_p2; + v_4 = sbp.limit_backward; + sbp.limit_backward = sbp.cursor; + sbp.cursor = sbp.limit - v_3; + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_9, 2); + if (among_var) { + sbp.bra = sbp.cursor; + sbp.limit_backward = v_4; + if (among_var == 1) { + v_5 = sbp.limit - sbp.cursor; + if (sbp.eq_s_b(2, "po")) + return; + sbp.cursor = sbp.limit - v_5; + } + sbp.slice_del(); + return; + } + } + } + } + sbp.limit_backward = v_1; + } + } + + function r_tidy() { + var v_1, v_2, v_3, v_4; + if (sbp.cursor >= I_p1) { + v_1 = sbp.limit_backward; + sbp.limit_backward = I_p1; + v_2 = sbp.limit - sbp.cursor; + if (r_LONG()) { + sbp.cursor = sbp.limit - v_2; + sbp.ket = sbp.cursor; + if (sbp.cursor > sbp.limit_backward) { + sbp.cursor--; + sbp.bra = sbp.cursor; + sbp.slice_del(); + } + } + sbp.cursor = sbp.limit - v_2; + sbp.ket = sbp.cursor; + if (sbp.in_grouping_b(g_AEI, 97, 228)) { + sbp.bra = sbp.cursor; + if (sbp.out_grouping_b(g_V1, 97, 246)) + sbp.slice_del(); + } + sbp.cursor = sbp.limit - v_2; + sbp.ket = sbp.cursor; + if (sbp.eq_s_b(1, "j")) { + sbp.bra = sbp.cursor; + v_3 = sbp.limit - sbp.cursor; + if (!sbp.eq_s_b(1, "o")) { + sbp.cursor = sbp.limit - v_3; + if (sbp.eq_s_b(1, "u")) + sbp.slice_del(); + } else + sbp.slice_del(); + } + sbp.cursor = sbp.limit - v_2; + sbp.ket = sbp.cursor; + if (sbp.eq_s_b(1, "o")) { + sbp.bra = sbp.cursor; + if (sbp.eq_s_b(1, "j")) + sbp.slice_del(); + } + sbp.cursor = sbp.limit - v_2; + sbp.limit_backward = v_1; + while (true) { + v_4 = sbp.limit - sbp.cursor; + if (sbp.out_grouping_b(g_V1, 97, 246)) { + sbp.cursor = sbp.limit - v_4; + break; + } + sbp.cursor = sbp.limit - v_4; + if (sbp.cursor <= sbp.limit_backward) + return; + sbp.cursor--; + } + sbp.ket = sbp.cursor; + if (sbp.cursor > sbp.limit_backward) { + sbp.cursor--; + sbp.bra = sbp.cursor; + S_x = sbp.slice_to(); + if (sbp.eq_v_b(S_x)) + sbp.slice_del(); + } + } + } + this.stem = function() { + var v_1 = sbp.cursor; + r_mark_regions(); + B_ending_removed = false; + sbp.limit_backward = v_1; + sbp.cursor = sbp.limit; + r_particle_etc(); + sbp.cursor = sbp.limit; + r_possessive(); + sbp.cursor = sbp.limit; + r_case_ending(); + sbp.cursor = sbp.limit; + r_other_endings(); + sbp.cursor = sbp.limit; + if (B_ending_removed) { + r_i_plural(); + sbp.cursor = sbp.limit; + } else { + sbp.cursor = sbp.limit; + r_t_plural(); + sbp.cursor = sbp.limit; + } + r_tidy(); + return true; + } + }; + + /* and return a function that stems a word for the current locale */ + return function(token) { + // for lunr version 2 + if (typeof token.update === "function") { + return token.update(function(word) { + st.setCurrent(word); + st.stem(); + return st.getCurrent(); + }) + } else { // for lunr version <= 1 + st.setCurrent(token); + st.stem(); + return st.getCurrent(); + } + } + })(); + + lunr.Pipeline.registerFunction(lunr.fi.stemmer, 'stemmer-fi'); + + lunr.fi.stopWordFilter = lunr.generateStopWordFilter('ei eivät emme en et ette että he heidän heidät heihin heille heillä heiltä heissä heistä heitä hän häneen hänelle hänellä häneltä hänen hänessä hänestä hänet häntä itse ja johon joiden joihin joiksi joilla joille joilta joina joissa joista joita joka joksi jolla jolle jolta jona jonka jos jossa josta jota jotka kanssa keiden keihin keiksi keille keillä keiltä keinä keissä keistä keitä keneen keneksi kenelle kenellä keneltä kenen kenenä kenessä kenestä kenet ketkä ketkä ketä koska kuin kuka kun me meidän meidät meihin meille meillä meiltä meissä meistä meitä mihin miksi mikä mille millä miltä minkä minkä minua minulla minulle minulta minun minussa minusta minut minuun minä minä missä mistä mitkä mitä mukaan mutta ne niiden niihin niiksi niille niillä niiltä niin niin niinä niissä niistä niitä noiden noihin noiksi noilla noille noilta noin noina noissa noista noita nuo nyt näiden näihin näiksi näille näillä näiltä näinä näissä näistä näitä nämä ole olemme olen olet olette oli olimme olin olisi olisimme olisin olisit olisitte olisivat olit olitte olivat olla olleet ollut on ovat poikki se sekä sen siihen siinä siitä siksi sille sillä sillä siltä sinua sinulla sinulle sinulta sinun sinussa sinusta sinut sinuun sinä sinä sitä tai te teidän teidät teihin teille teillä teiltä teissä teistä teitä tuo tuohon tuoksi tuolla tuolle tuolta tuon tuona tuossa tuosta tuota tähän täksi tälle tällä tältä tämä tämän tänä tässä tästä tätä vaan vai vaikka yli'.split(' ')); + + lunr.Pipeline.registerFunction(lunr.fi.stopWordFilter, 'stopWordFilter-fi'); + }; +})) \ No newline at end of file diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.fr.js b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.fr.js new file mode 100644 index 0000000000000000000000000000000000000000..2de6d469b3353d0b21b5ed434c6c060d92086a79 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.fr.js @@ -0,0 +1,703 @@ +/*! + * Lunr languages, `French` language + * https://github.com/MihaiValentin/lunr-languages + * + * Copyright 2014, Mihai Valentin + * http://www.mozilla.org/MPL/ + */ +/*! + * based on + * Snowball JavaScript Library v0.3 + * http://code.google.com/p/urim/ + * http://snowball.tartarus.org/ + * + * Copyright 2010, Oleg Mazko + * http://www.mozilla.org/MPL/ + */ + +/** + * export the module via AMD, CommonJS or as a browser global + * Export code from https://github.com/umdjs/umd/blob/master/returnExports.js + */ +; +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(factory) + } else if (typeof exports === 'object') { + /** + * Node. Does not work with strict CommonJS, but + * only CommonJS-like environments that support module.exports, + * like Node. + */ + module.exports = factory() + } else { + // Browser globals (root is window) + factory()(root.lunr); + } +}(this, function() { + /** + * Just return a value to define the module export. + * This example returns an object, but the module + * can return a function as the exported value. + */ + return function(lunr) { + /* throw error if lunr is not yet included */ + if ('undefined' === typeof lunr) { + throw new Error('Lunr is not present. Please include / require Lunr before this script.'); + } + + /* throw error if lunr stemmer support is not yet included */ + if ('undefined' === typeof lunr.stemmerSupport) { + throw new Error('Lunr stemmer support is not present. Please include / require Lunr stemmer support before this script.'); + } + + /* register specific locale function */ + lunr.fr = function() { + this.pipeline.reset(); + this.pipeline.add( + lunr.fr.trimmer, + lunr.fr.stopWordFilter, + lunr.fr.stemmer + ); + + // for lunr version 2 + // this is necessary so that every searched word is also stemmed before + // in lunr <= 1 this is not needed, as it is done using the normal pipeline + if (this.searchPipeline) { + this.searchPipeline.reset(); + this.searchPipeline.add(lunr.fr.stemmer) + } + }; + + /* lunr trimmer function */ + lunr.fr.wordCharacters = "A-Za-z\xAA\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02B8\u02E0-\u02E4\u1D00-\u1D25\u1D2C-\u1D5C\u1D62-\u1D65\u1D6B-\u1D77\u1D79-\u1DBE\u1E00-\u1EFF\u2071\u207F\u2090-\u209C\u212A\u212B\u2132\u214E\u2160-\u2188\u2C60-\u2C7F\uA722-\uA787\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA7FF\uAB30-\uAB5A\uAB5C-\uAB64\uFB00-\uFB06\uFF21-\uFF3A\uFF41-\uFF5A"; + lunr.fr.trimmer = lunr.trimmerSupport.generateTrimmer(lunr.fr.wordCharacters); + + lunr.Pipeline.registerFunction(lunr.fr.trimmer, 'trimmer-fr'); + + /* lunr stemmer function */ + lunr.fr.stemmer = (function() { + /* create the wrapped stemmer object */ + var Among = lunr.stemmerSupport.Among, + SnowballProgram = lunr.stemmerSupport.SnowballProgram, + st = new function FrenchStemmer() { + var a_0 = [new Among("col", -1, -1), new Among("par", -1, -1), + new Among("tap", -1, -1) + ], + a_1 = [new Among("", -1, 4), + new Among("I", 0, 1), new Among("U", 0, 2), new Among("Y", 0, 3) + ], + a_2 = [ + new Among("iqU", -1, 3), new Among("abl", -1, 3), + new Among("I\u00E8r", -1, 4), new Among("i\u00E8r", -1, 4), + new Among("eus", -1, 2), new Among("iv", -1, 1) + ], + a_3 = [ + new Among("ic", -1, 2), new Among("abil", -1, 1), + new Among("iv", -1, 3) + ], + a_4 = [new Among("iqUe", -1, 1), + new Among("atrice", -1, 2), new Among("ance", -1, 1), + new Among("ence", -1, 5), new Among("logie", -1, 3), + new Among("able", -1, 1), new Among("isme", -1, 1), + new Among("euse", -1, 11), new Among("iste", -1, 1), + new Among("ive", -1, 8), new Among("if", -1, 8), + new Among("usion", -1, 4), new Among("ation", -1, 2), + new Among("ution", -1, 4), new Among("ateur", -1, 2), + new Among("iqUes", -1, 1), new Among("atrices", -1, 2), + new Among("ances", -1, 1), new Among("ences", -1, 5), + new Among("logies", -1, 3), new Among("ables", -1, 1), + new Among("ismes", -1, 1), new Among("euses", -1, 11), + new Among("istes", -1, 1), new Among("ives", -1, 8), + new Among("ifs", -1, 8), new Among("usions", -1, 4), + new Among("ations", -1, 2), new Among("utions", -1, 4), + new Among("ateurs", -1, 2), new Among("ments", -1, 15), + new Among("ements", 30, 6), new Among("issements", 31, 12), + new Among("it\u00E9s", -1, 7), new Among("ment", -1, 15), + new Among("ement", 34, 6), new Among("issement", 35, 12), + new Among("amment", 34, 13), new Among("emment", 34, 14), + new Among("aux", -1, 10), new Among("eaux", 39, 9), + new Among("eux", -1, 1), new Among("it\u00E9", -1, 7) + ], + a_5 = [ + new Among("ira", -1, 1), new Among("ie", -1, 1), + new Among("isse", -1, 1), new Among("issante", -1, 1), + new Among("i", -1, 1), new Among("irai", 4, 1), + new Among("ir", -1, 1), new Among("iras", -1, 1), + new Among("ies", -1, 1), new Among("\u00EEmes", -1, 1), + new Among("isses", -1, 1), new Among("issantes", -1, 1), + new Among("\u00EEtes", -1, 1), new Among("is", -1, 1), + new Among("irais", 13, 1), new Among("issais", 13, 1), + new Among("irions", -1, 1), new Among("issions", -1, 1), + new Among("irons", -1, 1), new Among("issons", -1, 1), + new Among("issants", -1, 1), new Among("it", -1, 1), + new Among("irait", 21, 1), new Among("issait", 21, 1), + new Among("issant", -1, 1), new Among("iraIent", -1, 1), + new Among("issaIent", -1, 1), new Among("irent", -1, 1), + new Among("issent", -1, 1), new Among("iront", -1, 1), + new Among("\u00EEt", -1, 1), new Among("iriez", -1, 1), + new Among("issiez", -1, 1), new Among("irez", -1, 1), + new Among("issez", -1, 1) + ], + a_6 = [new Among("a", -1, 3), + new Among("era", 0, 2), new Among("asse", -1, 3), + new Among("ante", -1, 3), new Among("\u00E9e", -1, 2), + new Among("ai", -1, 3), new Among("erai", 5, 2), + new Among("er", -1, 2), new Among("as", -1, 3), + new Among("eras", 8, 2), new Among("\u00E2mes", -1, 3), + new Among("asses", -1, 3), new Among("antes", -1, 3), + new Among("\u00E2tes", -1, 3), new Among("\u00E9es", -1, 2), + new Among("ais", -1, 3), new Among("erais", 15, 2), + new Among("ions", -1, 1), new Among("erions", 17, 2), + new Among("assions", 17, 3), new Among("erons", -1, 2), + new Among("ants", -1, 3), new Among("\u00E9s", -1, 2), + new Among("ait", -1, 3), new Among("erait", 23, 2), + new Among("ant", -1, 3), new Among("aIent", -1, 3), + new Among("eraIent", 26, 2), new Among("\u00E8rent", -1, 2), + new Among("assent", -1, 3), new Among("eront", -1, 2), + new Among("\u00E2t", -1, 3), new Among("ez", -1, 2), + new Among("iez", 32, 2), new Among("eriez", 33, 2), + new Among("assiez", 33, 3), new Among("erez", 32, 2), + new Among("\u00E9", -1, 2) + ], + a_7 = [new Among("e", -1, 3), + new Among("I\u00E8re", 0, 2), new Among("i\u00E8re", 0, 2), + new Among("ion", -1, 1), new Among("Ier", -1, 2), + new Among("ier", -1, 2), new Among("\u00EB", -1, 4) + ], + a_8 = [ + new Among("ell", -1, -1), new Among("eill", -1, -1), + new Among("enn", -1, -1), new Among("onn", -1, -1), + new Among("ett", -1, -1) + ], + g_v = [17, 65, 16, 1, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 128, 130, 103, 8, 5 + ], + g_keep_with_s = [1, 65, 20, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128 + ], + I_p2, I_p1, I_pV, sbp = new SnowballProgram(); + this.setCurrent = function(word) { + sbp.setCurrent(word); + }; + this.getCurrent = function() { + return sbp.getCurrent(); + }; + + function habr1(c1, c2, v_1) { + if (sbp.eq_s(1, c1)) { + sbp.ket = sbp.cursor; + if (sbp.in_grouping(g_v, 97, 251)) { + sbp.slice_from(c2); + sbp.cursor = v_1; + return true; + } + } + return false; + } + + function habr2(c1, c2, v_1) { + if (sbp.eq_s(1, c1)) { + sbp.ket = sbp.cursor; + sbp.slice_from(c2); + sbp.cursor = v_1; + return true; + } + return false; + } + + function r_prelude() { + var v_1, v_2; + while (true) { + v_1 = sbp.cursor; + if (sbp.in_grouping(g_v, 97, 251)) { + sbp.bra = sbp.cursor; + v_2 = sbp.cursor; + if (habr1("u", "U", v_1)) + continue; + sbp.cursor = v_2; + if (habr1("i", "I", v_1)) + continue; + sbp.cursor = v_2; + if (habr2("y", "Y", v_1)) + continue; + } + sbp.cursor = v_1; + sbp.bra = v_1; + if (!habr1("y", "Y", v_1)) { + sbp.cursor = v_1; + if (sbp.eq_s(1, "q")) { + sbp.bra = sbp.cursor; + if (habr2("u", "U", v_1)) + continue; + } + sbp.cursor = v_1; + if (v_1 >= sbp.limit) + return; + sbp.cursor++; + } + } + } + + function habr3() { + while (!sbp.in_grouping(g_v, 97, 251)) { + if (sbp.cursor >= sbp.limit) + return true; + sbp.cursor++; + } + while (!sbp.out_grouping(g_v, 97, 251)) { + if (sbp.cursor >= sbp.limit) + return true; + sbp.cursor++; + } + return false; + } + + function r_mark_regions() { + var v_1 = sbp.cursor; + I_pV = sbp.limit; + I_p1 = I_pV; + I_p2 = I_pV; + if (sbp.in_grouping(g_v, 97, 251) && sbp.in_grouping(g_v, 97, 251) && + sbp.cursor < sbp.limit) + sbp.cursor++; + else { + sbp.cursor = v_1; + if (!sbp.find_among(a_0, 3)) { + sbp.cursor = v_1; + do { + if (sbp.cursor >= sbp.limit) { + sbp.cursor = I_pV; + break; + } + sbp.cursor++; + } while (!sbp.in_grouping(g_v, 97, 251)); + } + } + I_pV = sbp.cursor; + sbp.cursor = v_1; + if (!habr3()) { + I_p1 = sbp.cursor; + if (!habr3()) + I_p2 = sbp.cursor; + } + } + + function r_postlude() { + var among_var, v_1; + while (true) { + v_1 = sbp.cursor; + sbp.bra = v_1; + among_var = sbp.find_among(a_1, 4); + if (!among_var) + break; + sbp.ket = sbp.cursor; + switch (among_var) { + case 1: + sbp.slice_from("i"); + break; + case 2: + sbp.slice_from("u"); + break; + case 3: + sbp.slice_from("y"); + break; + case 4: + if (sbp.cursor >= sbp.limit) + return; + sbp.cursor++; + break; + } + } + } + + function r_RV() { + return I_pV <= sbp.cursor; + } + + function r_R1() { + return I_p1 <= sbp.cursor; + } + + function r_R2() { + return I_p2 <= sbp.cursor; + } + + function r_standard_suffix() { + var among_var, v_1; + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_4, 43); + if (among_var) { + sbp.bra = sbp.cursor; + switch (among_var) { + case 1: + if (!r_R2()) + return false; + sbp.slice_del(); + break; + case 2: + if (!r_R2()) + return false; + sbp.slice_del(); + sbp.ket = sbp.cursor; + if (sbp.eq_s_b(2, "ic")) { + sbp.bra = sbp.cursor; + if (!r_R2()) + sbp.slice_from("iqU"); + else + sbp.slice_del(); + } + break; + case 3: + if (!r_R2()) + return false; + sbp.slice_from("log"); + break; + case 4: + if (!r_R2()) + return false; + sbp.slice_from("u"); + break; + case 5: + if (!r_R2()) + return false; + sbp.slice_from("ent"); + break; + case 6: + if (!r_RV()) + return false; + sbp.slice_del(); + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_2, 6); + if (among_var) { + sbp.bra = sbp.cursor; + switch (among_var) { + case 1: + if (r_R2()) { + sbp.slice_del(); + sbp.ket = sbp.cursor; + if (sbp.eq_s_b(2, "at")) { + sbp.bra = sbp.cursor; + if (r_R2()) + sbp.slice_del(); + } + } + break; + case 2: + if (r_R2()) + sbp.slice_del(); + else if (r_R1()) + sbp.slice_from("eux"); + break; + case 3: + if (r_R2()) + sbp.slice_del(); + break; + case 4: + if (r_RV()) + sbp.slice_from("i"); + break; + } + } + break; + case 7: + if (!r_R2()) + return false; + sbp.slice_del(); + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_3, 3); + if (among_var) { + sbp.bra = sbp.cursor; + switch (among_var) { + case 1: + if (r_R2()) + sbp.slice_del(); + else + sbp.slice_from("abl"); + break; + case 2: + if (r_R2()) + sbp.slice_del(); + else + sbp.slice_from("iqU"); + break; + case 3: + if (r_R2()) + sbp.slice_del(); + break; + } + } + break; + case 8: + if (!r_R2()) + return false; + sbp.slice_del(); + sbp.ket = sbp.cursor; + if (sbp.eq_s_b(2, "at")) { + sbp.bra = sbp.cursor; + if (r_R2()) { + sbp.slice_del(); + sbp.ket = sbp.cursor; + if (sbp.eq_s_b(2, "ic")) { + sbp.bra = sbp.cursor; + if (r_R2()) + sbp.slice_del(); + else + sbp.slice_from("iqU"); + break; + } + } + } + break; + case 9: + sbp.slice_from("eau"); + break; + case 10: + if (!r_R1()) + return false; + sbp.slice_from("al"); + break; + case 11: + if (r_R2()) + sbp.slice_del(); + else if (!r_R1()) + return false; + else + sbp.slice_from("eux"); + break; + case 12: + if (!r_R1() || !sbp.out_grouping_b(g_v, 97, 251)) + return false; + sbp.slice_del(); + break; + case 13: + if (r_RV()) + sbp.slice_from("ant"); + return false; + case 14: + if (r_RV()) + sbp.slice_from("ent"); + return false; + case 15: + v_1 = sbp.limit - sbp.cursor; + if (sbp.in_grouping_b(g_v, 97, 251) && r_RV()) { + sbp.cursor = sbp.limit - v_1; + sbp.slice_del(); + } + return false; + } + return true; + } + return false; + } + + function r_i_verb_suffix() { + var among_var, v_1; + if (sbp.cursor < I_pV) + return false; + v_1 = sbp.limit_backward; + sbp.limit_backward = I_pV; + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_5, 35); + if (!among_var) { + sbp.limit_backward = v_1; + return false; + } + sbp.bra = sbp.cursor; + if (among_var == 1) { + if (!sbp.out_grouping_b(g_v, 97, 251)) { + sbp.limit_backward = v_1; + return false; + } + sbp.slice_del(); + } + sbp.limit_backward = v_1; + return true; + } + + function r_verb_suffix() { + var among_var, v_2, v_3; + if (sbp.cursor < I_pV) + return false; + v_2 = sbp.limit_backward; + sbp.limit_backward = I_pV; + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_6, 38); + if (!among_var) { + sbp.limit_backward = v_2; + return false; + } + sbp.bra = sbp.cursor; + switch (among_var) { + case 1: + if (!r_R2()) { + sbp.limit_backward = v_2; + return false; + } + sbp.slice_del(); + break; + case 2: + sbp.slice_del(); + break; + case 3: + sbp.slice_del(); + v_3 = sbp.limit - sbp.cursor; + sbp.ket = sbp.cursor; + if (sbp.eq_s_b(1, "e")) { + sbp.bra = sbp.cursor; + sbp.slice_del(); + } else + sbp.cursor = sbp.limit - v_3; + break; + } + sbp.limit_backward = v_2; + return true; + } + + function r_residual_suffix() { + var among_var, v_1 = sbp.limit - sbp.cursor, + v_2, v_4, v_5; + sbp.ket = sbp.cursor; + if (sbp.eq_s_b(1, "s")) { + sbp.bra = sbp.cursor; + v_2 = sbp.limit - sbp.cursor; + if (sbp.out_grouping_b(g_keep_with_s, 97, 232)) { + sbp.cursor = sbp.limit - v_2; + sbp.slice_del(); + } else + sbp.cursor = sbp.limit - v_1; + } else + sbp.cursor = sbp.limit - v_1; + if (sbp.cursor >= I_pV) { + v_4 = sbp.limit_backward; + sbp.limit_backward = I_pV; + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_7, 7); + if (among_var) { + sbp.bra = sbp.cursor; + switch (among_var) { + case 1: + if (r_R2()) { + v_5 = sbp.limit - sbp.cursor; + if (!sbp.eq_s_b(1, "s")) { + sbp.cursor = sbp.limit - v_5; + if (!sbp.eq_s_b(1, "t")) + break; + } + sbp.slice_del(); + } + break; + case 2: + sbp.slice_from("i"); + break; + case 3: + sbp.slice_del(); + break; + case 4: + if (sbp.eq_s_b(2, "gu")) + sbp.slice_del(); + break; + } + } + sbp.limit_backward = v_4; + } + } + + function r_un_double() { + var v_1 = sbp.limit - sbp.cursor; + if (sbp.find_among_b(a_8, 5)) { + sbp.cursor = sbp.limit - v_1; + sbp.ket = sbp.cursor; + if (sbp.cursor > sbp.limit_backward) { + sbp.cursor--; + sbp.bra = sbp.cursor; + sbp.slice_del(); + } + } + } + + function r_un_accent() { + var v_1, v_2 = 1; + while (sbp.out_grouping_b(g_v, 97, 251)) + v_2--; + if (v_2 <= 0) { + sbp.ket = sbp.cursor; + v_1 = sbp.limit - sbp.cursor; + if (!sbp.eq_s_b(1, "\u00E9")) { + sbp.cursor = sbp.limit - v_1; + if (!sbp.eq_s_b(1, "\u00E8")) + return; + } + sbp.bra = sbp.cursor; + sbp.slice_from("e"); + } + } + + function habr5() { + if (!r_standard_suffix()) { + sbp.cursor = sbp.limit; + if (!r_i_verb_suffix()) { + sbp.cursor = sbp.limit; + if (!r_verb_suffix()) { + sbp.cursor = sbp.limit; + r_residual_suffix(); + return; + } + } + } + sbp.cursor = sbp.limit; + sbp.ket = sbp.cursor; + if (sbp.eq_s_b(1, "Y")) { + sbp.bra = sbp.cursor; + sbp.slice_from("i"); + } else { + sbp.cursor = sbp.limit; + if (sbp.eq_s_b(1, "\u00E7")) { + sbp.bra = sbp.cursor; + sbp.slice_from("c"); + } + } + } + this.stem = function() { + var v_1 = sbp.cursor; + r_prelude(); + sbp.cursor = v_1; + r_mark_regions(); + sbp.limit_backward = v_1; + sbp.cursor = sbp.limit; + habr5(); + sbp.cursor = sbp.limit; + r_un_double(); + sbp.cursor = sbp.limit; + r_un_accent(); + sbp.cursor = sbp.limit_backward; + r_postlude(); + return true; + } + }; + + /* and return a function that stems a word for the current locale */ + return function(token) { + // for lunr version 2 + if (typeof token.update === "function") { + return token.update(function(word) { + st.setCurrent(word); + st.stem(); + return st.getCurrent(); + }) + } else { // for lunr version <= 1 + st.setCurrent(token); + st.stem(); + return st.getCurrent(); + } + } + })(); + + lunr.Pipeline.registerFunction(lunr.fr.stemmer, 'stemmer-fr'); + + lunr.fr.stopWordFilter = lunr.generateStopWordFilter('ai aie aient aies ait as au aura aurai auraient aurais aurait auras aurez auriez aurions aurons auront aux avaient avais avait avec avez aviez avions avons ayant ayez ayons c ce ceci celà ces cet cette d dans de des du elle en es est et eu eue eues eurent eus eusse eussent eusses eussiez eussions eut eux eûmes eût eûtes furent fus fusse fussent fusses fussiez fussions fut fûmes fût fûtes ici il ils j je l la le les leur leurs lui m ma mais me mes moi mon même n ne nos notre nous on ont ou par pas pour qu que quel quelle quelles quels qui s sa sans se sera serai seraient serais serait seras serez seriez serions serons seront ses soi soient sois soit sommes son sont soyez soyons suis sur t ta te tes toi ton tu un une vos votre vous y à étaient étais était étant étiez étions été étée étées étés êtes'.split(' ')); + + lunr.Pipeline.registerFunction(lunr.fr.stopWordFilter, 'stopWordFilter-fr'); + }; +})) \ No newline at end of file diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.hi.js b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.hi.js new file mode 100644 index 0000000000000000000000000000000000000000..ed6a0c5bdb9e5c1074aaa3721387cd8901347063 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.hi.js @@ -0,0 +1,123 @@ +/*! + * Lunr languages, `Hindi` language + * https://github.com/MiKr13/lunr-languages + * + * Copyright 2020, Mihir Kumar + * http://www.mozilla.org/MPL/ + */ +/*! + * based on + * Snowball JavaScript Library v0.3 + * http://code.google.com/p/urim/ + * http://snowball.tartarus.org/ + * + * Copyright 2010, Oleg Mazko + * http://www.mozilla.org/MPL/ + */ + +/** + * export the module via AMD, CommonJS or as a browser global + * Export code from https://github.com/umdjs/umd/blob/master/returnExports.js + */ +; +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(factory) + } else if (typeof exports === 'object') { + /** + * Node. Does not work with strict CommonJS, but + * only CommonJS-like environments that support module.exports, + * like Node. + */ + module.exports = factory() + } else { + // Browser globals (root is window) + factory()(root.lunr); + } +}(this, function() { + /** + * Just return a value to define the module export. + * This example returns an object, but the module + * can return a function as the exported value. + */ + return function(lunr) { + /* throw error if lunr is not yet included */ + if ('undefined' === typeof lunr) { + throw new Error('Lunr is not present. Please include / require Lunr before this script.'); + } + + /* throw error if lunr stemmer support is not yet included */ + if ('undefined' === typeof lunr.stemmerSupport) { + throw new Error('Lunr stemmer support is not present. Please include / require Lunr stemmer support before this script.'); + } + + /* register specific locale function */ + lunr.hi = function() { + this.pipeline.reset(); + this.pipeline.add( + lunr.hi.trimmer, + lunr.hi.stopWordFilter, + lunr.hi.stemmer + ); + + // change the tokenizer for japanese one + // if (isLunr2) { // for lunr version 2.0.0 + // this.tokenizer = lunr.hi.tokenizer; + // } else { + // if (lunr.tokenizer) { // for lunr version 0.6.0 + // lunr.tokenizer = lunr.hi.tokenizer; + // } + // if (this.tokenizerFn) { // for lunr version 0.7.0 -> 1.0.0 + // this.tokenizerFn = lunr.hi.tokenizer; + // } + // } + + if (this.searchPipeline) { + this.searchPipeline.reset(); + this.searchPipeline.add(lunr.hi.stemmer) + } + }; + + /* lunr trimmer function */ + lunr.hi.wordCharacters = "\u0900-\u0903\u0904-\u090f\u0910-\u091f\u0920-\u092f\u0930-\u093f\u0940-\u094f\u0950-\u095f\u0960-\u096f\u0970-\u097fa-zA-Za-zA-Z0-90-9"; + // lunr.hi.wordCharacters = "ऀँंःऄअआइईउऊऋऌऍऎएऐऑऒओऔकखगघङचछजझञटठडढणतथदधनऩपफबभमयरऱलळऴवशषसहऺऻ़ऽािीुूृॄॅॆेैॉॊोौ्ॎॏॐ॒॑॓॔ॕॖॗक़ख़ग़ज़ड़ढ़फ़य़ॠॡॢॣ।॥०१२३४५६७८९॰ॱॲॳॴॵॶॷॸॹॺॻॼॽॾॿa-zA-Za-zA-Z0-90-9"; + lunr.hi.trimmer = lunr.trimmerSupport.generateTrimmer(lunr.hi.wordCharacters); + + lunr.Pipeline.registerFunction(lunr.hi.trimmer, 'trimmer-hi'); + /* lunr stop word filter */ + lunr.hi.stopWordFilter = lunr.generateStopWordFilter( + 'अत अपना अपनी अपने अभी अंदर आदि आप इत्यादि इन इनका इन्हीं इन्हें इन्हों इस इसका इसकी इसके इसमें इसी इसे उन उनका उनकी उनके उनको उन्हीं उन्हें उन्हों उस उसके उसी उसे एक एवं एस ऐसे और कई कर करता करते करना करने करें कहते कहा का काफ़ी कि कितना किन्हें किन्हों किया किर किस किसी किसे की कुछ कुल के को कोई कौन कौनसा गया घर जब जहाँ जा जितना जिन जिन्हें जिन्हों जिस जिसे जीधर जैसा जैसे जो तक तब तरह तिन तिन्हें तिन्हों तिस तिसे तो था थी थे दबारा दिया दुसरा दूसरे दो द्वारा न नके नहीं ना निहायत नीचे ने पर पहले पूरा पे फिर बनी बही बहुत बाद बाला बिलकुल भी भीतर मगर मानो मे में यदि यह यहाँ यही या यिह ये रखें रहा रहे ऱ्वासा लिए लिये लेकिन व वग़ैरह वर्ग वह वहाँ वहीं वाले वुह वे वो सकता सकते सबसे सभी साथ साबुत साभ सारा से सो संग ही हुआ हुई हुए है हैं हो होता होती होते होना होने'.split(' ')); + /* lunr stemmer function */ + lunr.hi.stemmer = (function() { + + return function(word) { + // for lunr version 2 + if (typeof word.update === "function") { + return word.update(function(word) { + return word; + }) + } else { // for lunr version <= 1 + return word; + } + + } + })(); + + var segmenter = lunr.wordcut; + segmenter.init(); + lunr.hi.tokenizer = function(obj) { + if (!arguments.length || obj == null || obj == undefined) return [] + if (Array.isArray(obj)) return obj.map(function(t) { + return isLunr2 ? new lunr.Token(t.toLowerCase()) : t.toLowerCase() + }); + + var str = obj.toString().toLowerCase().replace(/^\s+/, ''); + return segmenter.cut(str).split('|'); + } + + lunr.Pipeline.registerFunction(lunr.hi.stemmer, 'stemmer-hi'); + lunr.Pipeline.registerFunction(lunr.hi.stopWordFilter, 'stopWordFilter-hi'); + + }; +})) \ No newline at end of file diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.hu.js b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.hu.js new file mode 100644 index 0000000000000000000000000000000000000000..c52219ffeef26fb601da2071a682bd99304c10ea --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.hu.js @@ -0,0 +1,565 @@ +/*! + * Lunr languages, `Hungarian` language + * https://github.com/MihaiValentin/lunr-languages + * + * Copyright 2014, Mihai Valentin + * http://www.mozilla.org/MPL/ + */ +/*! + * based on + * Snowball JavaScript Library v0.3 + * http://code.google.com/p/urim/ + * http://snowball.tartarus.org/ + * + * Copyright 2010, Oleg Mazko + * http://www.mozilla.org/MPL/ + */ + +/** + * export the module via AMD, CommonJS or as a browser global + * Export code from https://github.com/umdjs/umd/blob/master/returnExports.js + */ +; +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(factory) + } else if (typeof exports === 'object') { + /** + * Node. Does not work with strict CommonJS, but + * only CommonJS-like environments that support module.exports, + * like Node. + */ + module.exports = factory() + } else { + // Browser globals (root is window) + factory()(root.lunr); + } +}(this, function() { + /** + * Just return a value to define the module export. + * This example returns an object, but the module + * can return a function as the exported value. + */ + return function(lunr) { + /* throw error if lunr is not yet included */ + if ('undefined' === typeof lunr) { + throw new Error('Lunr is not present. Please include / require Lunr before this script.'); + } + + /* throw error if lunr stemmer support is not yet included */ + if ('undefined' === typeof lunr.stemmerSupport) { + throw new Error('Lunr stemmer support is not present. Please include / require Lunr stemmer support before this script.'); + } + + /* register specific locale function */ + lunr.hu = function() { + this.pipeline.reset(); + this.pipeline.add( + lunr.hu.trimmer, + lunr.hu.stopWordFilter, + lunr.hu.stemmer + ); + + // for lunr version 2 + // this is necessary so that every searched word is also stemmed before + // in lunr <= 1 this is not needed, as it is done using the normal pipeline + if (this.searchPipeline) { + this.searchPipeline.reset(); + this.searchPipeline.add(lunr.hu.stemmer) + } + }; + + /* lunr trimmer function */ + lunr.hu.wordCharacters = "A-Za-z\xAA\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02B8\u02E0-\u02E4\u1D00-\u1D25\u1D2C-\u1D5C\u1D62-\u1D65\u1D6B-\u1D77\u1D79-\u1DBE\u1E00-\u1EFF\u2071\u207F\u2090-\u209C\u212A\u212B\u2132\u214E\u2160-\u2188\u2C60-\u2C7F\uA722-\uA787\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA7FF\uAB30-\uAB5A\uAB5C-\uAB64\uFB00-\uFB06\uFF21-\uFF3A\uFF41-\uFF5A"; + lunr.hu.trimmer = lunr.trimmerSupport.generateTrimmer(lunr.hu.wordCharacters); + + lunr.Pipeline.registerFunction(lunr.hu.trimmer, 'trimmer-hu'); + + /* lunr stemmer function */ + lunr.hu.stemmer = (function() { + /* create the wrapped stemmer object */ + var Among = lunr.stemmerSupport.Among, + SnowballProgram = lunr.stemmerSupport.SnowballProgram, + st = new function HungarianStemmer() { + var a_0 = [new Among("cs", -1, -1), new Among("dzs", -1, -1), + new Among("gy", -1, -1), new Among("ly", -1, -1), + new Among("ny", -1, -1), new Among("sz", -1, -1), + new Among("ty", -1, -1), new Among("zs", -1, -1) + ], + a_1 = [ + new Among("\u00E1", -1, 1), new Among("\u00E9", -1, 2) + ], + a_2 = [ + new Among("bb", -1, -1), new Among("cc", -1, -1), + new Among("dd", -1, -1), new Among("ff", -1, -1), + new Among("gg", -1, -1), new Among("jj", -1, -1), + new Among("kk", -1, -1), new Among("ll", -1, -1), + new Among("mm", -1, -1), new Among("nn", -1, -1), + new Among("pp", -1, -1), new Among("rr", -1, -1), + new Among("ccs", -1, -1), new Among("ss", -1, -1), + new Among("zzs", -1, -1), new Among("tt", -1, -1), + new Among("vv", -1, -1), new Among("ggy", -1, -1), + new Among("lly", -1, -1), new Among("nny", -1, -1), + new Among("tty", -1, -1), new Among("ssz", -1, -1), + new Among("zz", -1, -1) + ], + a_3 = [new Among("al", -1, 1), + new Among("el", -1, 2) + ], + a_4 = [new Among("ba", -1, -1), + new Among("ra", -1, -1), new Among("be", -1, -1), + new Among("re", -1, -1), new Among("ig", -1, -1), + new Among("nak", -1, -1), new Among("nek", -1, -1), + new Among("val", -1, -1), new Among("vel", -1, -1), + new Among("ul", -1, -1), new Among("n\u00E1l", -1, -1), + new Among("n\u00E9l", -1, -1), new Among("b\u00F3l", -1, -1), + new Among("r\u00F3l", -1, -1), new Among("t\u00F3l", -1, -1), + new Among("b\u00F5l", -1, -1), new Among("r\u00F5l", -1, -1), + new Among("t\u00F5l", -1, -1), new Among("\u00FCl", -1, -1), + new Among("n", -1, -1), new Among("an", 19, -1), + new Among("ban", 20, -1), new Among("en", 19, -1), + new Among("ben", 22, -1), new Among("k\u00E9ppen", 22, -1), + new Among("on", 19, -1), new Among("\u00F6n", 19, -1), + new Among("k\u00E9pp", -1, -1), new Among("kor", -1, -1), + new Among("t", -1, -1), new Among("at", 29, -1), + new Among("et", 29, -1), new Among("k\u00E9nt", 29, -1), + new Among("ank\u00E9nt", 32, -1), new Among("enk\u00E9nt", 32, -1), + new Among("onk\u00E9nt", 32, -1), new Among("ot", 29, -1), + new Among("\u00E9rt", 29, -1), new Among("\u00F6t", 29, -1), + new Among("hez", -1, -1), new Among("hoz", -1, -1), + new Among("h\u00F6z", -1, -1), new Among("v\u00E1", -1, -1), + new Among("v\u00E9", -1, -1) + ], + a_5 = [new Among("\u00E1n", -1, 2), + new Among("\u00E9n", -1, 1), new Among("\u00E1nk\u00E9nt", -1, 3) + ], + a_6 = [ + new Among("stul", -1, 2), new Among("astul", 0, 1), + new Among("\u00E1stul", 0, 3), new Among("st\u00FCl", -1, 2), + new Among("est\u00FCl", 3, 1), new Among("\u00E9st\u00FCl", 3, 4) + ], + a_7 = [ + new Among("\u00E1", -1, 1), new Among("\u00E9", -1, 2) + ], + a_8 = [ + new Among("k", -1, 7), new Among("ak", 0, 4), + new Among("ek", 0, 6), new Among("ok", 0, 5), + new Among("\u00E1k", 0, 1), new Among("\u00E9k", 0, 2), + new Among("\u00F6k", 0, 3) + ], + a_9 = [new Among("\u00E9i", -1, 7), + new Among("\u00E1\u00E9i", 0, 6), new Among("\u00E9\u00E9i", 0, 5), + new Among("\u00E9", -1, 9), new Among("k\u00E9", 3, 4), + new Among("ak\u00E9", 4, 1), new Among("ek\u00E9", 4, 1), + new Among("ok\u00E9", 4, 1), new Among("\u00E1k\u00E9", 4, 3), + new Among("\u00E9k\u00E9", 4, 2), new Among("\u00F6k\u00E9", 4, 1), + new Among("\u00E9\u00E9", 3, 8) + ], + a_10 = [new Among("a", -1, 18), + new Among("ja", 0, 17), new Among("d", -1, 16), + new Among("ad", 2, 13), new Among("ed", 2, 13), + new Among("od", 2, 13), new Among("\u00E1d", 2, 14), + new Among("\u00E9d", 2, 15), new Among("\u00F6d", 2, 13), + new Among("e", -1, 18), new Among("je", 9, 17), + new Among("nk", -1, 4), new Among("unk", 11, 1), + new Among("\u00E1nk", 11, 2), new Among("\u00E9nk", 11, 3), + new Among("\u00FCnk", 11, 1), new Among("uk", -1, 8), + new Among("juk", 16, 7), new Among("\u00E1juk", 17, 5), + new Among("\u00FCk", -1, 8), new Among("j\u00FCk", 19, 7), + new Among("\u00E9j\u00FCk", 20, 6), new Among("m", -1, 12), + new Among("am", 22, 9), new Among("em", 22, 9), + new Among("om", 22, 9), new Among("\u00E1m", 22, 10), + new Among("\u00E9m", 22, 11), new Among("o", -1, 18), + new Among("\u00E1", -1, 19), new Among("\u00E9", -1, 20) + ], + a_11 = [ + new Among("id", -1, 10), new Among("aid", 0, 9), + new Among("jaid", 1, 6), new Among("eid", 0, 9), + new Among("jeid", 3, 6), new Among("\u00E1id", 0, 7), + new Among("\u00E9id", 0, 8), new Among("i", -1, 15), + new Among("ai", 7, 14), new Among("jai", 8, 11), + new Among("ei", 7, 14), new Among("jei", 10, 11), + new Among("\u00E1i", 7, 12), new Among("\u00E9i", 7, 13), + new Among("itek", -1, 24), new Among("eitek", 14, 21), + new Among("jeitek", 15, 20), new Among("\u00E9itek", 14, 23), + new Among("ik", -1, 29), new Among("aik", 18, 26), + new Among("jaik", 19, 25), new Among("eik", 18, 26), + new Among("jeik", 21, 25), new Among("\u00E1ik", 18, 27), + new Among("\u00E9ik", 18, 28), new Among("ink", -1, 20), + new Among("aink", 25, 17), new Among("jaink", 26, 16), + new Among("eink", 25, 17), new Among("jeink", 28, 16), + new Among("\u00E1ink", 25, 18), new Among("\u00E9ink", 25, 19), + new Among("aitok", -1, 21), new Among("jaitok", 32, 20), + new Among("\u00E1itok", -1, 22), new Among("im", -1, 5), + new Among("aim", 35, 4), new Among("jaim", 36, 1), + new Among("eim", 35, 4), new Among("jeim", 38, 1), + new Among("\u00E1im", 35, 2), new Among("\u00E9im", 35, 3) + ], + g_v = [ + 17, 65, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 17, 52, 14 + ], + I_p1, sbp = new SnowballProgram(); + this.setCurrent = function(word) { + sbp.setCurrent(word); + }; + this.getCurrent = function() { + return sbp.getCurrent(); + }; + + function r_mark_regions() { + var v_1 = sbp.cursor, + v_2; + I_p1 = sbp.limit; + if (sbp.in_grouping(g_v, 97, 252)) { + while (true) { + v_2 = sbp.cursor; + if (sbp.out_grouping(g_v, 97, 252)) { + sbp.cursor = v_2; + if (!sbp.find_among(a_0, 8)) { + sbp.cursor = v_2; + if (v_2 < sbp.limit) + sbp.cursor++; + } + I_p1 = sbp.cursor; + return; + } + sbp.cursor = v_2; + if (v_2 >= sbp.limit) { + I_p1 = v_2; + return; + } + sbp.cursor++; + } + } + sbp.cursor = v_1; + if (sbp.out_grouping(g_v, 97, 252)) { + while (!sbp.in_grouping(g_v, 97, 252)) { + if (sbp.cursor >= sbp.limit) + return; + sbp.cursor++; + } + I_p1 = sbp.cursor; + } + } + + function r_R1() { + return I_p1 <= sbp.cursor; + } + + function r_v_ending() { + var among_var; + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_1, 2); + if (among_var) { + sbp.bra = sbp.cursor; + if (r_R1()) { + switch (among_var) { + case 1: + sbp.slice_from("a"); + break; + case 2: + sbp.slice_from("e"); + break; + } + } + } + } + + function r_double() { + var v_1 = sbp.limit - sbp.cursor; + if (!sbp.find_among_b(a_2, 23)) + return false; + sbp.cursor = sbp.limit - v_1; + return true; + } + + function r_undouble() { + if (sbp.cursor > sbp.limit_backward) { + sbp.cursor--; + sbp.ket = sbp.cursor; + var c = sbp.cursor - 1; + if (sbp.limit_backward <= c && c <= sbp.limit) { + sbp.cursor = c; + sbp.bra = c; + sbp.slice_del(); + } + } + } + + function r_instrum() { + var among_var; + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_3, 2); + if (among_var) { + sbp.bra = sbp.cursor; + if (r_R1()) { + if (among_var == 1 || among_var == 2) + if (!r_double()) + return; + sbp.slice_del(); + r_undouble(); + } + } + } + + function r_case() { + sbp.ket = sbp.cursor; + if (sbp.find_among_b(a_4, 44)) { + sbp.bra = sbp.cursor; + if (r_R1()) { + sbp.slice_del(); + r_v_ending(); + } + } + } + + function r_case_special() { + var among_var; + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_5, 3); + if (among_var) { + sbp.bra = sbp.cursor; + if (r_R1()) { + switch (among_var) { + case 1: + sbp.slice_from("e"); + break; + case 2: + case 3: + sbp.slice_from("a"); + break; + } + } + } + } + + function r_case_other() { + var among_var; + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_6, 6); + if (among_var) { + sbp.bra = sbp.cursor; + if (r_R1()) { + switch (among_var) { + case 1: + case 2: + sbp.slice_del(); + break; + case 3: + sbp.slice_from("a"); + break; + case 4: + sbp.slice_from("e"); + break; + } + } + } + } + + function r_factive() { + var among_var; + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_7, 2); + if (among_var) { + sbp.bra = sbp.cursor; + if (r_R1()) { + if (among_var == 1 || among_var == 2) + if (!r_double()) + return; + sbp.slice_del(); + r_undouble() + } + } + } + + function r_plural() { + var among_var; + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_8, 7); + if (among_var) { + sbp.bra = sbp.cursor; + if (r_R1()) { + switch (among_var) { + case 1: + sbp.slice_from("a"); + break; + case 2: + sbp.slice_from("e"); + break; + case 3: + case 4: + case 5: + case 6: + case 7: + sbp.slice_del(); + break; + } + } + } + } + + function r_owned() { + var among_var; + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_9, 12); + if (among_var) { + sbp.bra = sbp.cursor; + if (r_R1()) { + switch (among_var) { + case 1: + case 4: + case 7: + case 9: + sbp.slice_del(); + break; + case 2: + case 5: + case 8: + sbp.slice_from("e"); + break; + case 3: + case 6: + sbp.slice_from("a"); + break; + } + } + } + } + + function r_sing_owner() { + var among_var; + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_10, 31); + if (among_var) { + sbp.bra = sbp.cursor; + if (r_R1()) { + switch (among_var) { + case 1: + case 4: + case 7: + case 8: + case 9: + case 12: + case 13: + case 16: + case 17: + case 18: + sbp.slice_del(); + break; + case 2: + case 5: + case 10: + case 14: + case 19: + sbp.slice_from("a"); + break; + case 3: + case 6: + case 11: + case 15: + case 20: + sbp.slice_from("e"); + break; + } + } + } + } + + function r_plur_owner() { + var among_var; + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_11, 42); + if (among_var) { + sbp.bra = sbp.cursor; + if (r_R1()) { + switch (among_var) { + case 1: + case 4: + case 5: + case 6: + case 9: + case 10: + case 11: + case 14: + case 15: + case 16: + case 17: + case 20: + case 21: + case 24: + case 25: + case 26: + case 29: + sbp.slice_del(); + break; + case 2: + case 7: + case 12: + case 18: + case 22: + case 27: + sbp.slice_from("a"); + break; + case 3: + case 8: + case 13: + case 19: + case 23: + case 28: + sbp.slice_from("e"); + break; + } + } + } + } + this.stem = function() { + var v_1 = sbp.cursor; + r_mark_regions(); + sbp.limit_backward = v_1; + sbp.cursor = sbp.limit; + r_instrum(); + sbp.cursor = sbp.limit; + r_case(); + sbp.cursor = sbp.limit; + r_case_special(); + sbp.cursor = sbp.limit; + r_case_other(); + sbp.cursor = sbp.limit; + r_factive(); + sbp.cursor = sbp.limit; + r_owned(); + sbp.cursor = sbp.limit; + r_sing_owner(); + sbp.cursor = sbp.limit; + r_plur_owner(); + sbp.cursor = sbp.limit; + r_plural(); + return true; + } + }; + + /* and return a function that stems a word for the current locale */ + return function(token) { + // for lunr version 2 + if (typeof token.update === "function") { + return token.update(function(word) { + st.setCurrent(word); + st.stem(); + return st.getCurrent(); + }) + } else { // for lunr version <= 1 + st.setCurrent(token); + st.stem(); + return st.getCurrent(); + } + } + })(); + + lunr.Pipeline.registerFunction(lunr.hu.stemmer, 'stemmer-hu'); + + lunr.hu.stopWordFilter = lunr.generateStopWordFilter('a abban ahhoz ahogy ahol aki akik akkor alatt amely amelyek amelyekben amelyeket amelyet amelynek ami amikor amit amolyan amíg annak arra arról az azok azon azonban azt aztán azután azzal azért be belül benne bár cikk cikkek cikkeket csak de e ebben eddig egy egyes egyetlen egyik egyre egyéb egész ehhez ekkor el ellen elsõ elég elõ elõször elõtt emilyen ennek erre ez ezek ezen ezt ezzel ezért fel felé hanem hiszen hogy hogyan igen ill ill. illetve ilyen ilyenkor ismét ison itt jobban jó jól kell kellett keressünk keresztül ki kívül között közül legalább legyen lehet lehetett lenne lenni lesz lett maga magát majd majd meg mellett mely melyek mert mi mikor milyen minden mindenki mindent mindig mint mintha mit mivel miért most már más másik még míg nagy nagyobb nagyon ne nekem neki nem nincs néha néhány nélkül olyan ott pedig persze rá s saját sem semmi sok sokat sokkal szemben szerint szinte számára talán tehát teljes tovább továbbá több ugyanis utolsó után utána vagy vagyis vagyok valaki valami valamint való van vannak vele vissza viszont volna volt voltak voltam voltunk által általában át én éppen és így õ õk õket össze úgy új újabb újra'.split(' ')); + + lunr.Pipeline.registerFunction(lunr.hu.stopWordFilter, 'stopWordFilter-hu'); + }; +})) \ No newline at end of file diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.hy.js b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.hy.js new file mode 100644 index 0000000000000000000000000000000000000000..3336e0f71051124a4efd0b003c43cac3e04d0d81 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.hy.js @@ -0,0 +1,98 @@ +/*! + * Lunr languages, `Armenian` language + * https://github.com/turbobit/lunr-languages + * + * Copyright 2021, Manikandan Venkatasubban + * http://www.mozilla.org/MPL/ + */ +/*! + * based on + * Snowball JavaScript Library v0.3 + * http://code.google.com/p/urim/ + * http://snowball.tartarus.org/ + * + * Copyright 2010, Oleg Mazko + * http://www.mozilla.org/MPL/ + */ + +/** + * export the module via AMD, CommonJS or as a browser global + * Export code from https://github.com/umdjs/umd/blob/master/returnExports.js + */ +; +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(factory) + } else if (typeof exports === 'object') { + /** + * Node. Does not work with strict CommonJS, but + * only CommonJS-like environments that support module.exports, + * like Node. + */ + module.exports = factory() + } else { + // Browser globals (root is window) + factory()(root.lunr); + } +}(this, function() { + /** + * Just return a value to define the module export. + * This example returns an object, but the module + * can return a function as the exported value. + */ + return function(lunr) { + /* throw error if lunr is not yet included */ + if ('undefined' === typeof lunr) { + throw new Error('Lunr is not present. Please include / require Lunr before this script.'); + } + + /* throw error if lunr stemmer support is not yet included */ + if ('undefined' === typeof lunr.stemmerSupport) { + throw new Error('Lunr stemmer support is not present. Please include / require Lunr stemmer support before this script.'); + } + + /* register specific locale function */ + lunr.hy = function() { + this.pipeline.reset(); + this.pipeline.add( + lunr.hy.trimmer, + lunr.hy.stopWordFilter + ); + }; + + /* lunr trimmer function */ + // http://www.unicode.org/charts/ + lunr.hy.wordCharacters = "[" + + "A-Za-z" + + "\u0530-\u058F" + // armenian alphabet + "\uFB00-\uFB4F" + // armenian ligatures + "]"; + lunr.hy.trimmer = lunr.trimmerSupport.generateTrimmer(lunr.hy.wordCharacters); + + lunr.Pipeline.registerFunction(lunr.hy.trimmer, 'trimmer-hy'); + + + /* lunr stop word filter */ + // https://www.ranks.nl/stopwords/armenian + lunr.hy.stopWordFilter = lunr.generateStopWordFilter('դու և եք էիր էիք հետո նաև նրանք որը վրա է որ պիտի են այս մեջ ն իր ու ի այդ որոնք այն կամ էր մի ես համար այլ իսկ էին ենք հետ ին թ էինք մենք նրա նա դուք եմ էի ըստ որպես ում'.split(' ')); + lunr.Pipeline.registerFunction(lunr.hy.stopWordFilter, 'stopWordFilter-hy'); + + /* lunr stemmer function */ + lunr.hy.stemmer = (function() { + + return function(word) { + // for lunr version 2 + if (typeof word.update === "function") { + return word.update(function(word) { + return word; + }) + } else { // for lunr version <= 1 + return word; + } + + } + })(); + lunr.Pipeline.registerFunction(lunr.hy.stemmer, 'stemmer-hy'); + }; +})) \ No newline at end of file diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.it.js b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.it.js new file mode 100644 index 0000000000000000000000000000000000000000..676863b56358a457db9b09c52a62ef7b4cbf3214 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.it.js @@ -0,0 +1,617 @@ +/*! + * Lunr languages, `Italian` language + * https://github.com/MihaiValentin/lunr-languages + * + * Copyright 2014, Mihai Valentin + * http://www.mozilla.org/MPL/ + */ +/*! + * based on + * Snowball JavaScript Library v0.3 + * http://code.google.com/p/urim/ + * http://snowball.tartarus.org/ + * + * Copyright 2010, Oleg Mazko + * http://www.mozilla.org/MPL/ + */ + +/** + * export the module via AMD, CommonJS or as a browser global + * Export code from https://github.com/umdjs/umd/blob/master/returnExports.js + */ +; +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(factory) + } else if (typeof exports === 'object') { + /** + * Node. Does not work with strict CommonJS, but + * only CommonJS-like environments that support module.exports, + * like Node. + */ + module.exports = factory() + } else { + // Browser globals (root is window) + factory()(root.lunr); + } +}(this, function() { + /** + * Just return a value to define the module export. + * This example returns an object, but the module + * can return a function as the exported value. + */ + return function(lunr) { + /* throw error if lunr is not yet included */ + if ('undefined' === typeof lunr) { + throw new Error('Lunr is not present. Please include / require Lunr before this script.'); + } + + /* throw error if lunr stemmer support is not yet included */ + if ('undefined' === typeof lunr.stemmerSupport) { + throw new Error('Lunr stemmer support is not present. Please include / require Lunr stemmer support before this script.'); + } + + /* register specific locale function */ + lunr.it = function() { + this.pipeline.reset(); + this.pipeline.add( + lunr.it.trimmer, + lunr.it.stopWordFilter, + lunr.it.stemmer + ); + + // for lunr version 2 + // this is necessary so that every searched word is also stemmed before + // in lunr <= 1 this is not needed, as it is done using the normal pipeline + if (this.searchPipeline) { + this.searchPipeline.reset(); + this.searchPipeline.add(lunr.it.stemmer) + } + }; + + /* lunr trimmer function */ + lunr.it.wordCharacters = "A-Za-z\xAA\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02B8\u02E0-\u02E4\u1D00-\u1D25\u1D2C-\u1D5C\u1D62-\u1D65\u1D6B-\u1D77\u1D79-\u1DBE\u1E00-\u1EFF\u2071\u207F\u2090-\u209C\u212A\u212B\u2132\u214E\u2160-\u2188\u2C60-\u2C7F\uA722-\uA787\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA7FF\uAB30-\uAB5A\uAB5C-\uAB64\uFB00-\uFB06\uFF21-\uFF3A\uFF41-\uFF5A"; + lunr.it.trimmer = lunr.trimmerSupport.generateTrimmer(lunr.it.wordCharacters); + + lunr.Pipeline.registerFunction(lunr.it.trimmer, 'trimmer-it'); + + /* lunr stemmer function */ + lunr.it.stemmer = (function() { + /* create the wrapped stemmer object */ + var Among = lunr.stemmerSupport.Among, + SnowballProgram = lunr.stemmerSupport.SnowballProgram, + st = new function ItalianStemmer() { + var a_0 = [new Among("", -1, 7), new Among("qu", 0, 6), + new Among("\u00E1", 0, 1), new Among("\u00E9", 0, 2), + new Among("\u00ED", 0, 3), new Among("\u00F3", 0, 4), + new Among("\u00FA", 0, 5) + ], + a_1 = [new Among("", -1, 3), + new Among("I", 0, 1), new Among("U", 0, 2) + ], + a_2 = [ + new Among("la", -1, -1), new Among("cela", 0, -1), + new Among("gliela", 0, -1), new Among("mela", 0, -1), + new Among("tela", 0, -1), new Among("vela", 0, -1), + new Among("le", -1, -1), new Among("cele", 6, -1), + new Among("gliele", 6, -1), new Among("mele", 6, -1), + new Among("tele", 6, -1), new Among("vele", 6, -1), + new Among("ne", -1, -1), new Among("cene", 12, -1), + new Among("gliene", 12, -1), new Among("mene", 12, -1), + new Among("sene", 12, -1), new Among("tene", 12, -1), + new Among("vene", 12, -1), new Among("ci", -1, -1), + new Among("li", -1, -1), new Among("celi", 20, -1), + new Among("glieli", 20, -1), new Among("meli", 20, -1), + new Among("teli", 20, -1), new Among("veli", 20, -1), + new Among("gli", 20, -1), new Among("mi", -1, -1), + new Among("si", -1, -1), new Among("ti", -1, -1), + new Among("vi", -1, -1), new Among("lo", -1, -1), + new Among("celo", 31, -1), new Among("glielo", 31, -1), + new Among("melo", 31, -1), new Among("telo", 31, -1), + new Among("velo", 31, -1) + ], + a_3 = [new Among("ando", -1, 1), + new Among("endo", -1, 1), new Among("ar", -1, 2), + new Among("er", -1, 2), new Among("ir", -1, 2) + ], + a_4 = [ + new Among("ic", -1, -1), new Among("abil", -1, -1), + new Among("os", -1, -1), new Among("iv", -1, 1) + ], + a_5 = [ + new Among("ic", -1, 1), new Among("abil", -1, 1), + new Among("iv", -1, 1) + ], + a_6 = [new Among("ica", -1, 1), + new Among("logia", -1, 3), new Among("osa", -1, 1), + new Among("ista", -1, 1), new Among("iva", -1, 9), + new Among("anza", -1, 1), new Among("enza", -1, 5), + new Among("ice", -1, 1), new Among("atrice", 7, 1), + new Among("iche", -1, 1), new Among("logie", -1, 3), + new Among("abile", -1, 1), new Among("ibile", -1, 1), + new Among("usione", -1, 4), new Among("azione", -1, 2), + new Among("uzione", -1, 4), new Among("atore", -1, 2), + new Among("ose", -1, 1), new Among("ante", -1, 1), + new Among("mente", -1, 1), new Among("amente", 19, 7), + new Among("iste", -1, 1), new Among("ive", -1, 9), + new Among("anze", -1, 1), new Among("enze", -1, 5), + new Among("ici", -1, 1), new Among("atrici", 25, 1), + new Among("ichi", -1, 1), new Among("abili", -1, 1), + new Among("ibili", -1, 1), new Among("ismi", -1, 1), + new Among("usioni", -1, 4), new Among("azioni", -1, 2), + new Among("uzioni", -1, 4), new Among("atori", -1, 2), + new Among("osi", -1, 1), new Among("anti", -1, 1), + new Among("amenti", -1, 6), new Among("imenti", -1, 6), + new Among("isti", -1, 1), new Among("ivi", -1, 9), + new Among("ico", -1, 1), new Among("ismo", -1, 1), + new Among("oso", -1, 1), new Among("amento", -1, 6), + new Among("imento", -1, 6), new Among("ivo", -1, 9), + new Among("it\u00E0", -1, 8), new Among("ist\u00E0", -1, 1), + new Among("ist\u00E8", -1, 1), new Among("ist\u00EC", -1, 1) + ], + a_7 = [ + new Among("isca", -1, 1), new Among("enda", -1, 1), + new Among("ata", -1, 1), new Among("ita", -1, 1), + new Among("uta", -1, 1), new Among("ava", -1, 1), + new Among("eva", -1, 1), new Among("iva", -1, 1), + new Among("erebbe", -1, 1), new Among("irebbe", -1, 1), + new Among("isce", -1, 1), new Among("ende", -1, 1), + new Among("are", -1, 1), new Among("ere", -1, 1), + new Among("ire", -1, 1), new Among("asse", -1, 1), + new Among("ate", -1, 1), new Among("avate", 16, 1), + new Among("evate", 16, 1), new Among("ivate", 16, 1), + new Among("ete", -1, 1), new Among("erete", 20, 1), + new Among("irete", 20, 1), new Among("ite", -1, 1), + new Among("ereste", -1, 1), new Among("ireste", -1, 1), + new Among("ute", -1, 1), new Among("erai", -1, 1), + new Among("irai", -1, 1), new Among("isci", -1, 1), + new Among("endi", -1, 1), new Among("erei", -1, 1), + new Among("irei", -1, 1), new Among("assi", -1, 1), + new Among("ati", -1, 1), new Among("iti", -1, 1), + new Among("eresti", -1, 1), new Among("iresti", -1, 1), + new Among("uti", -1, 1), new Among("avi", -1, 1), + new Among("evi", -1, 1), new Among("ivi", -1, 1), + new Among("isco", -1, 1), new Among("ando", -1, 1), + new Among("endo", -1, 1), new Among("Yamo", -1, 1), + new Among("iamo", -1, 1), new Among("avamo", -1, 1), + new Among("evamo", -1, 1), new Among("ivamo", -1, 1), + new Among("eremo", -1, 1), new Among("iremo", -1, 1), + new Among("assimo", -1, 1), new Among("ammo", -1, 1), + new Among("emmo", -1, 1), new Among("eremmo", 54, 1), + new Among("iremmo", 54, 1), new Among("immo", -1, 1), + new Among("ano", -1, 1), new Among("iscano", 58, 1), + new Among("avano", 58, 1), new Among("evano", 58, 1), + new Among("ivano", 58, 1), new Among("eranno", -1, 1), + new Among("iranno", -1, 1), new Among("ono", -1, 1), + new Among("iscono", 65, 1), new Among("arono", 65, 1), + new Among("erono", 65, 1), new Among("irono", 65, 1), + new Among("erebbero", -1, 1), new Among("irebbero", -1, 1), + new Among("assero", -1, 1), new Among("essero", -1, 1), + new Among("issero", -1, 1), new Among("ato", -1, 1), + new Among("ito", -1, 1), new Among("uto", -1, 1), + new Among("avo", -1, 1), new Among("evo", -1, 1), + new Among("ivo", -1, 1), new Among("ar", -1, 1), + new Among("ir", -1, 1), new Among("er\u00E0", -1, 1), + new Among("ir\u00E0", -1, 1), new Among("er\u00F2", -1, 1), + new Among("ir\u00F2", -1, 1) + ], + g_v = [17, 65, 16, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 128, 128, 8, 2, 1 + ], + g_AEIO = [17, 65, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 8, 2 + ], + g_CG = [17], + I_p2, I_p1, I_pV, sbp = new SnowballProgram(); + this.setCurrent = function(word) { + sbp.setCurrent(word); + }; + this.getCurrent = function() { + return sbp.getCurrent(); + }; + + function habr1(c1, c2, v_1) { + if (sbp.eq_s(1, c1)) { + sbp.ket = sbp.cursor; + if (sbp.in_grouping(g_v, 97, 249)) { + sbp.slice_from(c2); + sbp.cursor = v_1; + return true; + } + } + return false; + } + + function r_prelude() { + var among_var, v_1 = sbp.cursor, + v_2, v_3, v_4; + while (true) { + sbp.bra = sbp.cursor; + among_var = sbp.find_among(a_0, 7); + if (among_var) { + sbp.ket = sbp.cursor; + switch (among_var) { + case 1: + sbp.slice_from("\u00E0"); + continue; + case 2: + sbp.slice_from("\u00E8"); + continue; + case 3: + sbp.slice_from("\u00EC"); + continue; + case 4: + sbp.slice_from("\u00F2"); + continue; + case 5: + sbp.slice_from("\u00F9"); + continue; + case 6: + sbp.slice_from("qU"); + continue; + case 7: + if (sbp.cursor >= sbp.limit) + break; + sbp.cursor++; + continue; + } + } + break; + } + sbp.cursor = v_1; + while (true) { + v_2 = sbp.cursor; + while (true) { + v_3 = sbp.cursor; + if (sbp.in_grouping(g_v, 97, 249)) { + sbp.bra = sbp.cursor; + v_4 = sbp.cursor; + if (habr1("u", "U", v_3)) + break; + sbp.cursor = v_4; + if (habr1("i", "I", v_3)) + break; + } + sbp.cursor = v_3; + if (sbp.cursor >= sbp.limit) { + sbp.cursor = v_2; + return; + } + sbp.cursor++; + } + } + } + + function habr2(v_1) { + sbp.cursor = v_1; + if (!sbp.in_grouping(g_v, 97, 249)) + return false; + while (!sbp.out_grouping(g_v, 97, 249)) { + if (sbp.cursor >= sbp.limit) + return false; + sbp.cursor++; + } + return true; + } + + function habr3() { + if (sbp.in_grouping(g_v, 97, 249)) { + var v_1 = sbp.cursor; + if (sbp.out_grouping(g_v, 97, 249)) { + while (!sbp.in_grouping(g_v, 97, 249)) { + if (sbp.cursor >= sbp.limit) + return habr2(v_1); + sbp.cursor++; + } + return true; + } + return habr2(v_1); + } + return false; + } + + function habr4() { + var v_1 = sbp.cursor, + v_2; + if (!habr3()) { + sbp.cursor = v_1; + if (!sbp.out_grouping(g_v, 97, 249)) + return; + v_2 = sbp.cursor; + if (sbp.out_grouping(g_v, 97, 249)) { + while (!sbp.in_grouping(g_v, 97, 249)) { + if (sbp.cursor >= sbp.limit) { + sbp.cursor = v_2; + if (sbp.in_grouping(g_v, 97, 249) && + sbp.cursor < sbp.limit) + sbp.cursor++; + return; + } + sbp.cursor++; + } + I_pV = sbp.cursor; + return; + } + sbp.cursor = v_2; + if (!sbp.in_grouping(g_v, 97, 249) || sbp.cursor >= sbp.limit) + return; + sbp.cursor++; + } + I_pV = sbp.cursor; + } + + function habr5() { + while (!sbp.in_grouping(g_v, 97, 249)) { + if (sbp.cursor >= sbp.limit) + return false; + sbp.cursor++; + } + while (!sbp.out_grouping(g_v, 97, 249)) { + if (sbp.cursor >= sbp.limit) + return false; + sbp.cursor++; + } + return true; + } + + function r_mark_regions() { + var v_1 = sbp.cursor; + I_pV = sbp.limit; + I_p1 = I_pV; + I_p2 = I_pV; + habr4(); + sbp.cursor = v_1; + if (habr5()) { + I_p1 = sbp.cursor; + if (habr5()) + I_p2 = sbp.cursor; + } + } + + function r_postlude() { + var among_var; + while (true) { + sbp.bra = sbp.cursor; + among_var = sbp.find_among(a_1, 3); + if (!among_var) + break; + sbp.ket = sbp.cursor; + switch (among_var) { + case 1: + sbp.slice_from("i"); + break; + case 2: + sbp.slice_from("u"); + break; + case 3: + if (sbp.cursor >= sbp.limit) + return; + sbp.cursor++; + break; + } + } + } + + function r_RV() { + return I_pV <= sbp.cursor; + } + + function r_R1() { + return I_p1 <= sbp.cursor; + } + + function r_R2() { + return I_p2 <= sbp.cursor; + } + + function r_attached_pronoun() { + var among_var; + sbp.ket = sbp.cursor; + if (sbp.find_among_b(a_2, 37)) { + sbp.bra = sbp.cursor; + among_var = sbp.find_among_b(a_3, 5); + if (among_var && r_RV()) { + switch (among_var) { + case 1: + sbp.slice_del(); + break; + case 2: + sbp.slice_from("e"); + break; + } + } + } + } + + function r_standard_suffix() { + var among_var; + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_6, 51); + if (!among_var) + return false; + sbp.bra = sbp.cursor; + switch (among_var) { + case 1: + if (!r_R2()) + return false; + sbp.slice_del(); + break; + case 2: + if (!r_R2()) + return false; + sbp.slice_del(); + sbp.ket = sbp.cursor; + if (sbp.eq_s_b(2, "ic")) { + sbp.bra = sbp.cursor; + if (r_R2()) + sbp.slice_del(); + } + break; + case 3: + if (!r_R2()) + return false; + sbp.slice_from("log"); + break; + case 4: + if (!r_R2()) + return false; + sbp.slice_from("u"); + break; + case 5: + if (!r_R2()) + return false; + sbp.slice_from("ente"); + break; + case 6: + if (!r_RV()) + return false; + sbp.slice_del(); + break; + case 7: + if (!r_R1()) + return false; + sbp.slice_del(); + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_4, 4); + if (among_var) { + sbp.bra = sbp.cursor; + if (r_R2()) { + sbp.slice_del(); + if (among_var == 1) { + sbp.ket = sbp.cursor; + if (sbp.eq_s_b(2, "at")) { + sbp.bra = sbp.cursor; + if (r_R2()) + sbp.slice_del(); + } + } + } + } + break; + case 8: + if (!r_R2()) + return false; + sbp.slice_del(); + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_5, 3); + if (among_var) { + sbp.bra = sbp.cursor; + if (among_var == 1) + if (r_R2()) + sbp.slice_del(); + } + break; + case 9: + if (!r_R2()) + return false; + sbp.slice_del(); + sbp.ket = sbp.cursor; + if (sbp.eq_s_b(2, "at")) { + sbp.bra = sbp.cursor; + if (r_R2()) { + sbp.slice_del(); + sbp.ket = sbp.cursor; + if (sbp.eq_s_b(2, "ic")) { + sbp.bra = sbp.cursor; + if (r_R2()) + sbp.slice_del(); + } + } + } + break; + } + return true; + } + + function r_verb_suffix() { + var among_var, v_1; + if (sbp.cursor >= I_pV) { + v_1 = sbp.limit_backward; + sbp.limit_backward = I_pV; + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_7, 87); + if (among_var) { + sbp.bra = sbp.cursor; + if (among_var == 1) + sbp.slice_del(); + } + sbp.limit_backward = v_1; + } + } + + function habr6() { + var v_1 = sbp.limit - sbp.cursor; + sbp.ket = sbp.cursor; + if (sbp.in_grouping_b(g_AEIO, 97, 242)) { + sbp.bra = sbp.cursor; + if (r_RV()) { + sbp.slice_del(); + sbp.ket = sbp.cursor; + if (sbp.eq_s_b(1, "i")) { + sbp.bra = sbp.cursor; + if (r_RV()) { + sbp.slice_del(); + return; + } + } + } + } + sbp.cursor = sbp.limit - v_1; + } + + function r_vowel_suffix() { + habr6(); + sbp.ket = sbp.cursor; + if (sbp.eq_s_b(1, "h")) { + sbp.bra = sbp.cursor; + if (sbp.in_grouping_b(g_CG, 99, 103)) + if (r_RV()) + sbp.slice_del(); + } + } + this.stem = function() { + var v_1 = sbp.cursor; + r_prelude(); + sbp.cursor = v_1; + r_mark_regions(); + sbp.limit_backward = v_1; + sbp.cursor = sbp.limit; + r_attached_pronoun(); + sbp.cursor = sbp.limit; + if (!r_standard_suffix()) { + sbp.cursor = sbp.limit; + r_verb_suffix(); + } + sbp.cursor = sbp.limit; + r_vowel_suffix(); + sbp.cursor = sbp.limit_backward; + r_postlude(); + return true; + } + }; + + /* and return a function that stems a word for the current locale */ + return function(token) { + // for lunr version 2 + if (typeof token.update === "function") { + return token.update(function(word) { + st.setCurrent(word); + st.stem(); + return st.getCurrent(); + }) + } else { // for lunr version <= 1 + st.setCurrent(token); + st.stem(); + return st.getCurrent(); + } + } + })(); + + lunr.Pipeline.registerFunction(lunr.it.stemmer, 'stemmer-it'); + + lunr.it.stopWordFilter = lunr.generateStopWordFilter('a abbia abbiamo abbiano abbiate ad agl agli ai al all alla alle allo anche avemmo avendo avesse avessero avessi avessimo aveste avesti avete aveva avevamo avevano avevate avevi avevo avrai avranno avrebbe avrebbero avrei avremmo avremo avreste avresti avrete avrà avrò avuta avute avuti avuto c che chi ci coi col come con contro cui da dagl dagli dai dal dall dalla dalle dallo degl degli dei del dell della delle dello di dov dove e ebbe ebbero ebbi ed era erano eravamo eravate eri ero essendo faccia facciamo facciano facciate faccio facemmo facendo facesse facessero facessi facessimo faceste facesti faceva facevamo facevano facevate facevi facevo fai fanno farai faranno farebbe farebbero farei faremmo faremo fareste faresti farete farà farò fece fecero feci fosse fossero fossi fossimo foste fosti fu fui fummo furono gli ha hai hanno ho i il in io l la le lei li lo loro lui ma mi mia mie miei mio ne negl negli nei nel nell nella nelle nello noi non nostra nostre nostri nostro o per perché più quale quanta quante quanti quanto quella quelle quelli quello questa queste questi questo sarai saranno sarebbe sarebbero sarei saremmo saremo sareste saresti sarete sarà sarò se sei si sia siamo siano siate siete sono sta stai stando stanno starai staranno starebbe starebbero starei staremmo staremo stareste staresti starete starà starò stava stavamo stavano stavate stavi stavo stemmo stesse stessero stessi stessimo steste stesti stette stettero stetti stia stiamo stiano stiate sto su sua sue sugl sugli sui sul sull sulla sulle sullo suo suoi ti tra tu tua tue tuo tuoi tutti tutto un una uno vi voi vostra vostre vostri vostro è'.split(' ')); + + lunr.Pipeline.registerFunction(lunr.it.stopWordFilter, 'stopWordFilter-it'); + }; +})) \ No newline at end of file diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.ja.js b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.ja.js new file mode 100644 index 0000000000000000000000000000000000000000..44eb411ef5cdcc3c52e1c347384e937210490197 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.ja.js @@ -0,0 +1,188 @@ +/*! + * Lunr languages, `Japanese` language + * https://github.com/MihaiValentin/lunr-languages + * + * Copyright 2014, Chad Liu + * http://www.mozilla.org/MPL/ + */ +/*! + * based on + * Snowball JavaScript Library v0.3 + * http://code.google.com/p/urim/ + * http://snowball.tartarus.org/ + * + * Copyright 2010, Oleg Mazko + * http://www.mozilla.org/MPL/ + */ + +/** + * export the module via AMD, CommonJS or as a browser global + * Export code from https://github.com/umdjs/umd/blob/master/returnExports.js + */ +; +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(factory) + } else if (typeof exports === 'object') { + /** + * Node. Does not work with strict CommonJS, but + * only CommonJS-like environments that support module.exports, + * like Node. + */ + module.exports = factory() + } else { + // Browser globals (root is window) + factory()(root.lunr); + } +}(this, function() { + /** + * Just return a value to define the module export. + * This example returns an object, but the module + * can return a function as the exported value. + */ + return function(lunr) { + /* throw error if lunr is not yet included */ + if ('undefined' === typeof lunr) { + throw new Error('Lunr is not present. Please include / require Lunr before this script.'); + } + + /* throw error if lunr stemmer support is not yet included */ + if ('undefined' === typeof lunr.stemmerSupport) { + throw new Error('Lunr stemmer support is not present. Please include / require Lunr stemmer support before this script.'); + } + + /* + Japanese tokenization is trickier, since it does not + take into account spaces. + Since the tokenization function is represented different + internally for each of the Lunr versions, this had to be done + in order to try to try to pick the best way of doing this based + on the Lunr version + */ + var isLunr2 = lunr.version[0] == "2"; + + /* register specific locale function */ + lunr.ja = function() { + this.pipeline.reset(); + this.pipeline.add( + lunr.ja.trimmer, + lunr.ja.stopWordFilter, + lunr.ja.stemmer + ); + + // change the tokenizer for japanese one + if (isLunr2) { // for lunr version 2.0.0 + this.tokenizer = lunr.ja.tokenizer; + } else { + if (lunr.tokenizer) { // for lunr version 0.6.0 + lunr.tokenizer = lunr.ja.tokenizer; + } + if (this.tokenizerFn) { // for lunr version 0.7.0 -> 1.0.0 + this.tokenizerFn = lunr.ja.tokenizer; + } + } + }; + var segmenter = new lunr.TinySegmenter(); // インスタンス生成 + + lunr.ja.tokenizer = function(obj) { + var i; + var str; + var len; + var segs; + var tokens; + var char; + var sliceLength; + var sliceStart; + var sliceEnd; + var segStart; + + if (!arguments.length || obj == null || obj == undefined) + return []; + + if (Array.isArray(obj)) { + return obj.map( + function(t) { + return isLunr2 ? new lunr.Token(t.toLowerCase()) : t.toLowerCase(); + } + ); + } + + str = obj.toString().toLowerCase().replace(/^\s+/, ''); + for (i = str.length - 1; i >= 0; i--) { + if (/\S/.test(str.charAt(i))) { + str = str.substring(0, i + 1); + break; + } + } + + tokens = []; + len = str.length; + for (sliceEnd = 0, sliceStart = 0; sliceEnd <= len; sliceEnd++) { + char = str.charAt(sliceEnd); + sliceLength = sliceEnd - sliceStart; + + if ((char.match(/\s/) || sliceEnd == len)) { + if (sliceLength > 0) { + segs = segmenter.segment(str.slice(sliceStart, sliceEnd)).filter( + function(token) { + return !!token; + } + ); + + segStart = sliceStart; + for (i = 0; i < segs.length; i++) { + if (isLunr2) { + tokens.push( + new lunr.Token( + segs[i], { + position: [segStart, segs[i].length], + index: tokens.length + } + ) + ); + } else { + tokens.push(segs[i]); + } + segStart += segs[i].length; + } + } + + sliceStart = sliceEnd + 1; + } + } + + return tokens; + } + + /* lunr stemmer function */ + lunr.ja.stemmer = (function() { + + /* TODO japanese stemmer */ + return function(word) { + return word; + } + })(); + lunr.Pipeline.registerFunction(lunr.ja.stemmer, 'stemmer-ja'); + + /* lunr trimmer function */ + lunr.ja.wordCharacters = "一二三四五六七八九十百千万億兆一-龠々〆ヵヶぁ-んァ-ヴーア-ン゙a-zA-Za-zA-Z0-90-9"; + lunr.ja.trimmer = lunr.trimmerSupport.generateTrimmer(lunr.ja.wordCharacters); + lunr.Pipeline.registerFunction(lunr.ja.trimmer, 'trimmer-ja'); + + /* lunr stop word filter. see http://www.ranks.nl/stopwords/japanese */ + lunr.ja.stopWordFilter = lunr.generateStopWordFilter( + 'これ それ あれ この その あの ここ そこ あそこ こちら どこ だれ なに なん 何 私 貴方 貴方方 我々 私達 あの人 あのかた 彼女 彼 です あります おります います は が の に を で え から まで より も どの と し それで しかし'.split(' ')); + lunr.Pipeline.registerFunction(lunr.ja.stopWordFilter, 'stopWordFilter-ja'); + + // alias ja => jp for backward-compatibility. + // jp is the country code, while ja is the language code + // a new lunr.ja.js has been created, but in order to + // keep the backward compatibility, we'll leave the lunr.jp.js + // here for a while, and just make it use the new lunr.ja.js + lunr.jp = lunr.ja; + lunr.Pipeline.registerFunction(lunr.jp.stemmer, 'stemmer-jp'); + lunr.Pipeline.registerFunction(lunr.jp.trimmer, 'trimmer-jp'); + lunr.Pipeline.registerFunction(lunr.jp.stopWordFilter, 'stopWordFilter-jp'); + }; +})) \ No newline at end of file diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.jp.js b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.jp.js new file mode 100644 index 0000000000000000000000000000000000000000..73ebff1d6e729695714cbd6f5111dd8226c9f3b2 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.jp.js @@ -0,0 +1,5 @@ +// jp is the country code, while ja is the language code +// a new lunr.ja.js has been created, but in order to +// keep the backward compatibility, we'll leave the lunr.jp.js +// here for a while, and just make it use the new lunr.ja.js +module.exports = require('./lunr.ja'); \ No newline at end of file diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.kn.js b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.kn.js new file mode 100644 index 0000000000000000000000000000000000000000..8b861c879857beda3c03222a15635c1ba5056428 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.kn.js @@ -0,0 +1,110 @@ +/*! + * Lunr languages, `Kannada` language + * https://github.com/MiKr13/lunr-languages + * + * Copyright 2023, India + * http://www.mozilla.org/MPL/ + */ +/*! + * based on + * Snowball JavaScript Library v0.3 + * http://code.google.com/p/urim/ + * http://snowball.tartarus.org/ + * + * Copyright 2010, Oleg Mazko + * http://www.mozilla.org/MPL/ + */ + +/** + * export the module via AMD, CommonJS or as a browser global + * Export code from https://github.com/umdjs/umd/blob/master/returnExports.js + */ +; +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(factory) + } else if (typeof exports === 'object') { + /** + * Node. Does not work with strict CommonJS, but + * only CommonJS-like environments that support module.exports, + * like Node. + */ + module.exports = factory() + } else { + // Browser globals (root is window) + factory()(root.lunr); + } +}(this, function() { + /** + * Just return a value to define the module export. + * This example returns an object, but the module + * can return a function as the exported value. + */ + return function(lunr) { + /* throw error if lunr is not yet included */ + if ('undefined' === typeof lunr) { + throw new Error('Lunr is not present. Please include / require Lunr before this script.'); + } + + /* throw error if lunr stemmer support is not yet included */ + if ('undefined' === typeof lunr.stemmerSupport) { + throw new Error('Lunr stemmer support is not present. Please include / require Lunr stemmer support before this script.'); + } + + /* register specific locale function */ + lunr.kn = function() { + this.pipeline.reset(); + this.pipeline.add( + lunr.kn.trimmer, + lunr.kn.stopWordFilter, + lunr.kn.stemmer + ); + + if (this.searchPipeline) { + this.searchPipeline.reset(); + this.searchPipeline.add(lunr.kn.stemmer) + } + }; + + /* lunr trimmer function */ + lunr.kn.wordCharacters = "\u0C80-\u0C84\u0C85-\u0C94\u0C95-\u0CB9\u0CBE-\u0CCC\u0CBC-\u0CBD\u0CD5-\u0CD6\u0CDD-\u0CDE\u0CE0-\u0CE1\u0CE2-\u0CE3\u0CE4\u0CE5\u0CE6-\u0CEF\u0CF1-\u0CF3"; + lunr.kn.trimmer = lunr.trimmerSupport.generateTrimmer(lunr.kn.wordCharacters); + + lunr.Pipeline.registerFunction(lunr.kn.trimmer, 'trimmer-kn'); + /* lunr stop word filter */ + lunr.kn.stopWordFilter = lunr.generateStopWordFilter( + 'ಮತ್ತು ಈ ಒಂದು ರಲ್ಲಿ ಹಾಗೂ ಎಂದು ಅಥವಾ ಇದು ರ ಅವರು ಎಂಬ ಮೇಲೆ ಅವರ ತನ್ನ ಆದರೆ ತಮ್ಮ ನಂತರ ಮೂಲಕ ಹೆಚ್ಚು ನ ಆ ಕೆಲವು ಅನೇಕ ಎರಡು ಹಾಗು ಪ್ರಮುಖ ಇದನ್ನು ಇದರ ಸುಮಾರು ಅದರ ಅದು ಮೊದಲ ಬಗ್ಗೆ ನಲ್ಲಿ ರಂದು ಇತರ ಅತ್ಯಂತ ಹೆಚ್ಚಿನ ಸಹ ಸಾಮಾನ್ಯವಾಗಿ ನೇ ಹಲವಾರು ಹೊಸ ದಿ ಕಡಿಮೆ ಯಾವುದೇ ಹೊಂದಿದೆ ದೊಡ್ಡ ಅನ್ನು ಇವರು ಪ್ರಕಾರ ಇದೆ ಮಾತ್ರ ಕೂಡ ಇಲ್ಲಿ ಎಲ್ಲಾ ವಿವಿಧ ಅದನ್ನು ಹಲವು ರಿಂದ ಕೇವಲ ದ ದಕ್ಷಿಣ ಗೆ ಅವನ ಅತಿ ನೆಯ ಬಹಳ ಕೆಲಸ ಎಲ್ಲ ಪ್ರತಿ ಇತ್ಯಾದಿ ಇವು ಬೇರೆ ಹೀಗೆ ನಡುವೆ ಇದಕ್ಕೆ ಎಸ್ ಇವರ ಮೊದಲು ಶ್ರೀ ಮಾಡುವ ಇದರಲ್ಲಿ ರೀತಿಯ ಮಾಡಿದ ಕಾಲ ಅಲ್ಲಿ ಮಾಡಲು ಅದೇ ಈಗ ಅವು ಗಳು ಎ ಎಂಬುದು ಅವನು ಅಂದರೆ ಅವರಿಗೆ ಇರುವ ವಿಶೇಷ ಮುಂದೆ ಅವುಗಳ ಮುಂತಾದ ಮೂಲ ಬಿ ಮೀ ಒಂದೇ ಇನ್ನೂ ಹೆಚ್ಚಾಗಿ ಮಾಡಿ ಅವರನ್ನು ಇದೇ ಯ ರೀತಿಯಲ್ಲಿ ಜೊತೆ ಅದರಲ್ಲಿ ಮಾಡಿದರು ನಡೆದ ಆಗ ಮತ್ತೆ ಪೂರ್ವ ಆತ ಬಂದ ಯಾವ ಒಟ್ಟು ಇತರೆ ಹಿಂದೆ ಪ್ರಮಾಣದ ಗಳನ್ನು ಕುರಿತು ಯು ಆದ್ದರಿಂದ ಅಲ್ಲದೆ ನಗರದ ಮೇಲಿನ ಏಕೆಂದರೆ ರಷ್ಟು ಎಂಬುದನ್ನು ಬಾರಿ ಎಂದರೆ ಹಿಂದಿನ ಆದರೂ ಆದ ಸಂಬಂಧಿಸಿದ ಮತ್ತೊಂದು ಸಿ ಆತನ '.split(' ')); + /* lunr stemmer function */ + lunr.kn.stemmer = (function() { + + return function(word) { + // for lunr version 2 + if (typeof word.update === "function") { + return word.update(function(word) { + return word; + }) + } else { // for lunr version <= 1 + return word; + } + + } + })(); + + var segmenter = lunr.wordcut; + segmenter.init(); + lunr.kn.tokenizer = function(obj) { + if (!arguments.length || obj == null || obj == undefined) return [] + if (Array.isArray(obj)) return obj.map(function(t) { + return isLunr2 ? new lunr.Token(t.toLowerCase()) : t.toLowerCase() + }); + + var str = obj.toString().toLowerCase().replace(/^\s+/, ''); + return segmenter.cut(str).split('|'); + } + + lunr.Pipeline.registerFunction(lunr.kn.stemmer, 'stemmer-kn'); + lunr.Pipeline.registerFunction(lunr.kn.stopWordFilter, 'stopWordFilter-kn'); + + }; +})) \ No newline at end of file diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.ko.js b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.ko.js new file mode 100644 index 0000000000000000000000000000000000000000..508f53e5a787cb891e105e050b07717b2030fa7f --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.ko.js @@ -0,0 +1,114 @@ +/*! + * Lunr languages, `Korean` language + * https://github.com/turbobit/lunr-languages + * + * Copyright 2021, Manikandan Venkatasubban + * http://www.mozilla.org/MPL/ + */ +/*! + * based on + * Snowball JavaScript Library v0.3 + * http://code.google.com/p/urim/ + * http://snowball.tartarus.org/ + * + * Copyright 2010, Oleg Mazko + * http://www.mozilla.org/MPL/ + */ + +/** + * export the module via AMD, CommonJS or as a browser global + * Export code from https://github.com/umdjs/umd/blob/master/returnExports.js + */ +; +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(factory) + } else if (typeof exports === 'object') { + /** + * Node. Does not work with strict CommonJS, but + * only CommonJS-like environments that support module.exports, + * like Node. + */ + module.exports = factory() + } else { + // Browser globals (root is window) + factory()(root.lunr); + } +}(this, function() { + /** + * Just return a value to define the module export. + * This example returns an object, but the module + * can return a function as the exported value. + */ + return function(lunr) { + /* throw error if lunr is not yet included */ + if ('undefined' === typeof lunr) { + throw new Error('Lunr is not present. Please include / require Lunr before this script.'); + } + + /* throw error if lunr stemmer support is not yet included */ + if ('undefined' === typeof lunr.stemmerSupport) { + throw new Error('Lunr stemmer support is not present. Please include / require Lunr stemmer support before this script.'); + } + + /* register specific locale function */ + lunr.ko = function() { + this.pipeline.reset(); + this.pipeline.add( + lunr.ko.trimmer, + lunr.ko.stopWordFilter + ); + + // change the tokenizer for japanese one + // if (isLunr2) { // for lunr version 2.0.0 + // this.tokenizer = lunr.ko.tokenizer; + // } else { + // if (lunr.tokenizer) { // for lunr version 0.6.0 + // lunr.tokenizer = lunr.ko.tokenizer; + // } + // if (this.tokenizerFn) { // for lunr version 0.7.0 -> 1.0.0 + // this.tokenizerFn = lunr.ko.tokenizer; + // } + // } + /* + if (this.searchPipeline) { + this.searchPipeline.reset(); + this.searchPipeline.add(lunr.ko.stemmer) + } + */ + }; + + /* lunr trimmer function */ + lunr.ko.wordCharacters = "[" + + "A-Za-z" + + "\uac00-\ud7a3" + + "]"; + lunr.ko.trimmer = lunr.trimmerSupport.generateTrimmer(lunr.ko.wordCharacters); + + lunr.Pipeline.registerFunction(lunr.ko.trimmer, 'trimmer-ko'); + + + /* lunr stop word filter */ + //https://www.ranks.nl/stopwords/korean + lunr.ko.stopWordFilter = lunr.generateStopWordFilter('아 휴 아이구 아이쿠 아이고 어 나 우리 저희 따라 의해 을 를 에 의 가 으로 로 에게 뿐이다 의거하여 근거하여 입각하여 기준으로 예하면 예를 들면 예를 들자면 저 소인 소생 저희 지말고 하지마 하지마라 다른 물론 또한 그리고 비길수 없다 해서는 안된다 뿐만 아니라 만이 아니다 만은 아니다 막론하고 관계없이 그치지 않다 그러나 그런데 하지만 든간에 논하지 않다 따지지 않다 설사 비록 더라도 아니면 만 못하다 하는 편이 낫다 불문하고 향하여 향해서 향하다 쪽으로 틈타 이용하여 타다 오르다 제외하고 이 외에 이 밖에 하여야 비로소 한다면 몰라도 외에도 이곳 여기 부터 기점으로 따라서 할 생각이다 하려고하다 이리하여 그리하여 그렇게 함으로써 하지만 일때 할때 앞에서 중에서 보는데서 으로써 로써 까지 해야한다 일것이다 반드시 할줄알다 할수있다 할수있어 임에 틀림없다 한다면 등 등등 제 겨우 단지 다만 할뿐 딩동 댕그 대해서 대하여 대하면 훨씬 얼마나 얼마만큼 얼마큼 남짓 여 얼마간 약간 다소 좀 조금 다수 몇 얼마 지만 하물며 또한 그러나 그렇지만 하지만 이외에도 대해 말하자면 뿐이다 다음에 반대로 반대로 말하자면 이와 반대로 바꾸어서 말하면 바꾸어서 한다면 만약 그렇지않으면 까악 툭 딱 삐걱거리다 보드득 비걱거리다 꽈당 응당 해야한다 에 가서 각 각각 여러분 각종 각자 제각기 하도록하다 와 과 그러므로 그래서 고로 한 까닭에 하기 때문에 거니와 이지만 대하여 관하여 관한 과연 실로 아니나다를가 생각한대로 진짜로 한적이있다 하곤하였다 하 하하 허허 아하 거바 와 오 왜 어째서 무엇때문에 어찌 하겠는가 무슨 어디 어느곳 더군다나 하물며 더욱이는 어느때 언제 야 이봐 어이 여보시오 흐흐 흥 휴 헉헉 헐떡헐떡 영차 여차 어기여차 끙끙 아야 앗 아야 콸콸 졸졸 좍좍 뚝뚝 주룩주룩 솨 우르르 그래도 또 그리고 바꾸어말하면 바꾸어말하자면 혹은 혹시 답다 및 그에 따르는 때가 되어 즉 지든지 설령 가령 하더라도 할지라도 일지라도 지든지 몇 거의 하마터면 인젠 이젠 된바에야 된이상 만큼 어찌됏든 그위에 게다가 점에서 보아 비추어 보아 고려하면 하게될것이다 일것이다 비교적 좀 보다더 비하면 시키다 하게하다 할만하다 의해서 연이서 이어서 잇따라 뒤따라 뒤이어 결국 의지하여 기대여 통하여 자마자 더욱더 불구하고 얼마든지 마음대로 주저하지 않고 곧 즉시 바로 당장 하자마자 밖에 안된다 하면된다 그래 그렇지 요컨대 다시 말하자면 바꿔 말하면 즉 구체적으로 말하자면 시작하여 시초에 이상 허 헉 허걱 바와같이 해도좋다 해도된다 게다가 더구나 하물며 와르르 팍 퍽 펄렁 동안 이래 하고있었다 이었다 에서 로부터 까지 예하면 했어요 해요 함께 같이 더불어 마저 마저도 양자 모두 습니다 가까스로 하려고하다 즈음하여 다른 다른 방면으로 해봐요 습니까 했어요 말할것도 없고 무릎쓰고 개의치않고 하는것만 못하다 하는것이 낫다 매 매번 들 모 어느것 어느 로써 갖고말하자면 어디 어느쪽 어느것 어느해 어느 년도 라 해도 언젠가 어떤것 어느것 저기 저쪽 저것 그때 그럼 그러면 요만한걸 그래 그때 저것만큼 그저 이르기까지 할 줄 안다 할 힘이 있다 너 너희 당신 어찌 설마 차라리 할지언정 할지라도 할망정 할지언정 구토하다 게우다 토하다 메쓰겁다 옆사람 퉤 쳇 의거하여 근거하여 의해 따라 힘입어 그 다음 버금 두번째로 기타 첫번째로 나머지는 그중에서 견지에서 형식으로 쓰여 입장에서 위해서 단지 의해되다 하도록시키다 뿐만아니라 반대로 전후 전자 앞의것 잠시 잠깐 하면서 그렇지만 다음에 그러한즉 그런즉 남들 아무거나 어찌하든지 같다 비슷하다 예컨대 이럴정도로 어떻게 만약 만일 위에서 서술한바와같이 인 듯하다 하지 않는다면 만약에 무엇 무슨 어느 어떤 아래윗 조차 한데 그럼에도 불구하고 여전히 심지어 까지도 조차도 하지 않도록 않기 위하여 때 시각 무렵 시간 동안 어때 어떠한 하여금 네 예 우선 누구 누가 알겠는가 아무도 줄은모른다 줄은 몰랏다 하는 김에 겸사겸사 하는바 그런 까닭에 한 이유는 그러니 그러니까 때문에 그 너희 그들 너희들 타인 것 것들 너 위하여 공동으로 동시에 하기 위하여 어찌하여 무엇때문에 붕붕 윙윙 나 우리 엉엉 휘익 윙윙 오호 아하 어쨋든 만 못하다 하기보다는 차라리 하는 편이 낫다 흐흐 놀라다 상대적으로 말하자면 마치 아니라면 쉿 그렇지 않으면 그렇지 않다면 안 그러면 아니었다면 하든지 아니면 이라면 좋아 알았어 하는것도 그만이다 어쩔수 없다 하나 일 일반적으로 일단 한켠으로는 오자마자 이렇게되면 이와같다면 전부 한마디 한항목 근거로 하기에 아울러 하지 않도록 않기 위해서 이르기까지 이 되다 로 인하여 까닭으로 이유만으로 이로 인하여 그래서 이 때문에 그러므로 그런 까닭에 알 수 있다 결론을 낼 수 있다 으로 인하여 있다 어떤것 관계가 있다 관련이 있다 연관되다 어떤것들 에 대해 이리하여 그리하여 여부 하기보다는 하느니 하면 할수록 운운 이러이러하다 하구나 하도다 다시말하면 다음으로 에 있다 에 달려 있다 우리 우리들 오히려 하기는한데 어떻게 어떻해 어찌됏어 어때 어째서 본대로 자 이 이쪽 여기 이것 이번 이렇게말하자면 이런 이러한 이와 같은 요만큼 요만한 것 얼마 안 되는 것 이만큼 이 정도의 이렇게 많은 것 이와 같다 이때 이렇구나 것과 같이 끼익 삐걱 따위 와 같은 사람들 부류의 사람들 왜냐하면 중의하나 오직 오로지 에 한하다 하기만 하면 도착하다 까지 미치다 도달하다 정도에 이르다 할 지경이다 결과에 이르다 관해서는 여러분 하고 있다 한 후 혼자 자기 자기집 자신 우에 종합한것과같이 총적으로 보면 총적으로 말하면 총적으로 대로 하다 으로서 참 그만이다 할 따름이다 쿵 탕탕 쾅쾅 둥둥 봐 봐라 아이야 아니 와아 응 아이 참나 년 월 일 령 영 일 이 삼 사 오 육 륙 칠 팔 구 이천육 이천칠 이천팔 이천구 하나 둘 셋 넷 다섯 여섯 일곱 여덟 아홉 령 영'.split(' ')); + lunr.Pipeline.registerFunction(lunr.ko.stopWordFilter, 'stopWordFilter-ko'); + + /* lunr stemmer function */ + lunr.ko.stemmer = (function() { + + return function(word) { + // for lunr version 2 + if (typeof word.update === "function") { + return word.update(function(word) { + return word; + }) + } else { // for lunr version <= 1 + return word; + } + + } + })(); + lunr.Pipeline.registerFunction(lunr.ko.stemmer, 'stemmer-ko'); + }; +})) \ No newline at end of file diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.multi.js b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.multi.js new file mode 100644 index 0000000000000000000000000000000000000000..4e921e022fabb85a9b3beb8cf1069a0c3fa52a6e --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.multi.js @@ -0,0 +1,79 @@ +/** + * export the module via AMD, CommonJS or as a browser global + * Export code from https://github.com/umdjs/umd/blob/master/returnExports.js + */ +;(function (root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(factory) + } else if (typeof exports === 'object') { + /** + * Node. Does not work with strict CommonJS, but + * only CommonJS-like environments that support module.exports, + * like Node. + */ + module.exports = factory() + } else { + // Browser globals (root is window) + factory()(root.lunr); + } +}(this, function () { + /** + * Just return a value to define the module export. + * This example returns an object, but the module + * can return a function as the exported value. + */ + return function(lunr) { + /* Set up the pipeline for indexing content in multiple languages. The + corresponding lunr.{lang} files must be loaded before calling this + function; English ('en') is built in. + + Returns: a lunr plugin for use in your indexer. + + Known drawback: every word will be stemmed with stemmers for every + language. This could mean that sometimes words that have the same + stemming root will not be stemmed as such. + */ + lunr.multiLanguage = function(/* lang1, lang2, ... */) { + var languages = Array.prototype.slice.call(arguments); + var nameSuffix = languages.join('-'); + var wordCharacters = ""; + var pipeline = []; + var searchPipeline = []; + for (var i = 0; i < languages.length; ++i) { + if (languages[i] == 'en') { + wordCharacters += '\\w'; + pipeline.unshift(lunr.stopWordFilter); + pipeline.push(lunr.stemmer); + searchPipeline.push(lunr.stemmer); + } else { + wordCharacters += lunr[languages[i]].wordCharacters; + if (lunr[languages[i]].stopWordFilter) { + pipeline.unshift(lunr[languages[i]].stopWordFilter); + } + if (lunr[languages[i]].stemmer) { + pipeline.push(lunr[languages[i]].stemmer); + searchPipeline.push(lunr[languages[i]].stemmer); + } + } + }; + var multiTrimmer = lunr.trimmerSupport.generateTrimmer(wordCharacters); + lunr.Pipeline.registerFunction(multiTrimmer, 'lunr-multi-trimmer-' + nameSuffix); + pipeline.unshift(multiTrimmer); + + return function() { + this.pipeline.reset(); + + this.pipeline.add.apply(this.pipeline, pipeline); + + // for lunr version 2 + // this is necessary so that every searched word is also stemmed before + // in lunr <= 1 this is not needed, as it is done using the normal pipeline + if (this.searchPipeline) { + this.searchPipeline.reset(); + this.searchPipeline.add.apply(this.searchPipeline, searchPipeline); + } + }; + } + } +})); diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.nl.js b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.nl.js new file mode 100644 index 0000000000000000000000000000000000000000..55b43ff0fb546c61434cecca7123bfa02d09e53b --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.nl.js @@ -0,0 +1,448 @@ +/*! + * Lunr languages, `Dutch` language + * https://github.com/MihaiValentin/lunr-languages + * + * Copyright 2014, Mihai Valentin + * http://www.mozilla.org/MPL/ + */ +/*! + * based on + * Snowball JavaScript Library v0.3 + * http://code.google.com/p/urim/ + * http://snowball.tartarus.org/ + * + * Copyright 2010, Oleg Mazko + * http://www.mozilla.org/MPL/ + */ + +/** + * export the module via AMD, CommonJS or as a browser global + * Export code from https://github.com/umdjs/umd/blob/master/returnExports.js + */ +; +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(factory) + } else if (typeof exports === 'object') { + /** + * Node. Does not work with strict CommonJS, but + * only CommonJS-like environments that support module.exports, + * like Node. + */ + module.exports = factory() + } else { + // Browser globals (root is window) + factory()(root.lunr); + } +}(this, function() { + /** + * Just return a value to define the module export. + * This example returns an object, but the module + * can return a function as the exported value. + */ + return function(lunr) { + /* throw error if lunr is not yet included */ + if ('undefined' === typeof lunr) { + throw new Error('Lunr is not present. Please include / require Lunr before this script.'); + } + + /* throw error if lunr stemmer support is not yet included */ + if ('undefined' === typeof lunr.stemmerSupport) { + throw new Error('Lunr stemmer support is not present. Please include / require Lunr stemmer support before this script.'); + } + + /* register specific locale function */ + lunr.nl = function() { + this.pipeline.reset(); + this.pipeline.add( + lunr.nl.trimmer, + lunr.nl.stopWordFilter, + lunr.nl.stemmer + ); + + // for lunr version 2 + // this is necessary so that every searched word is also stemmed before + // in lunr <= 1 this is not needed, as it is done using the normal pipeline + if (this.searchPipeline) { + this.searchPipeline.reset(); + this.searchPipeline.add(lunr.nl.stemmer) + } + }; + + /* lunr trimmer function */ + lunr.nl.wordCharacters = "A-Za-z\xAA\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02B8\u02E0-\u02E4\u1D00-\u1D25\u1D2C-\u1D5C\u1D62-\u1D65\u1D6B-\u1D77\u1D79-\u1DBE\u1E00-\u1EFF\u2071\u207F\u2090-\u209C\u212A\u212B\u2132\u214E\u2160-\u2188\u2C60-\u2C7F\uA722-\uA787\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA7FF\uAB30-\uAB5A\uAB5C-\uAB64\uFB00-\uFB06\uFF21-\uFF3A\uFF41-\uFF5A"; + lunr.nl.trimmer = lunr.trimmerSupport.generateTrimmer(lunr.nl.wordCharacters); + + lunr.Pipeline.registerFunction(lunr.nl.trimmer, 'trimmer-nl'); + + /* lunr stemmer function */ + lunr.nl.stemmer = (function() { + /* create the wrapped stemmer object */ + var Among = lunr.stemmerSupport.Among, + SnowballProgram = lunr.stemmerSupport.SnowballProgram, + st = new function DutchStemmer() { + var a_0 = [new Among("", -1, 6), new Among("\u00E1", 0, 1), + new Among("\u00E4", 0, 1), new Among("\u00E9", 0, 2), + new Among("\u00EB", 0, 2), new Among("\u00ED", 0, 3), + new Among("\u00EF", 0, 3), new Among("\u00F3", 0, 4), + new Among("\u00F6", 0, 4), new Among("\u00FA", 0, 5), + new Among("\u00FC", 0, 5) + ], + a_1 = [new Among("", -1, 3), + new Among("I", 0, 2), new Among("Y", 0, 1) + ], + a_2 = [ + new Among("dd", -1, -1), new Among("kk", -1, -1), + new Among("tt", -1, -1) + ], + a_3 = [new Among("ene", -1, 2), + new Among("se", -1, 3), new Among("en", -1, 2), + new Among("heden", 2, 1), new Among("s", -1, 3) + ], + a_4 = [ + new Among("end", -1, 1), new Among("ig", -1, 2), + new Among("ing", -1, 1), new Among("lijk", -1, 3), + new Among("baar", -1, 4), new Among("bar", -1, 5) + ], + a_5 = [ + new Among("aa", -1, -1), new Among("ee", -1, -1), + new Among("oo", -1, -1), new Among("uu", -1, -1) + ], + g_v = [17, 65, + 16, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128 + ], + g_v_I = [1, 0, 0, + 17, 65, 16, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128 + ], + g_v_j = [ + 17, 67, 16, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128 + ], + I_p2, I_p1, B_e_found, sbp = new SnowballProgram(); + this.setCurrent = function(word) { + sbp.setCurrent(word); + }; + this.getCurrent = function() { + return sbp.getCurrent(); + }; + + function r_prelude() { + var among_var, v_1 = sbp.cursor, + v_2, v_3; + while (true) { + sbp.bra = sbp.cursor; + among_var = sbp.find_among(a_0, 11); + if (among_var) { + sbp.ket = sbp.cursor; + switch (among_var) { + case 1: + sbp.slice_from("a"); + continue; + case 2: + sbp.slice_from("e"); + continue; + case 3: + sbp.slice_from("i"); + continue; + case 4: + sbp.slice_from("o"); + continue; + case 5: + sbp.slice_from("u"); + continue; + case 6: + if (sbp.cursor >= sbp.limit) + break; + sbp.cursor++; + continue; + } + } + break; + } + sbp.cursor = v_1; + sbp.bra = v_1; + if (sbp.eq_s(1, "y")) { + sbp.ket = sbp.cursor; + sbp.slice_from("Y"); + } else + sbp.cursor = v_1; + while (true) { + v_2 = sbp.cursor; + if (sbp.in_grouping(g_v, 97, 232)) { + v_3 = sbp.cursor; + sbp.bra = v_3; + if (sbp.eq_s(1, "i")) { + sbp.ket = sbp.cursor; + if (sbp.in_grouping(g_v, 97, 232)) { + sbp.slice_from("I"); + sbp.cursor = v_2; + } + } else { + sbp.cursor = v_3; + if (sbp.eq_s(1, "y")) { + sbp.ket = sbp.cursor; + sbp.slice_from("Y"); + sbp.cursor = v_2; + } else if (habr1(v_2)) + break; + } + } else if (habr1(v_2)) + break; + } + } + + function habr1(v_1) { + sbp.cursor = v_1; + if (v_1 >= sbp.limit) + return true; + sbp.cursor++; + return false; + } + + function r_mark_regions() { + I_p1 = sbp.limit; + I_p2 = I_p1; + if (!habr2()) { + I_p1 = sbp.cursor; + if (I_p1 < 3) + I_p1 = 3; + if (!habr2()) + I_p2 = sbp.cursor; + } + } + + function habr2() { + while (!sbp.in_grouping(g_v, 97, 232)) { + if (sbp.cursor >= sbp.limit) + return true; + sbp.cursor++; + } + while (!sbp.out_grouping(g_v, 97, 232)) { + if (sbp.cursor >= sbp.limit) + return true; + sbp.cursor++; + } + return false; + } + + function r_postlude() { + var among_var; + while (true) { + sbp.bra = sbp.cursor; + among_var = sbp.find_among(a_1, 3); + if (among_var) { + sbp.ket = sbp.cursor; + switch (among_var) { + case 1: + sbp.slice_from("y"); + break; + case 2: + sbp.slice_from("i"); + break; + case 3: + if (sbp.cursor >= sbp.limit) + return; + sbp.cursor++; + break; + } + } + } + } + + function r_R1() { + return I_p1 <= sbp.cursor; + } + + function r_R2() { + return I_p2 <= sbp.cursor; + } + + function r_undouble() { + var v_1 = sbp.limit - sbp.cursor; + if (sbp.find_among_b(a_2, 3)) { + sbp.cursor = sbp.limit - v_1; + sbp.ket = sbp.cursor; + if (sbp.cursor > sbp.limit_backward) { + sbp.cursor--; + sbp.bra = sbp.cursor; + sbp.slice_del(); + } + } + } + + function r_e_ending() { + var v_1; + B_e_found = false; + sbp.ket = sbp.cursor; + if (sbp.eq_s_b(1, "e")) { + sbp.bra = sbp.cursor; + if (r_R1()) { + v_1 = sbp.limit - sbp.cursor; + if (sbp.out_grouping_b(g_v, 97, 232)) { + sbp.cursor = sbp.limit - v_1; + sbp.slice_del(); + B_e_found = true; + r_undouble(); + } + } + } + } + + function r_en_ending() { + var v_1; + if (r_R1()) { + v_1 = sbp.limit - sbp.cursor; + if (sbp.out_grouping_b(g_v, 97, 232)) { + sbp.cursor = sbp.limit - v_1; + if (!sbp.eq_s_b(3, "gem")) { + sbp.cursor = sbp.limit - v_1; + sbp.slice_del(); + r_undouble(); + } + } + } + } + + function r_standard_suffix() { + var among_var, v_1 = sbp.limit - sbp.cursor, + v_2, v_3, v_4, v_5, v_6; + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_3, 5); + if (among_var) { + sbp.bra = sbp.cursor; + switch (among_var) { + case 1: + if (r_R1()) + sbp.slice_from("heid"); + break; + case 2: + r_en_ending(); + break; + case 3: + if (r_R1() && sbp.out_grouping_b(g_v_j, 97, 232)) + sbp.slice_del(); + break; + } + } + sbp.cursor = sbp.limit - v_1; + r_e_ending(); + sbp.cursor = sbp.limit - v_1; + sbp.ket = sbp.cursor; + if (sbp.eq_s_b(4, "heid")) { + sbp.bra = sbp.cursor; + if (r_R2()) { + v_2 = sbp.limit - sbp.cursor; + if (!sbp.eq_s_b(1, "c")) { + sbp.cursor = sbp.limit - v_2; + sbp.slice_del(); + sbp.ket = sbp.cursor; + if (sbp.eq_s_b(2, "en")) { + sbp.bra = sbp.cursor; + r_en_ending(); + } + } + } + } + sbp.cursor = sbp.limit - v_1; + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_4, 6); + if (among_var) { + sbp.bra = sbp.cursor; + switch (among_var) { + case 1: + if (r_R2()) { + sbp.slice_del(); + v_3 = sbp.limit - sbp.cursor; + sbp.ket = sbp.cursor; + if (sbp.eq_s_b(2, "ig")) { + sbp.bra = sbp.cursor; + if (r_R2()) { + v_4 = sbp.limit - sbp.cursor; + if (!sbp.eq_s_b(1, "e")) { + sbp.cursor = sbp.limit - v_4; + sbp.slice_del(); + break; + } + } + } + sbp.cursor = sbp.limit - v_3; + r_undouble(); + } + break; + case 2: + if (r_R2()) { + v_5 = sbp.limit - sbp.cursor; + if (!sbp.eq_s_b(1, "e")) { + sbp.cursor = sbp.limit - v_5; + sbp.slice_del(); + } + } + break; + case 3: + if (r_R2()) { + sbp.slice_del(); + r_e_ending(); + } + break; + case 4: + if (r_R2()) + sbp.slice_del(); + break; + case 5: + if (r_R2() && B_e_found) + sbp.slice_del(); + break; + } + } + sbp.cursor = sbp.limit - v_1; + if (sbp.out_grouping_b(g_v_I, 73, 232)) { + v_6 = sbp.limit - sbp.cursor; + if (sbp.find_among_b(a_5, 4) && sbp.out_grouping_b(g_v, 97, 232)) { + sbp.cursor = sbp.limit - v_6; + sbp.ket = sbp.cursor; + if (sbp.cursor > sbp.limit_backward) { + sbp.cursor--; + sbp.bra = sbp.cursor; + sbp.slice_del(); + } + } + } + } + this.stem = function() { + var v_1 = sbp.cursor; + r_prelude(); + sbp.cursor = v_1; + r_mark_regions(); + sbp.limit_backward = v_1; + sbp.cursor = sbp.limit; + r_standard_suffix(); + sbp.cursor = sbp.limit_backward; + r_postlude(); + return true; + } + }; + + /* and return a function that stems a word for the current locale */ + return function(token) { + // for lunr version 2 + if (typeof token.update === "function") { + return token.update(function(word) { + st.setCurrent(word); + st.stem(); + return st.getCurrent(); + }) + } else { // for lunr version <= 1 + st.setCurrent(token); + st.stem(); + return st.getCurrent(); + } + } + })(); + + lunr.Pipeline.registerFunction(lunr.nl.stemmer, 'stemmer-nl'); + + lunr.nl.stopWordFilter = lunr.generateStopWordFilter(' aan al alles als altijd andere ben bij daar dan dat de der deze die dit doch doen door dus een eens en er ge geen geweest haar had heb hebben heeft hem het hier hij hoe hun iemand iets ik in is ja je kan kon kunnen maar me meer men met mij mijn moet na naar niet niets nog nu of om omdat onder ons ook op over reeds te tegen toch toen tot u uit uw van veel voor want waren was wat werd wezen wie wil worden wordt zal ze zelf zich zij zijn zo zonder zou'.split(' ')); + + lunr.Pipeline.registerFunction(lunr.nl.stopWordFilter, 'stopWordFilter-nl'); + }; +})) \ No newline at end of file diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.no.js b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.no.js new file mode 100644 index 0000000000000000000000000000000000000000..34f8ab1aae6c2f3035a9f4a10f3a8d8116ab8dc0 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.no.js @@ -0,0 +1,258 @@ +/*! + * Lunr languages, `Norwegian` language + * https://github.com/MihaiValentin/lunr-languages + * + * Copyright 2014, Mihai Valentin + * http://www.mozilla.org/MPL/ + */ +/*! + * based on + * Snowball JavaScript Library v0.3 + * http://code.google.com/p/urim/ + * http://snowball.tartarus.org/ + * + * Copyright 2010, Oleg Mazko + * http://www.mozilla.org/MPL/ + */ + +/** + * export the module via AMD, CommonJS or as a browser global + * Export code from https://github.com/umdjs/umd/blob/master/returnExports.js + */ +; +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(factory) + } else if (typeof exports === 'object') { + /** + * Node. Does not work with strict CommonJS, but + * only CommonJS-like environments that support module.exports, + * like Node. + */ + module.exports = factory() + } else { + // Browser globals (root is window) + factory()(root.lunr); + } +}(this, function() { + /** + * Just return a value to define the module export. + * This example returns an object, but the module + * can return a function as the exported value. + */ + return function(lunr) { + /* throw error if lunr is not yet included */ + if ('undefined' === typeof lunr) { + throw new Error('Lunr is not present. Please include / require Lunr before this script.'); + } + + /* throw error if lunr stemmer support is not yet included */ + if ('undefined' === typeof lunr.stemmerSupport) { + throw new Error('Lunr stemmer support is not present. Please include / require Lunr stemmer support before this script.'); + } + + /* register specific locale function */ + lunr.no = function() { + this.pipeline.reset(); + this.pipeline.add( + lunr.no.trimmer, + lunr.no.stopWordFilter, + lunr.no.stemmer + ); + + // for lunr version 2 + // this is necessary so that every searched word is also stemmed before + // in lunr <= 1 this is not needed, as it is done using the normal pipeline + if (this.searchPipeline) { + this.searchPipeline.reset(); + this.searchPipeline.add(lunr.no.stemmer) + } + }; + + /* lunr trimmer function */ + lunr.no.wordCharacters = "A-Za-z\xAA\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02B8\u02E0-\u02E4\u1D00-\u1D25\u1D2C-\u1D5C\u1D62-\u1D65\u1D6B-\u1D77\u1D79-\u1DBE\u1E00-\u1EFF\u2071\u207F\u2090-\u209C\u212A\u212B\u2132\u214E\u2160-\u2188\u2C60-\u2C7F\uA722-\uA787\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA7FF\uAB30-\uAB5A\uAB5C-\uAB64\uFB00-\uFB06\uFF21-\uFF3A\uFF41-\uFF5A"; + lunr.no.trimmer = lunr.trimmerSupport.generateTrimmer(lunr.no.wordCharacters); + + lunr.Pipeline.registerFunction(lunr.no.trimmer, 'trimmer-no'); + + /* lunr stemmer function */ + lunr.no.stemmer = (function() { + /* create the wrapped stemmer object */ + var Among = lunr.stemmerSupport.Among, + SnowballProgram = lunr.stemmerSupport.SnowballProgram, + st = new function NorwegianStemmer() { + var a_0 = [new Among("a", -1, 1), new Among("e", -1, 1), + new Among("ede", 1, 1), new Among("ande", 1, 1), + new Among("ende", 1, 1), new Among("ane", 1, 1), + new Among("ene", 1, 1), new Among("hetene", 6, 1), + new Among("erte", 1, 3), new Among("en", -1, 1), + new Among("heten", 9, 1), new Among("ar", -1, 1), + new Among("er", -1, 1), new Among("heter", 12, 1), + new Among("s", -1, 2), new Among("as", 14, 1), + new Among("es", 14, 1), new Among("edes", 16, 1), + new Among("endes", 16, 1), new Among("enes", 16, 1), + new Among("hetenes", 19, 1), new Among("ens", 14, 1), + new Among("hetens", 21, 1), new Among("ers", 14, 1), + new Among("ets", 14, 1), new Among("et", -1, 1), + new Among("het", 25, 1), new Among("ert", -1, 3), + new Among("ast", -1, 1) + ], + a_1 = [new Among("dt", -1, -1), + new Among("vt", -1, -1) + ], + a_2 = [new Among("leg", -1, 1), + new Among("eleg", 0, 1), new Among("ig", -1, 1), + new Among("eig", 2, 1), new Among("lig", 2, 1), + new Among("elig", 4, 1), new Among("els", -1, 1), + new Among("lov", -1, 1), new Among("elov", 7, 1), + new Among("slov", 7, 1), new Among("hetslov", 9, 1) + ], + g_v = [17, + 65, 16, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 48, 0, 128 + ], + g_s_ending = [ + 119, 125, 149, 1 + ], + I_x, I_p1, sbp = new SnowballProgram(); + this.setCurrent = function(word) { + sbp.setCurrent(word); + }; + this.getCurrent = function() { + return sbp.getCurrent(); + }; + + function r_mark_regions() { + var v_1, c = sbp.cursor + 3; + I_p1 = sbp.limit; + if (0 <= c || c <= sbp.limit) { + I_x = c; + while (true) { + v_1 = sbp.cursor; + if (sbp.in_grouping(g_v, 97, 248)) { + sbp.cursor = v_1; + break; + } + if (v_1 >= sbp.limit) + return; + sbp.cursor = v_1 + 1; + } + while (!sbp.out_grouping(g_v, 97, 248)) { + if (sbp.cursor >= sbp.limit) + return; + sbp.cursor++; + } + I_p1 = sbp.cursor; + if (I_p1 < I_x) + I_p1 = I_x; + } + } + + function r_main_suffix() { + var among_var, v_1, v_2; + if (sbp.cursor >= I_p1) { + v_1 = sbp.limit_backward; + sbp.limit_backward = I_p1; + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_0, 29); + sbp.limit_backward = v_1; + if (among_var) { + sbp.bra = sbp.cursor; + switch (among_var) { + case 1: + sbp.slice_del(); + break; + case 2: + v_2 = sbp.limit - sbp.cursor; + if (sbp.in_grouping_b(g_s_ending, 98, 122)) + sbp.slice_del(); + else { + sbp.cursor = sbp.limit - v_2; + if (sbp.eq_s_b(1, "k") && + sbp.out_grouping_b(g_v, 97, 248)) + sbp.slice_del(); + } + break; + case 3: + sbp.slice_from("er"); + break; + } + } + } + } + + function r_consonant_pair() { + var v_1 = sbp.limit - sbp.cursor, + v_2; + if (sbp.cursor >= I_p1) { + v_2 = sbp.limit_backward; + sbp.limit_backward = I_p1; + sbp.ket = sbp.cursor; + if (sbp.find_among_b(a_1, 2)) { + sbp.bra = sbp.cursor; + sbp.limit_backward = v_2; + sbp.cursor = sbp.limit - v_1; + if (sbp.cursor > sbp.limit_backward) { + sbp.cursor--; + sbp.bra = sbp.cursor; + sbp.slice_del(); + } + } else + sbp.limit_backward = v_2; + } + } + + function r_other_suffix() { + var among_var, v_1; + if (sbp.cursor >= I_p1) { + v_1 = sbp.limit_backward; + sbp.limit_backward = I_p1; + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_2, 11); + if (among_var) { + sbp.bra = sbp.cursor; + sbp.limit_backward = v_1; + if (among_var == 1) + sbp.slice_del(); + } else + sbp.limit_backward = v_1; + } + } + this.stem = function() { + var v_1 = sbp.cursor; + r_mark_regions(); + sbp.limit_backward = v_1; + sbp.cursor = sbp.limit; + r_main_suffix(); + sbp.cursor = sbp.limit; + r_consonant_pair(); + sbp.cursor = sbp.limit; + r_other_suffix(); + return true; + } + }; + + /* and return a function that stems a word for the current locale */ + return function(token) { + // for lunr version 2 + if (typeof token.update === "function") { + return token.update(function(word) { + st.setCurrent(word); + st.stem(); + return st.getCurrent(); + }) + } else { // for lunr version <= 1 + st.setCurrent(token); + st.stem(); + return st.getCurrent(); + } + } + })(); + + lunr.Pipeline.registerFunction(lunr.no.stemmer, 'stemmer-no'); + + lunr.no.stopWordFilter = lunr.generateStopWordFilter('alle at av bare begge ble blei bli blir blitt både båe da de deg dei deim deira deires dem den denne der dere deres det dette di din disse ditt du dykk dykkar då eg ein eit eitt eller elles en enn er et ett etter for fordi fra før ha hadde han hans har hennar henne hennes her hjå ho hoe honom hoss hossen hun hva hvem hver hvilke hvilken hvis hvor hvordan hvorfor i ikke ikkje ikkje ingen ingi inkje inn inni ja jeg kan kom korleis korso kun kunne kva kvar kvarhelst kven kvi kvifor man mange me med medan meg meget mellom men mi min mine mitt mot mykje ned no noe noen noka noko nokon nokor nokre nå når og også om opp oss over på samme seg selv si si sia sidan siden sin sine sitt sjøl skal skulle slik so som som somme somt så sånn til um upp ut uten var vart varte ved vere verte vi vil ville vore vors vort vår være være vært å'.split(' ')); + + lunr.Pipeline.registerFunction(lunr.no.stopWordFilter, 'stopWordFilter-no'); + }; +})) \ No newline at end of file diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.pt.js b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.pt.js new file mode 100644 index 0000000000000000000000000000000000000000..8834b907f16a8689ef654ab9ac9f2f4264440b82 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.pt.js @@ -0,0 +1,570 @@ +/*! + * Lunr languages, `Portuguese` language + * https://github.com/MihaiValentin/lunr-languages + * + * Copyright 2014, Mihai Valentin + * http://www.mozilla.org/MPL/ + */ +/*! + * based on + * Snowball JavaScript Library v0.3 + * http://code.google.com/p/urim/ + * http://snowball.tartarus.org/ + * + * Copyright 2010, Oleg Mazko + * http://www.mozilla.org/MPL/ + */ + +/** + * export the module via AMD, CommonJS or as a browser global + * Export code from https://github.com/umdjs/umd/blob/master/returnExports.js + */ +; +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(factory) + } else if (typeof exports === 'object') { + /** + * Node. Does not work with strict CommonJS, but + * only CommonJS-like environments that support module.exports, + * like Node. + */ + module.exports = factory() + } else { + // Browser globals (root is window) + factory()(root.lunr); + } +}(this, function() { + /** + * Just return a value to define the module export. + * This example returns an object, but the module + * can return a function as the exported value. + */ + return function(lunr) { + /* throw error if lunr is not yet included */ + if ('undefined' === typeof lunr) { + throw new Error('Lunr is not present. Please include / require Lunr before this script.'); + } + + /* throw error if lunr stemmer support is not yet included */ + if ('undefined' === typeof lunr.stemmerSupport) { + throw new Error('Lunr stemmer support is not present. Please include / require Lunr stemmer support before this script.'); + } + + /* register specific locale function */ + lunr.pt = function() { + this.pipeline.reset(); + this.pipeline.add( + lunr.pt.trimmer, + lunr.pt.stopWordFilter, + lunr.pt.stemmer + ); + + // for lunr version 2 + // this is necessary so that every searched word is also stemmed before + // in lunr <= 1 this is not needed, as it is done using the normal pipeline + if (this.searchPipeline) { + this.searchPipeline.reset(); + this.searchPipeline.add(lunr.pt.stemmer) + } + }; + + /* lunr trimmer function */ + lunr.pt.wordCharacters = "A-Za-z\xAA\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02B8\u02E0-\u02E4\u1D00-\u1D25\u1D2C-\u1D5C\u1D62-\u1D65\u1D6B-\u1D77\u1D79-\u1DBE\u1E00-\u1EFF\u2071\u207F\u2090-\u209C\u212A\u212B\u2132\u214E\u2160-\u2188\u2C60-\u2C7F\uA722-\uA787\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA7FF\uAB30-\uAB5A\uAB5C-\uAB64\uFB00-\uFB06\uFF21-\uFF3A\uFF41-\uFF5A"; + lunr.pt.trimmer = lunr.trimmerSupport.generateTrimmer(lunr.pt.wordCharacters); + + lunr.Pipeline.registerFunction(lunr.pt.trimmer, 'trimmer-pt'); + + /* lunr stemmer function */ + lunr.pt.stemmer = (function() { + /* create the wrapped stemmer object */ + var Among = lunr.stemmerSupport.Among, + SnowballProgram = lunr.stemmerSupport.SnowballProgram, + st = new function PortugueseStemmer() { + var a_0 = [new Among("", -1, 3), new Among("\u00E3", 0, 1), + new Among("\u00F5", 0, 2) + ], + a_1 = [new Among("", -1, 3), + new Among("a~", 0, 1), new Among("o~", 0, 2) + ], + a_2 = [ + new Among("ic", -1, -1), new Among("ad", -1, -1), + new Among("os", -1, -1), new Among("iv", -1, 1) + ], + a_3 = [ + new Among("ante", -1, 1), new Among("avel", -1, 1), + new Among("\u00EDvel", -1, 1) + ], + a_4 = [new Among("ic", -1, 1), + new Among("abil", -1, 1), new Among("iv", -1, 1) + ], + a_5 = [ + new Among("ica", -1, 1), new Among("\u00E2ncia", -1, 1), + new Among("\u00EAncia", -1, 4), new Among("ira", -1, 9), + new Among("adora", -1, 1), new Among("osa", -1, 1), + new Among("ista", -1, 1), new Among("iva", -1, 8), + new Among("eza", -1, 1), new Among("log\u00EDa", -1, 2), + new Among("idade", -1, 7), new Among("ante", -1, 1), + new Among("mente", -1, 6), new Among("amente", 12, 5), + new Among("\u00E1vel", -1, 1), new Among("\u00EDvel", -1, 1), + new Among("uci\u00F3n", -1, 3), new Among("ico", -1, 1), + new Among("ismo", -1, 1), new Among("oso", -1, 1), + new Among("amento", -1, 1), new Among("imento", -1, 1), + new Among("ivo", -1, 8), new Among("a\u00E7a~o", -1, 1), + new Among("ador", -1, 1), new Among("icas", -1, 1), + new Among("\u00EAncias", -1, 4), new Among("iras", -1, 9), + new Among("adoras", -1, 1), new Among("osas", -1, 1), + new Among("istas", -1, 1), new Among("ivas", -1, 8), + new Among("ezas", -1, 1), new Among("log\u00EDas", -1, 2), + new Among("idades", -1, 7), new Among("uciones", -1, 3), + new Among("adores", -1, 1), new Among("antes", -1, 1), + new Among("a\u00E7o~es", -1, 1), new Among("icos", -1, 1), + new Among("ismos", -1, 1), new Among("osos", -1, 1), + new Among("amentos", -1, 1), new Among("imentos", -1, 1), + new Among("ivos", -1, 8) + ], + a_6 = [new Among("ada", -1, 1), + new Among("ida", -1, 1), new Among("ia", -1, 1), + new Among("aria", 2, 1), new Among("eria", 2, 1), + new Among("iria", 2, 1), new Among("ara", -1, 1), + new Among("era", -1, 1), new Among("ira", -1, 1), + new Among("ava", -1, 1), new Among("asse", -1, 1), + new Among("esse", -1, 1), new Among("isse", -1, 1), + new Among("aste", -1, 1), new Among("este", -1, 1), + new Among("iste", -1, 1), new Among("ei", -1, 1), + new Among("arei", 16, 1), new Among("erei", 16, 1), + new Among("irei", 16, 1), new Among("am", -1, 1), + new Among("iam", 20, 1), new Among("ariam", 21, 1), + new Among("eriam", 21, 1), new Among("iriam", 21, 1), + new Among("aram", 20, 1), new Among("eram", 20, 1), + new Among("iram", 20, 1), new Among("avam", 20, 1), + new Among("em", -1, 1), new Among("arem", 29, 1), + new Among("erem", 29, 1), new Among("irem", 29, 1), + new Among("assem", 29, 1), new Among("essem", 29, 1), + new Among("issem", 29, 1), new Among("ado", -1, 1), + new Among("ido", -1, 1), new Among("ando", -1, 1), + new Among("endo", -1, 1), new Among("indo", -1, 1), + new Among("ara~o", -1, 1), new Among("era~o", -1, 1), + new Among("ira~o", -1, 1), new Among("ar", -1, 1), + new Among("er", -1, 1), new Among("ir", -1, 1), + new Among("as", -1, 1), new Among("adas", 47, 1), + new Among("idas", 47, 1), new Among("ias", 47, 1), + new Among("arias", 50, 1), new Among("erias", 50, 1), + new Among("irias", 50, 1), new Among("aras", 47, 1), + new Among("eras", 47, 1), new Among("iras", 47, 1), + new Among("avas", 47, 1), new Among("es", -1, 1), + new Among("ardes", 58, 1), new Among("erdes", 58, 1), + new Among("irdes", 58, 1), new Among("ares", 58, 1), + new Among("eres", 58, 1), new Among("ires", 58, 1), + new Among("asses", 58, 1), new Among("esses", 58, 1), + new Among("isses", 58, 1), new Among("astes", 58, 1), + new Among("estes", 58, 1), new Among("istes", 58, 1), + new Among("is", -1, 1), new Among("ais", 71, 1), + new Among("eis", 71, 1), new Among("areis", 73, 1), + new Among("ereis", 73, 1), new Among("ireis", 73, 1), + new Among("\u00E1reis", 73, 1), new Among("\u00E9reis", 73, 1), + new Among("\u00EDreis", 73, 1), new Among("\u00E1sseis", 73, 1), + new Among("\u00E9sseis", 73, 1), new Among("\u00EDsseis", 73, 1), + new Among("\u00E1veis", 73, 1), new Among("\u00EDeis", 73, 1), + new Among("ar\u00EDeis", 84, 1), new Among("er\u00EDeis", 84, 1), + new Among("ir\u00EDeis", 84, 1), new Among("ados", -1, 1), + new Among("idos", -1, 1), new Among("amos", -1, 1), + new Among("\u00E1ramos", 90, 1), new Among("\u00E9ramos", 90, 1), + new Among("\u00EDramos", 90, 1), new Among("\u00E1vamos", 90, 1), + new Among("\u00EDamos", 90, 1), new Among("ar\u00EDamos", 95, 1), + new Among("er\u00EDamos", 95, 1), new Among("ir\u00EDamos", 95, 1), + new Among("emos", -1, 1), new Among("aremos", 99, 1), + new Among("eremos", 99, 1), new Among("iremos", 99, 1), + new Among("\u00E1ssemos", 99, 1), new Among("\u00EAssemos", 99, 1), + new Among("\u00EDssemos", 99, 1), new Among("imos", -1, 1), + new Among("armos", -1, 1), new Among("ermos", -1, 1), + new Among("irmos", -1, 1), new Among("\u00E1mos", -1, 1), + new Among("ar\u00E1s", -1, 1), new Among("er\u00E1s", -1, 1), + new Among("ir\u00E1s", -1, 1), new Among("eu", -1, 1), + new Among("iu", -1, 1), new Among("ou", -1, 1), + new Among("ar\u00E1", -1, 1), new Among("er\u00E1", -1, 1), + new Among("ir\u00E1", -1, 1) + ], + a_7 = [new Among("a", -1, 1), + new Among("i", -1, 1), new Among("o", -1, 1), + new Among("os", -1, 1), new Among("\u00E1", -1, 1), + new Among("\u00ED", -1, 1), new Among("\u00F3", -1, 1) + ], + a_8 = [ + new Among("e", -1, 1), new Among("\u00E7", -1, 2), + new Among("\u00E9", -1, 1), new Among("\u00EA", -1, 1) + ], + g_v = [17, + 65, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 19, 12, 2 + ], + I_p2, I_p1, I_pV, sbp = new SnowballProgram(); + this.setCurrent = function(word) { + sbp.setCurrent(word); + }; + this.getCurrent = function() { + return sbp.getCurrent(); + }; + + function r_prelude() { + var among_var; + while (true) { + sbp.bra = sbp.cursor; + among_var = sbp.find_among(a_0, 3); + if (among_var) { + sbp.ket = sbp.cursor; + switch (among_var) { + case 1: + sbp.slice_from("a~"); + continue; + case 2: + sbp.slice_from("o~"); + continue; + case 3: + if (sbp.cursor >= sbp.limit) + break; + sbp.cursor++; + continue; + } + } + break; + } + } + + function habr2() { + if (sbp.out_grouping(g_v, 97, 250)) { + while (!sbp.in_grouping(g_v, 97, 250)) { + if (sbp.cursor >= sbp.limit) + return true; + sbp.cursor++; + } + return false; + } + return true; + } + + function habr3() { + if (sbp.in_grouping(g_v, 97, 250)) { + while (!sbp.out_grouping(g_v, 97, 250)) { + if (sbp.cursor >= sbp.limit) + return false; + sbp.cursor++; + } + } + I_pV = sbp.cursor; + return true; + } + + function habr4() { + var v_1 = sbp.cursor, + v_2, v_3; + if (sbp.in_grouping(g_v, 97, 250)) { + v_2 = sbp.cursor; + if (habr2()) { + sbp.cursor = v_2; + if (habr3()) + return; + } else + I_pV = sbp.cursor; + } + sbp.cursor = v_1; + if (sbp.out_grouping(g_v, 97, 250)) { + v_3 = sbp.cursor; + if (habr2()) { + sbp.cursor = v_3; + if (!sbp.in_grouping(g_v, 97, 250) || sbp.cursor >= sbp.limit) + return; + sbp.cursor++; + } + I_pV = sbp.cursor; + } + } + + function habr5() { + while (!sbp.in_grouping(g_v, 97, 250)) { + if (sbp.cursor >= sbp.limit) + return false; + sbp.cursor++; + } + while (!sbp.out_grouping(g_v, 97, 250)) { + if (sbp.cursor >= sbp.limit) + return false; + sbp.cursor++; + } + return true; + } + + function r_mark_regions() { + var v_1 = sbp.cursor; + I_pV = sbp.limit; + I_p1 = I_pV; + I_p2 = I_pV; + habr4(); + sbp.cursor = v_1; + if (habr5()) { + I_p1 = sbp.cursor; + if (habr5()) + I_p2 = sbp.cursor; + } + } + + function r_postlude() { + var among_var; + while (true) { + sbp.bra = sbp.cursor; + among_var = sbp.find_among(a_1, 3); + if (among_var) { + sbp.ket = sbp.cursor; + switch (among_var) { + case 1: + sbp.slice_from("\u00E3"); + continue; + case 2: + sbp.slice_from("\u00F5"); + continue; + case 3: + if (sbp.cursor >= sbp.limit) + break; + sbp.cursor++; + continue; + } + } + break; + } + } + + function r_RV() { + return I_pV <= sbp.cursor; + } + + function r_R1() { + return I_p1 <= sbp.cursor; + } + + function r_R2() { + return I_p2 <= sbp.cursor; + } + + function r_standard_suffix() { + var among_var; + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_5, 45); + if (!among_var) + return false; + sbp.bra = sbp.cursor; + switch (among_var) { + case 1: + if (!r_R2()) + return false; + sbp.slice_del(); + break; + case 2: + if (!r_R2()) + return false; + sbp.slice_from("log"); + break; + case 3: + if (!r_R2()) + return false; + sbp.slice_from("u"); + break; + case 4: + if (!r_R2()) + return false; + sbp.slice_from("ente"); + break; + case 5: + if (!r_R1()) + return false; + sbp.slice_del(); + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_2, 4); + if (among_var) { + sbp.bra = sbp.cursor; + if (r_R2()) { + sbp.slice_del(); + if (among_var == 1) { + sbp.ket = sbp.cursor; + if (sbp.eq_s_b(2, "at")) { + sbp.bra = sbp.cursor; + if (r_R2()) + sbp.slice_del(); + } + } + } + } + break; + case 6: + if (!r_R2()) + return false; + sbp.slice_del(); + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_3, 3); + if (among_var) { + sbp.bra = sbp.cursor; + if (among_var == 1) + if (r_R2()) + sbp.slice_del(); + } + break; + case 7: + if (!r_R2()) + return false; + sbp.slice_del(); + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_4, 3); + if (among_var) { + sbp.bra = sbp.cursor; + if (among_var == 1) + if (r_R2()) + sbp.slice_del(); + } + break; + case 8: + if (!r_R2()) + return false; + sbp.slice_del(); + sbp.ket = sbp.cursor; + if (sbp.eq_s_b(2, "at")) { + sbp.bra = sbp.cursor; + if (r_R2()) + sbp.slice_del(); + } + break; + case 9: + if (!r_RV() || !sbp.eq_s_b(1, "e")) + return false; + sbp.slice_from("ir"); + break; + } + return true; + } + + function r_verb_suffix() { + var among_var, v_1; + if (sbp.cursor >= I_pV) { + v_1 = sbp.limit_backward; + sbp.limit_backward = I_pV; + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_6, 120); + if (among_var) { + sbp.bra = sbp.cursor; + if (among_var == 1) + sbp.slice_del(); + sbp.limit_backward = v_1; + return true; + } + sbp.limit_backward = v_1; + } + return false; + } + + function r_residual_suffix() { + var among_var; + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_7, 7); + if (among_var) { + sbp.bra = sbp.cursor; + if (among_var == 1) + if (r_RV()) + sbp.slice_del(); + } + } + + function habr6(c1, c2) { + if (sbp.eq_s_b(1, c1)) { + sbp.bra = sbp.cursor; + var v_1 = sbp.limit - sbp.cursor; + if (sbp.eq_s_b(1, c2)) { + sbp.cursor = sbp.limit - v_1; + if (r_RV()) + sbp.slice_del(); + return false; + } + } + return true; + } + + function r_residual_form() { + var among_var, v_1, v_2, v_3; + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_8, 4); + if (among_var) { + sbp.bra = sbp.cursor; + switch (among_var) { + case 1: + if (r_RV()) { + sbp.slice_del(); + sbp.ket = sbp.cursor; + v_1 = sbp.limit - sbp.cursor; + if (habr6("u", "g")) + habr6("i", "c") + } + break; + case 2: + sbp.slice_from("c"); + break; + } + } + } + + function habr1() { + if (!r_standard_suffix()) { + sbp.cursor = sbp.limit; + if (!r_verb_suffix()) { + sbp.cursor = sbp.limit; + r_residual_suffix(); + return; + } + } + sbp.cursor = sbp.limit; + sbp.ket = sbp.cursor; + if (sbp.eq_s_b(1, "i")) { + sbp.bra = sbp.cursor; + if (sbp.eq_s_b(1, "c")) { + sbp.cursor = sbp.limit; + if (r_RV()) + sbp.slice_del(); + } + } + } + this.stem = function() { + var v_1 = sbp.cursor; + r_prelude(); + sbp.cursor = v_1; + r_mark_regions(); + sbp.limit_backward = v_1; + sbp.cursor = sbp.limit; + habr1(); + sbp.cursor = sbp.limit; + r_residual_form(); + sbp.cursor = sbp.limit_backward; + r_postlude(); + return true; + } + }; + + /* and return a function that stems a word for the current locale */ + return function(token) { + // for lunr version 2 + if (typeof token.update === "function") { + return token.update(function(word) { + st.setCurrent(word); + st.stem(); + return st.getCurrent(); + }) + } else { // for lunr version <= 1 + st.setCurrent(token); + st.stem(); + return st.getCurrent(); + } + } + })(); + + lunr.Pipeline.registerFunction(lunr.pt.stemmer, 'stemmer-pt'); + + lunr.pt.stopWordFilter = lunr.generateStopWordFilter('a ao aos aquela aquelas aquele aqueles aquilo as até com como da das de dela delas dele deles depois do dos e ela elas ele eles em entre era eram essa essas esse esses esta estamos estas estava estavam este esteja estejam estejamos estes esteve estive estivemos estiver estivera estiveram estiverem estivermos estivesse estivessem estivéramos estivéssemos estou está estávamos estão eu foi fomos for fora foram forem formos fosse fossem fui fôramos fôssemos haja hajam hajamos havemos hei houve houvemos houver houvera houveram houverei houverem houveremos houveria houveriam houvermos houverá houverão houveríamos houvesse houvessem houvéramos houvéssemos há hão isso isto já lhe lhes mais mas me mesmo meu meus minha minhas muito na nas nem no nos nossa nossas nosso nossos num numa não nós o os ou para pela pelas pelo pelos por qual quando que quem se seja sejam sejamos sem serei seremos seria seriam será serão seríamos seu seus somos sou sua suas são só também te tem temos tenha tenham tenhamos tenho terei teremos teria teriam terá terão teríamos teu teus teve tinha tinham tive tivemos tiver tivera tiveram tiverem tivermos tivesse tivessem tivéramos tivéssemos tu tua tuas tém tínhamos um uma você vocês vos à às éramos'.split(' ')); + + lunr.Pipeline.registerFunction(lunr.pt.stopWordFilter, 'stopWordFilter-pt'); + }; +})) \ No newline at end of file diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.ro.js b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.ro.js new file mode 100644 index 0000000000000000000000000000000000000000..cabc5220754067f9a437f135730c645f3fe6e7a3 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.ro.js @@ -0,0 +1,558 @@ +/*! + * Lunr languages, `Romanian` language + * https://github.com/MihaiValentin/lunr-languages + * + * Copyright 2014, Mihai Valentin + * http://www.mozilla.org/MPL/ + */ +/*! + * based on + * Snowball JavaScript Library v0.3 + * http://code.google.com/p/urim/ + * http://snowball.tartarus.org/ + * + * Copyright 2010, Oleg Mazko + * http://www.mozilla.org/MPL/ + */ + +/** + * export the module via AMD, CommonJS or as a browser global + * Export code from https://github.com/umdjs/umd/blob/master/returnExports.js + */ +; +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(factory) + } else if (typeof exports === 'object') { + /** + * Node. Does not work with strict CommonJS, but + * only CommonJS-like environments that support module.exports, + * like Node. + */ + module.exports = factory() + } else { + // Browser globals (root is window) + factory()(root.lunr); + } +}(this, function() { + /** + * Just return a value to define the module export. + * This example returns an object, but the module + * can return a function as the exported value. + */ + return function(lunr) { + /* throw error if lunr is not yet included */ + if ('undefined' === typeof lunr) { + throw new Error('Lunr is not present. Please include / require Lunr before this script.'); + } + + /* throw error if lunr stemmer support is not yet included */ + if ('undefined' === typeof lunr.stemmerSupport) { + throw new Error('Lunr stemmer support is not present. Please include / require Lunr stemmer support before this script.'); + } + + /* register specific locale function */ + lunr.ro = function() { + this.pipeline.reset(); + this.pipeline.add( + lunr.ro.trimmer, + lunr.ro.stopWordFilter, + lunr.ro.stemmer + ); + + // for lunr version 2 + // this is necessary so that every searched word is also stemmed before + // in lunr <= 1 this is not needed, as it is done using the normal pipeline + if (this.searchPipeline) { + this.searchPipeline.reset(); + this.searchPipeline.add(lunr.ro.stemmer) + } + }; + + /* lunr trimmer function */ + lunr.ro.wordCharacters = "A-Za-z\xAA\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02B8\u02E0-\u02E4\u1D00-\u1D25\u1D2C-\u1D5C\u1D62-\u1D65\u1D6B-\u1D77\u1D79-\u1DBE\u1E00-\u1EFF\u2071\u207F\u2090-\u209C\u212A\u212B\u2132\u214E\u2160-\u2188\u2C60-\u2C7F\uA722-\uA787\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA7FF\uAB30-\uAB5A\uAB5C-\uAB64\uFB00-\uFB06\uFF21-\uFF3A\uFF41-\uFF5A"; + lunr.ro.trimmer = lunr.trimmerSupport.generateTrimmer(lunr.ro.wordCharacters); + + lunr.Pipeline.registerFunction(lunr.ro.trimmer, 'trimmer-ro'); + + /* lunr stemmer function */ + lunr.ro.stemmer = (function() { + /* create the wrapped stemmer object */ + var Among = lunr.stemmerSupport.Among, + SnowballProgram = lunr.stemmerSupport.SnowballProgram, + st = new function RomanianStemmer() { + var a_0 = [new Among("", -1, 3), new Among("I", 0, 1), new Among("U", 0, 2)], + a_1 = [ + new Among("ea", -1, 3), new Among("a\u0163ia", -1, 7), + new Among("aua", -1, 2), new Among("iua", -1, 4), + new Among("a\u0163ie", -1, 7), new Among("ele", -1, 3), + new Among("ile", -1, 5), new Among("iile", 6, 4), + new Among("iei", -1, 4), new Among("atei", -1, 6), + new Among("ii", -1, 4), new Among("ului", -1, 1), + new Among("ul", -1, 1), new Among("elor", -1, 3), + new Among("ilor", -1, 4), new Among("iilor", 14, 4) + ], + a_2 = [ + new Among("icala", -1, 4), new Among("iciva", -1, 4), + new Among("ativa", -1, 5), new Among("itiva", -1, 6), + new Among("icale", -1, 4), new Among("a\u0163iune", -1, 5), + new Among("i\u0163iune", -1, 6), new Among("atoare", -1, 5), + new Among("itoare", -1, 6), new Among("\u0103toare", -1, 5), + new Among("icitate", -1, 4), new Among("abilitate", -1, 1), + new Among("ibilitate", -1, 2), new Among("ivitate", -1, 3), + new Among("icive", -1, 4), new Among("ative", -1, 5), + new Among("itive", -1, 6), new Among("icali", -1, 4), + new Among("atori", -1, 5), new Among("icatori", 18, 4), + new Among("itori", -1, 6), new Among("\u0103tori", -1, 5), + new Among("icitati", -1, 4), new Among("abilitati", -1, 1), + new Among("ivitati", -1, 3), new Among("icivi", -1, 4), + new Among("ativi", -1, 5), new Among("itivi", -1, 6), + new Among("icit\u0103i", -1, 4), new Among("abilit\u0103i", -1, 1), + new Among("ivit\u0103i", -1, 3), + new Among("icit\u0103\u0163i", -1, 4), + new Among("abilit\u0103\u0163i", -1, 1), + new Among("ivit\u0103\u0163i", -1, 3), new Among("ical", -1, 4), + new Among("ator", -1, 5), new Among("icator", 35, 4), + new Among("itor", -1, 6), new Among("\u0103tor", -1, 5), + new Among("iciv", -1, 4), new Among("ativ", -1, 5), + new Among("itiv", -1, 6), new Among("ical\u0103", -1, 4), + new Among("iciv\u0103", -1, 4), new Among("ativ\u0103", -1, 5), + new Among("itiv\u0103", -1, 6) + ], + a_3 = [new Among("ica", -1, 1), + new Among("abila", -1, 1), new Among("ibila", -1, 1), + new Among("oasa", -1, 1), new Among("ata", -1, 1), + new Among("ita", -1, 1), new Among("anta", -1, 1), + new Among("ista", -1, 3), new Among("uta", -1, 1), + new Among("iva", -1, 1), new Among("ic", -1, 1), + new Among("ice", -1, 1), new Among("abile", -1, 1), + new Among("ibile", -1, 1), new Among("isme", -1, 3), + new Among("iune", -1, 2), new Among("oase", -1, 1), + new Among("ate", -1, 1), new Among("itate", 17, 1), + new Among("ite", -1, 1), new Among("ante", -1, 1), + new Among("iste", -1, 3), new Among("ute", -1, 1), + new Among("ive", -1, 1), new Among("ici", -1, 1), + new Among("abili", -1, 1), new Among("ibili", -1, 1), + new Among("iuni", -1, 2), new Among("atori", -1, 1), + new Among("osi", -1, 1), new Among("ati", -1, 1), + new Among("itati", 30, 1), new Among("iti", -1, 1), + new Among("anti", -1, 1), new Among("isti", -1, 3), + new Among("uti", -1, 1), new Among("i\u015Fti", -1, 3), + new Among("ivi", -1, 1), new Among("it\u0103i", -1, 1), + new Among("o\u015Fi", -1, 1), new Among("it\u0103\u0163i", -1, 1), + new Among("abil", -1, 1), new Among("ibil", -1, 1), + new Among("ism", -1, 3), new Among("ator", -1, 1), + new Among("os", -1, 1), new Among("at", -1, 1), + new Among("it", -1, 1), new Among("ant", -1, 1), + new Among("ist", -1, 3), new Among("ut", -1, 1), + new Among("iv", -1, 1), new Among("ic\u0103", -1, 1), + new Among("abil\u0103", -1, 1), new Among("ibil\u0103", -1, 1), + new Among("oas\u0103", -1, 1), new Among("at\u0103", -1, 1), + new Among("it\u0103", -1, 1), new Among("ant\u0103", -1, 1), + new Among("ist\u0103", -1, 3), new Among("ut\u0103", -1, 1), + new Among("iv\u0103", -1, 1) + ], + a_4 = [new Among("ea", -1, 1), + new Among("ia", -1, 1), new Among("esc", -1, 1), + new Among("\u0103sc", -1, 1), new Among("ind", -1, 1), + new Among("\u00E2nd", -1, 1), new Among("are", -1, 1), + new Among("ere", -1, 1), new Among("ire", -1, 1), + new Among("\u00E2re", -1, 1), new Among("se", -1, 2), + new Among("ase", 10, 1), new Among("sese", 10, 2), + new Among("ise", 10, 1), new Among("use", 10, 1), + new Among("\u00E2se", 10, 1), new Among("e\u015Fte", -1, 1), + new Among("\u0103\u015Fte", -1, 1), new Among("eze", -1, 1), + new Among("ai", -1, 1), new Among("eai", 19, 1), + new Among("iai", 19, 1), new Among("sei", -1, 2), + new Among("e\u015Fti", -1, 1), new Among("\u0103\u015Fti", -1, 1), + new Among("ui", -1, 1), new Among("ezi", -1, 1), + new Among("\u00E2i", -1, 1), new Among("a\u015Fi", -1, 1), + new Among("se\u015Fi", -1, 2), new Among("ase\u015Fi", 29, 1), + new Among("sese\u015Fi", 29, 2), new Among("ise\u015Fi", 29, 1), + new Among("use\u015Fi", 29, 1), + new Among("\u00E2se\u015Fi", 29, 1), new Among("i\u015Fi", -1, 1), + new Among("u\u015Fi", -1, 1), new Among("\u00E2\u015Fi", -1, 1), + new Among("a\u0163i", -1, 2), new Among("ea\u0163i", 38, 1), + new Among("ia\u0163i", 38, 1), new Among("e\u0163i", -1, 2), + new Among("i\u0163i", -1, 2), new Among("\u00E2\u0163i", -1, 2), + new Among("ar\u0103\u0163i", -1, 1), + new Among("ser\u0103\u0163i", -1, 2), + new Among("aser\u0103\u0163i", 45, 1), + new Among("seser\u0103\u0163i", 45, 2), + new Among("iser\u0103\u0163i", 45, 1), + new Among("user\u0103\u0163i", 45, 1), + new Among("\u00E2ser\u0103\u0163i", 45, 1), + new Among("ir\u0103\u0163i", -1, 1), + new Among("ur\u0103\u0163i", -1, 1), + new Among("\u00E2r\u0103\u0163i", -1, 1), new Among("am", -1, 1), + new Among("eam", 54, 1), new Among("iam", 54, 1), + new Among("em", -1, 2), new Among("asem", 57, 1), + new Among("sesem", 57, 2), new Among("isem", 57, 1), + new Among("usem", 57, 1), new Among("\u00E2sem", 57, 1), + new Among("im", -1, 2), new Among("\u00E2m", -1, 2), + new Among("\u0103m", -1, 2), new Among("ar\u0103m", 65, 1), + new Among("ser\u0103m", 65, 2), new Among("aser\u0103m", 67, 1), + new Among("seser\u0103m", 67, 2), new Among("iser\u0103m", 67, 1), + new Among("user\u0103m", 67, 1), + new Among("\u00E2ser\u0103m", 67, 1), + new Among("ir\u0103m", 65, 1), new Among("ur\u0103m", 65, 1), + new Among("\u00E2r\u0103m", 65, 1), new Among("au", -1, 1), + new Among("eau", 76, 1), new Among("iau", 76, 1), + new Among("indu", -1, 1), new Among("\u00E2ndu", -1, 1), + new Among("ez", -1, 1), new Among("easc\u0103", -1, 1), + new Among("ar\u0103", -1, 1), new Among("ser\u0103", -1, 2), + new Among("aser\u0103", 84, 1), new Among("seser\u0103", 84, 2), + new Among("iser\u0103", 84, 1), new Among("user\u0103", 84, 1), + new Among("\u00E2ser\u0103", 84, 1), new Among("ir\u0103", -1, 1), + new Among("ur\u0103", -1, 1), new Among("\u00E2r\u0103", -1, 1), + new Among("eaz\u0103", -1, 1) + ], + a_5 = [new Among("a", -1, 1), + new Among("e", -1, 1), new Among("ie", 1, 1), + new Among("i", -1, 1), new Among("\u0103", -1, 1) + ], + g_v = [17, 65, + 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 32, 0, 0, 4 + ], + B_standard_suffix_removed, I_p2, I_p1, I_pV, sbp = new SnowballProgram(); + this.setCurrent = function(word) { + sbp.setCurrent(word); + }; + this.getCurrent = function() { + return sbp.getCurrent(); + }; + + function habr1(c1, c2) { + if (sbp.eq_s(1, c1)) { + sbp.ket = sbp.cursor; + if (sbp.in_grouping(g_v, 97, 259)) + sbp.slice_from(c2); + } + } + + function r_prelude() { + var v_1, v_2; + while (true) { + v_1 = sbp.cursor; + if (sbp.in_grouping(g_v, 97, 259)) { + v_2 = sbp.cursor; + sbp.bra = v_2; + habr1("u", "U"); + sbp.cursor = v_2; + habr1("i", "I"); + } + sbp.cursor = v_1; + if (sbp.cursor >= sbp.limit) { + break; + } + sbp.cursor++; + } + } + + function habr2() { + if (sbp.out_grouping(g_v, 97, 259)) { + while (!sbp.in_grouping(g_v, 97, 259)) { + if (sbp.cursor >= sbp.limit) + return true; + sbp.cursor++; + } + return false; + } + return true; + } + + function habr3() { + if (sbp.in_grouping(g_v, 97, 259)) { + while (!sbp.out_grouping(g_v, 97, 259)) { + if (sbp.cursor >= sbp.limit) + return true; + sbp.cursor++; + } + } + return false; + } + + function habr4() { + var v_1 = sbp.cursor, + v_2, v_3; + if (sbp.in_grouping(g_v, 97, 259)) { + v_2 = sbp.cursor; + if (habr2()) { + sbp.cursor = v_2; + if (!habr3()) { + I_pV = sbp.cursor; + return; + } + } else { + I_pV = sbp.cursor; + return; + } + } + sbp.cursor = v_1; + if (sbp.out_grouping(g_v, 97, 259)) { + v_3 = sbp.cursor; + if (habr2()) { + sbp.cursor = v_3; + if (sbp.in_grouping(g_v, 97, 259) && sbp.cursor < sbp.limit) + sbp.cursor++; + } + I_pV = sbp.cursor; + } + } + + function habr5() { + while (!sbp.in_grouping(g_v, 97, 259)) { + if (sbp.cursor >= sbp.limit) + return false; + sbp.cursor++; + } + while (!sbp.out_grouping(g_v, 97, 259)) { + if (sbp.cursor >= sbp.limit) + return false; + sbp.cursor++; + } + return true; + } + + function r_mark_regions() { + var v_1 = sbp.cursor; + I_pV = sbp.limit; + I_p1 = I_pV; + I_p2 = I_pV; + habr4(); + sbp.cursor = v_1; + if (habr5()) { + I_p1 = sbp.cursor; + if (habr5()) + I_p2 = sbp.cursor; + } + } + + function r_postlude() { + var among_var; + while (true) { + sbp.bra = sbp.cursor; + among_var = sbp.find_among(a_0, 3); + if (among_var) { + sbp.ket = sbp.cursor; + switch (among_var) { + case 1: + sbp.slice_from("i"); + continue; + case 2: + sbp.slice_from("u"); + continue; + case 3: + if (sbp.cursor >= sbp.limit) + break; + sbp.cursor++; + continue; + } + } + break; + } + } + + function r_RV() { + return I_pV <= sbp.cursor; + } + + function r_R1() { + return I_p1 <= sbp.cursor; + } + + function r_R2() { + return I_p2 <= sbp.cursor; + } + + function r_step_0() { + var among_var, v_1; + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_1, 16); + if (among_var) { + sbp.bra = sbp.cursor; + if (r_R1()) { + switch (among_var) { + case 1: + sbp.slice_del(); + break; + case 2: + sbp.slice_from("a"); + break; + case 3: + sbp.slice_from("e"); + break; + case 4: + sbp.slice_from("i"); + break; + case 5: + v_1 = sbp.limit - sbp.cursor; + if (!sbp.eq_s_b(2, "ab")) { + sbp.cursor = sbp.limit - v_1; + sbp.slice_from("i"); + } + break; + case 6: + sbp.slice_from("at"); + break; + case 7: + sbp.slice_from("a\u0163i"); + break; + } + } + } + } + + function r_combo_suffix() { + var among_var, v_1 = sbp.limit - sbp.cursor; + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_2, 46); + if (among_var) { + sbp.bra = sbp.cursor; + if (r_R1()) { + switch (among_var) { + case 1: + sbp.slice_from("abil"); + break; + case 2: + sbp.slice_from("ibil"); + break; + case 3: + sbp.slice_from("iv"); + break; + case 4: + sbp.slice_from("ic"); + break; + case 5: + sbp.slice_from("at"); + break; + case 6: + sbp.slice_from("it"); + break; + } + B_standard_suffix_removed = true; + sbp.cursor = sbp.limit - v_1; + return true; + } + } + return false; + } + + function r_standard_suffix() { + var among_var, v_1; + B_standard_suffix_removed = false; + while (true) { + v_1 = sbp.limit - sbp.cursor; + if (!r_combo_suffix()) { + sbp.cursor = sbp.limit - v_1; + break; + } + } + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_3, 62); + if (among_var) { + sbp.bra = sbp.cursor; + if (r_R2()) { + switch (among_var) { + case 1: + sbp.slice_del(); + break; + case 2: + if (sbp.eq_s_b(1, "\u0163")) { + sbp.bra = sbp.cursor; + sbp.slice_from("t"); + } + break; + case 3: + sbp.slice_from("ist"); + break; + } + B_standard_suffix_removed = true; + } + } + } + + function r_verb_suffix() { + var among_var, v_1, v_2; + if (sbp.cursor >= I_pV) { + v_1 = sbp.limit_backward; + sbp.limit_backward = I_pV; + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_4, 94); + if (among_var) { + sbp.bra = sbp.cursor; + switch (among_var) { + case 1: + v_2 = sbp.limit - sbp.cursor; + if (!sbp.out_grouping_b(g_v, 97, 259)) { + sbp.cursor = sbp.limit - v_2; + if (!sbp.eq_s_b(1, "u")) + break; + } + case 2: + sbp.slice_del(); + break; + } + } + sbp.limit_backward = v_1; + } + } + + function r_vowel_suffix() { + var among_var; + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_5, 5); + if (among_var) { + sbp.bra = sbp.cursor; + if (r_RV() && among_var == 1) + sbp.slice_del(); + } + } + this.stem = function() { + var v_1 = sbp.cursor; + r_prelude(); + sbp.cursor = v_1; + r_mark_regions(); + sbp.limit_backward = v_1; + sbp.cursor = sbp.limit; + r_step_0(); + sbp.cursor = sbp.limit; + r_standard_suffix(); + sbp.cursor = sbp.limit; + if (!B_standard_suffix_removed) { + sbp.cursor = sbp.limit; + r_verb_suffix(); + sbp.cursor = sbp.limit; + } + r_vowel_suffix(); + sbp.cursor = sbp.limit_backward; + r_postlude(); + return true; + } + }; + + /* and return a function that stems a word for the current locale */ + return function(token) { + // for lunr version 2 + if (typeof token.update === "function") { + return token.update(function(word) { + st.setCurrent(word); + st.stem(); + return st.getCurrent(); + }) + } else { // for lunr version <= 1 + st.setCurrent(token); + st.stem(); + return st.getCurrent(); + } + } + })(); + + lunr.Pipeline.registerFunction(lunr.ro.stemmer, 'stemmer-ro'); + + lunr.ro.stopWordFilter = lunr.generateStopWordFilter('acea aceasta această aceea acei aceia acel acela acele acelea acest acesta aceste acestea aceşti aceştia acolo acord acum ai aia aibă aici al ale alea altceva altcineva am ar are asemenea asta astea astăzi asupra au avea avem aveţi azi aş aşadar aţi bine bucur bună ca care caut ce cel ceva chiar cinci cine cineva contra cu cum cumva curând curînd când cât câte câtva câţi cînd cît cîte cîtva cîţi că căci cărei căror cărui către da dacă dar datorită dată dau de deci deja deoarece departe deşi din dinaintea dintr- dintre doi doilea două drept după dă ea ei el ele eram este eu eşti face fata fi fie fiecare fii fim fiu fiţi frumos fără graţie halbă iar ieri la le li lor lui lângă lîngă mai mea mei mele mereu meu mi mie mine mult multă mulţi mulţumesc mâine mîine mă ne nevoie nici nicăieri nimeni nimeri nimic nişte noastre noastră noi noroc nostru nouă noştri nu opt ori oricare orice oricine oricum oricând oricât oricînd oricît oriunde patra patru patrulea pe pentru peste pic poate pot prea prima primul prin puţin puţina puţină până pînă rog sa sale sau se spate spre sub sunt suntem sunteţi sută sînt sîntem sînteţi să săi său ta tale te timp tine toate toată tot totuşi toţi trei treia treilea tu tăi tău un una unde undeva unei uneia unele uneori unii unor unora unu unui unuia unul vi voastre voastră voi vostru vouă voştri vreme vreo vreun vă zece zero zi zice îi îl îmi împotriva în înainte înaintea încotro încât încît între întrucât întrucît îţi ăla ălea ăsta ăstea ăştia şapte şase şi ştiu ţi ţie'.split(' ')); + + lunr.Pipeline.registerFunction(lunr.ro.stopWordFilter, 'stopWordFilter-ro'); + }; +})) \ No newline at end of file diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.ru.js b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.ru.js new file mode 100644 index 0000000000000000000000000000000000000000..c7909a0e776861235a742412bb3a82d52da8c95e --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.ru.js @@ -0,0 +1,391 @@ +/*! + * Lunr languages, `Russian` language + * https://github.com/MihaiValentin/lunr-languages + * + * Copyright 2014, Mihai Valentin + * http://www.mozilla.org/MPL/ + */ +/*! + * based on + * Snowball JavaScript Library v0.3 + * http://code.google.com/p/urim/ + * http://snowball.tartarus.org/ + * + * Copyright 2010, Oleg Mazko + * http://www.mozilla.org/MPL/ + */ + +/** + * export the module via AMD, CommonJS or as a browser global + * Export code from https://github.com/umdjs/umd/blob/master/returnExports.js + */ +; +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(factory) + } else if (typeof exports === 'object') { + /** + * Node. Does not work with strict CommonJS, but + * only CommonJS-like environments that support module.exports, + * like Node. + */ + module.exports = factory() + } else { + // Browser globals (root is window) + factory()(root.lunr); + } +}(this, function() { + /** + * Just return a value to define the module export. + * This example returns an object, but the module + * can return a function as the exported value. + */ + return function(lunr) { + /* throw error if lunr is not yet included */ + if ('undefined' === typeof lunr) { + throw new Error('Lunr is not present. Please include / require Lunr before this script.'); + } + + /* throw error if lunr stemmer support is not yet included */ + if ('undefined' === typeof lunr.stemmerSupport) { + throw new Error('Lunr stemmer support is not present. Please include / require Lunr stemmer support before this script.'); + } + + /* register specific locale function */ + lunr.ru = function() { + this.pipeline.reset(); + this.pipeline.add( + lunr.ru.trimmer, + lunr.ru.stopWordFilter, + lunr.ru.stemmer + ); + + // for lunr version 2 + // this is necessary so that every searched word is also stemmed before + // in lunr <= 1 this is not needed, as it is done using the normal pipeline + if (this.searchPipeline) { + this.searchPipeline.reset(); + this.searchPipeline.add(lunr.ru.stemmer) + } + }; + + /* lunr trimmer function */ + lunr.ru.wordCharacters = "\u0400-\u0484\u0487-\u052F\u1D2B\u1D78\u2DE0-\u2DFF\uA640-\uA69F\uFE2E\uFE2F"; + lunr.ru.trimmer = lunr.trimmerSupport.generateTrimmer(lunr.ru.wordCharacters); + + lunr.Pipeline.registerFunction(lunr.ru.trimmer, 'trimmer-ru'); + + /* lunr stemmer function */ + lunr.ru.stemmer = (function() { + /* create the wrapped stemmer object */ + var Among = lunr.stemmerSupport.Among, + SnowballProgram = lunr.stemmerSupport.SnowballProgram, + st = new function RussianStemmer() { + var a_0 = [new Among("\u0432", -1, 1), new Among("\u0438\u0432", 0, 2), + new Among("\u044B\u0432", 0, 2), + new Among("\u0432\u0448\u0438", -1, 1), + new Among("\u0438\u0432\u0448\u0438", 3, 2), + new Among("\u044B\u0432\u0448\u0438", 3, 2), + new Among("\u0432\u0448\u0438\u0441\u044C", -1, 1), + new Among("\u0438\u0432\u0448\u0438\u0441\u044C", 6, 2), + new Among("\u044B\u0432\u0448\u0438\u0441\u044C", 6, 2) + ], + a_1 = [ + new Among("\u0435\u0435", -1, 1), new Among("\u0438\u0435", -1, 1), + new Among("\u043E\u0435", -1, 1), new Among("\u044B\u0435", -1, 1), + new Among("\u0438\u043C\u0438", -1, 1), + new Among("\u044B\u043C\u0438", -1, 1), + new Among("\u0435\u0439", -1, 1), new Among("\u0438\u0439", -1, 1), + new Among("\u043E\u0439", -1, 1), new Among("\u044B\u0439", -1, 1), + new Among("\u0435\u043C", -1, 1), new Among("\u0438\u043C", -1, 1), + new Among("\u043E\u043C", -1, 1), new Among("\u044B\u043C", -1, 1), + new Among("\u0435\u0433\u043E", -1, 1), + new Among("\u043E\u0433\u043E", -1, 1), + new Among("\u0435\u043C\u0443", -1, 1), + new Among("\u043E\u043C\u0443", -1, 1), + new Among("\u0438\u0445", -1, 1), new Among("\u044B\u0445", -1, 1), + new Among("\u0435\u044E", -1, 1), new Among("\u043E\u044E", -1, 1), + new Among("\u0443\u044E", -1, 1), new Among("\u044E\u044E", -1, 1), + new Among("\u0430\u044F", -1, 1), new Among("\u044F\u044F", -1, 1) + ], + a_2 = [ + new Among("\u0435\u043C", -1, 1), new Among("\u043D\u043D", -1, 1), + new Among("\u0432\u0448", -1, 1), + new Among("\u0438\u0432\u0448", 2, 2), + new Among("\u044B\u0432\u0448", 2, 2), new Among("\u0449", -1, 1), + new Among("\u044E\u0449", 5, 1), + new Among("\u0443\u044E\u0449", 6, 2) + ], + a_3 = [ + new Among("\u0441\u044C", -1, 1), new Among("\u0441\u044F", -1, 1) + ], + a_4 = [ + new Among("\u043B\u0430", -1, 1), + new Among("\u0438\u043B\u0430", 0, 2), + new Among("\u044B\u043B\u0430", 0, 2), + new Among("\u043D\u0430", -1, 1), + new Among("\u0435\u043D\u0430", 3, 2), + new Among("\u0435\u0442\u0435", -1, 1), + new Among("\u0438\u0442\u0435", -1, 2), + new Among("\u0439\u0442\u0435", -1, 1), + new Among("\u0435\u0439\u0442\u0435", 7, 2), + new Among("\u0443\u0439\u0442\u0435", 7, 2), + new Among("\u043B\u0438", -1, 1), + new Among("\u0438\u043B\u0438", 10, 2), + new Among("\u044B\u043B\u0438", 10, 2), new Among("\u0439", -1, 1), + new Among("\u0435\u0439", 13, 2), new Among("\u0443\u0439", 13, 2), + new Among("\u043B", -1, 1), new Among("\u0438\u043B", 16, 2), + new Among("\u044B\u043B", 16, 2), new Among("\u0435\u043C", -1, 1), + new Among("\u0438\u043C", -1, 2), new Among("\u044B\u043C", -1, 2), + new Among("\u043D", -1, 1), new Among("\u0435\u043D", 22, 2), + new Among("\u043B\u043E", -1, 1), + new Among("\u0438\u043B\u043E", 24, 2), + new Among("\u044B\u043B\u043E", 24, 2), + new Among("\u043D\u043E", -1, 1), + new Among("\u0435\u043D\u043E", 27, 2), + new Among("\u043D\u043D\u043E", 27, 1), + new Among("\u0435\u0442", -1, 1), + new Among("\u0443\u0435\u0442", 30, 2), + new Among("\u0438\u0442", -1, 2), new Among("\u044B\u0442", -1, 2), + new Among("\u044E\u0442", -1, 1), + new Among("\u0443\u044E\u0442", 34, 2), + new Among("\u044F\u0442", -1, 2), new Among("\u043D\u044B", -1, 1), + new Among("\u0435\u043D\u044B", 37, 2), + new Among("\u0442\u044C", -1, 1), + new Among("\u0438\u0442\u044C", 39, 2), + new Among("\u044B\u0442\u044C", 39, 2), + new Among("\u0435\u0448\u044C", -1, 1), + new Among("\u0438\u0448\u044C", -1, 2), new Among("\u044E", -1, 2), + new Among("\u0443\u044E", 44, 2) + ], + a_5 = [ + new Among("\u0430", -1, 1), new Among("\u0435\u0432", -1, 1), + new Among("\u043E\u0432", -1, 1), new Among("\u0435", -1, 1), + new Among("\u0438\u0435", 3, 1), new Among("\u044C\u0435", 3, 1), + new Among("\u0438", -1, 1), new Among("\u0435\u0438", 6, 1), + new Among("\u0438\u0438", 6, 1), + new Among("\u0430\u043C\u0438", 6, 1), + new Among("\u044F\u043C\u0438", 6, 1), + new Among("\u0438\u044F\u043C\u0438", 10, 1), + new Among("\u0439", -1, 1), new Among("\u0435\u0439", 12, 1), + new Among("\u0438\u0435\u0439", 13, 1), + new Among("\u0438\u0439", 12, 1), new Among("\u043E\u0439", 12, 1), + new Among("\u0430\u043C", -1, 1), new Among("\u0435\u043C", -1, 1), + new Among("\u0438\u0435\u043C", 18, 1), + new Among("\u043E\u043C", -1, 1), new Among("\u044F\u043C", -1, 1), + new Among("\u0438\u044F\u043C", 21, 1), new Among("\u043E", -1, 1), + new Among("\u0443", -1, 1), new Among("\u0430\u0445", -1, 1), + new Among("\u044F\u0445", -1, 1), + new Among("\u0438\u044F\u0445", 26, 1), new Among("\u044B", -1, 1), + new Among("\u044C", -1, 1), new Among("\u044E", -1, 1), + new Among("\u0438\u044E", 30, 1), new Among("\u044C\u044E", 30, 1), + new Among("\u044F", -1, 1), new Among("\u0438\u044F", 33, 1), + new Among("\u044C\u044F", 33, 1) + ], + a_6 = [ + new Among("\u043E\u0441\u0442", -1, 1), + new Among("\u043E\u0441\u0442\u044C", -1, 1) + ], + a_7 = [ + new Among("\u0435\u0439\u0448\u0435", -1, 1), + new Among("\u043D", -1, 2), new Among("\u0435\u0439\u0448", -1, 1), + new Among("\u044C", -1, 3) + ], + g_v = [33, 65, 8, 232], + I_p2, I_pV, sbp = new SnowballProgram(); + this.setCurrent = function(word) { + sbp.setCurrent(word); + }; + this.getCurrent = function() { + return sbp.getCurrent(); + }; + + function habr3() { + while (!sbp.in_grouping(g_v, 1072, 1103)) { + if (sbp.cursor >= sbp.limit) + return false; + sbp.cursor++; + } + return true; + } + + function habr4() { + while (!sbp.out_grouping(g_v, 1072, 1103)) { + if (sbp.cursor >= sbp.limit) + return false; + sbp.cursor++; + } + return true; + } + + function r_mark_regions() { + I_pV = sbp.limit; + I_p2 = I_pV; + if (habr3()) { + I_pV = sbp.cursor; + if (habr4()) + if (habr3()) + if (habr4()) + I_p2 = sbp.cursor; + } + } + + function r_R2() { + return I_p2 <= sbp.cursor; + } + + function habr2(a, n) { + var among_var, v_1; + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a, n); + if (among_var) { + sbp.bra = sbp.cursor; + switch (among_var) { + case 1: + v_1 = sbp.limit - sbp.cursor; + if (!sbp.eq_s_b(1, "\u0430")) { + sbp.cursor = sbp.limit - v_1; + if (!sbp.eq_s_b(1, "\u044F")) + return false; + } + case 2: + sbp.slice_del(); + break; + } + return true; + } + return false; + } + + function r_perfective_gerund() { + return habr2(a_0, 9); + } + + function habr1(a, n) { + var among_var; + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a, n); + if (among_var) { + sbp.bra = sbp.cursor; + if (among_var == 1) + sbp.slice_del(); + return true; + } + return false; + } + + function r_adjective() { + return habr1(a_1, 26); + } + + function r_adjectival() { + var among_var; + if (r_adjective()) { + habr2(a_2, 8); + return true; + } + return false; + } + + function r_reflexive() { + return habr1(a_3, 2); + } + + function r_verb() { + return habr2(a_4, 46); + } + + function r_noun() { + habr1(a_5, 36); + } + + function r_derivational() { + var among_var; + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_6, 2); + if (among_var) { + sbp.bra = sbp.cursor; + if (r_R2() && among_var == 1) + sbp.slice_del(); + } + } + + function r_tidy_up() { + var among_var; + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_7, 4); + if (among_var) { + sbp.bra = sbp.cursor; + switch (among_var) { + case 1: + sbp.slice_del(); + sbp.ket = sbp.cursor; + if (!sbp.eq_s_b(1, "\u043D")) + break; + sbp.bra = sbp.cursor; + case 2: + if (!sbp.eq_s_b(1, "\u043D")) + break; + case 3: + sbp.slice_del(); + break; + } + } + } + this.stem = function() { + r_mark_regions(); + sbp.cursor = sbp.limit; + if (sbp.cursor < I_pV) + return false; + sbp.limit_backward = I_pV; + if (!r_perfective_gerund()) { + sbp.cursor = sbp.limit; + if (!r_reflexive()) + sbp.cursor = sbp.limit; + if (!r_adjectival()) { + sbp.cursor = sbp.limit; + if (!r_verb()) { + sbp.cursor = sbp.limit; + r_noun(); + } + } + } + sbp.cursor = sbp.limit; + sbp.ket = sbp.cursor; + if (sbp.eq_s_b(1, "\u0438")) { + sbp.bra = sbp.cursor; + sbp.slice_del(); + } else + sbp.cursor = sbp.limit; + r_derivational(); + sbp.cursor = sbp.limit; + r_tidy_up(); + return true; + } + }; + + /* and return a function that stems a word for the current locale */ + return function(token) { + // for lunr version 2 + if (typeof token.update === "function") { + return token.update(function(word) { + st.setCurrent(word); + st.stem(); + return st.getCurrent(); + }) + } else { // for lunr version <= 1 + st.setCurrent(token); + st.stem(); + return st.getCurrent(); + } + } + })(); + + lunr.Pipeline.registerFunction(lunr.ru.stemmer, 'stemmer-ru'); + + lunr.ru.stopWordFilter = lunr.generateStopWordFilter('алло без близко более больше будем будет будете будешь будто буду будут будь бы бывает бывь был была были было быть в важная важное важные важный вам вами вас ваш ваша ваше ваши вверх вдали вдруг ведь везде весь вниз внизу во вокруг вон восемнадцатый восемнадцать восемь восьмой вот впрочем времени время все всегда всего всем всеми всему всех всею всю всюду вся всё второй вы г где говорил говорит год года году да давно даже далеко дальше даром два двадцатый двадцать две двенадцатый двенадцать двух девятнадцатый девятнадцать девятый девять действительно дел день десятый десять для до довольно долго должно другая другие других друго другое другой е его ее ей ему если есть еще ещё ею её ж же жизнь за занят занята занято заняты затем зато зачем здесь значит и из или им именно иметь ими имя иногда их к каждая каждое каждые каждый кажется как какая какой кем когда кого ком кому конечно которая которого которой которые который которых кроме кругом кто куда лет ли лишь лучше люди м мало между меля менее меньше меня миллионов мимо мира мне много многочисленная многочисленное многочисленные многочисленный мной мною мог могут мож может можно можхо мои мой мор мочь моя моё мы на наверху над надо назад наиболее наконец нам нами нас начала наш наша наше наши не него недавно недалеко нее ней нельзя нем немного нему непрерывно нередко несколько нет нею неё ни нибудь ниже низко никогда никуда ними них ничего но ну нужно нх о об оба обычно один одиннадцатый одиннадцать однажды однако одного одной около он она они оно опять особенно от отовсюду отсюда очень первый перед по под пожалуйста позже пока пор пора после посреди потом потому почему почти прекрасно при про просто против процентов пятнадцатый пятнадцать пятый пять раз разве рано раньше рядом с сам сама сами самим самими самих само самого самой самом самому саму свое своего своей свои своих свою сеаой себе себя сегодня седьмой сейчас семнадцатый семнадцать семь сих сказал сказала сказать сколько слишком сначала снова со собой собою совсем спасибо стал суть т та так такая также такие такое такой там твой твоя твоё те тебе тебя тем теми теперь тех то тобой тобою тогда того тоже только том тому тот тою третий три тринадцатый тринадцать ту туда тут ты тысяч у уж уже уметь хорошо хотеть хоть хотя хочешь часто чаще чего человек чем чему через четвертый четыре четырнадцатый четырнадцать что чтоб чтобы чуть шестнадцатый шестнадцать шестой шесть эта эти этим этими этих это этого этой этом этому этот эту я а'.split(' ')); + + lunr.Pipeline.registerFunction(lunr.ru.stopWordFilter, 'stopWordFilter-ru'); + }; +})) \ No newline at end of file diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.sa.js b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.sa.js new file mode 100644 index 0000000000000000000000000000000000000000..3d459f97844b2dfa4f5d51cb694c089952cc4bf3 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.sa.js @@ -0,0 +1,110 @@ +/*! + * Lunr languages, `Sanskrit` language + * https://github.com/MiKr13/lunr-languages + * + * Copyright 2023, India + * http://www.mozilla.org/MPL/ + */ +/*! + * based on + * Snowball JavaScript Library v0.3 + * http://code.google.com/p/urim/ + * http://snowball.tartarus.org/ + * + * Copyright 2010, Oleg Mazko + * http://www.mozilla.org/MPL/ + */ + +/** + * export the module via AMD, CommonJS or as a browser global + * Export code from https://github.com/umdjs/umd/blob/master/returnExports.js + */ +; +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(factory) + } else if (typeof exports === 'object') { + /** + * Node. Does not work with strict CommonJS, but + * only CommonJS-like environments that support module.exports, + * like Node. + */ + module.exports = factory() + } else { + // Browser globals (root is window) + factory()(root.lunr); + } +}(this, function() { + /** + * Just return a value to define the module export. + * This example returns an object, but the module + * can return a function as the exported value. + */ + return function(lunr) { + /* throw error if lunr is not yet included */ + if ('undefined' === typeof lunr) { + throw new Error('Lunr is not present. Please include / require Lunr before this script.'); + } + + /* throw error if lunr stemmer support is not yet included */ + if ('undefined' === typeof lunr.stemmerSupport) { + throw new Error('Lunr stemmer support is not present. Please include / require Lunr stemmer support before this script.'); + } + + /* register specific locale function */ + lunr.sa = function() { + this.pipeline.reset(); + this.pipeline.add( + lunr.sa.trimmer, + lunr.sa.stopWordFilter, + lunr.sa.stemmer + ); + + if (this.searchPipeline) { + this.searchPipeline.reset(); + this.searchPipeline.add(lunr.sa.stemmer) + } + }; + + /* lunr trimmer function */ + lunr.sa.wordCharacters = "\u0900-\u0903\u0904-\u090f\u0910-\u091f\u0920-\u092f\u0930-\u093f\u0940-\u094f\u0950-\u095f\u0960-\u096f\u0970-\u097f\uA8E0-\uA8F1\uA8F2-\uA8F7\uA8F8-\uA8FB\uA8FC-\uA8FD\uA8FE-\uA8FF\u11B00-\u11B09"; + lunr.sa.trimmer = lunr.trimmerSupport.generateTrimmer(lunr.sa.wordCharacters); + + lunr.Pipeline.registerFunction(lunr.sa.trimmer, 'trimmer-sa'); + /* lunr stop word filter */ + lunr.sa.stopWordFilter = lunr.generateStopWordFilter( + 'तथा अयम्‌ एकम्‌ इत्यस्मिन्‌ तथा तत्‌ वा अयम्‌ इत्यस्य ते आहूत उपरि तेषाम्‌ किन्तु तेषाम्‌ तदा इत्यनेन अधिकः इत्यस्य तत्‌ केचन बहवः द्वि तथा महत्वपूर्णः अयम्‌ अस्य विषये अयं अस्ति तत्‌ प्रथमः विषये इत्युपरि इत्युपरि इतर अधिकतमः अधिकः अपि सामान्यतया ठ इतरेतर नूतनम्‌ द न्यूनम्‌ कश्चित्‌ वा विशालः द सः अस्ति तदनुसारम् तत्र अस्ति केवलम्‌ अपि अत्र सर्वे विविधाः तत्‌ बहवः यतः इदानीम्‌ द दक्षिण इत्यस्मै तस्य उपरि नथ अतीव कार्यम्‌ सर्वे एकैकम्‌ इत्यादि। एते सन्ति उत इत्थम्‌ मध्ये एतदर्थं . स कस्य प्रथमः श्री. करोति अस्मिन् प्रकारः निर्मिता कालः तत्र कर्तुं समान अधुना ते सन्ति स एकः अस्ति सः अर्थात् तेषां कृते . स्थितम् विशेषः अग्रिम तेषाम्‌ समान स्रोतः ख म समान इदानीमपि अधिकतया करोतु ते समान इत्यस्य वीथी सह यस्मिन् कृतवान्‌ धृतः तदा पुनः पूर्वं सः आगतः किम्‌ कुल इतर पुरा मात्रा स विषये उ अतएव अपि नगरस्य उपरि यतः प्रतिशतं कतरः कालः साधनानि भूत तथापि जात सम्बन्धि अन्यत्‌ ग अतः अस्माकं स्वकीयाः अस्माकं इदानीं अन्तः इत्यादयः भवन्तः इत्यादयः एते एताः तस्य अस्य इदम् एते तेषां तेषां तेषां तान् तेषां तेषां तेषां समानः सः एकः च तादृशाः बहवः अन्ये च वदन्ति यत् कियत् कस्मै कस्मै यस्मै यस्मै यस्मै यस्मै न अतिनीचः किन्तु प्रथमं सम्पूर्णतया ततः चिरकालानन्तरं पुस्तकं सम्पूर्णतया अन्तः किन्तु अत्र वा इह इव श्रद्धाय अवशिष्यते परन्तु अन्ये वर्गाः सन्ति ते सन्ति शक्नुवन्ति सर्वे मिलित्वा सर्वे एकत्र"'.split(' ')); + /* lunr stemmer function */ + lunr.sa.stemmer = (function() { + + return function(word) { + // for lunr version 2 + if (typeof word.update === "function") { + return word.update(function(word) { + return word; + }) + } else { // for lunr version <= 1 + return word; + } + + } + })(); + + var segmenter = lunr.wordcut; + segmenter.init(); + lunr.sa.tokenizer = function(obj) { + if (!arguments.length || obj == null || obj == undefined) return [] + if (Array.isArray(obj)) return obj.map(function(t) { + return isLunr2 ? new lunr.Token(t.toLowerCase()) : t.toLowerCase() + }); + + var str = obj.toString().toLowerCase().replace(/^\s+/, ''); + return segmenter.cut(str).split('|'); + } + + lunr.Pipeline.registerFunction(lunr.sa.stemmer, 'stemmer-sa'); + lunr.Pipeline.registerFunction(lunr.sa.stopWordFilter, 'stopWordFilter-sa'); + + }; +})) \ No newline at end of file diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.stemmer.support.js b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.stemmer.support.js new file mode 100644 index 0000000000000000000000000000000000000000..896476a1812214c0d3527ff1764bd6729a80bc04 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.stemmer.support.js @@ -0,0 +1,304 @@ +/*! + * Snowball JavaScript Library v0.3 + * http://code.google.com/p/urim/ + * http://snowball.tartarus.org/ + * + * Copyright 2010, Oleg Mazko + * http://www.mozilla.org/MPL/ + */ + +/** + * export the module via AMD, CommonJS or as a browser global + * Export code from https://github.com/umdjs/umd/blob/master/returnExports.js + */ +;(function (root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(factory) + } else if (typeof exports === 'object') { + /** + * Node. Does not work with strict CommonJS, but + * only CommonJS-like environments that support module.exports, + * like Node. + */ + module.exports = factory() + } else { + // Browser globals (root is window) + factory()(root.lunr); + } +}(this, function () { + /** + * Just return a value to define the module export. + * This example returns an object, but the module + * can return a function as the exported value. + */ + return function(lunr) { + /* provides utilities for the included stemmers */ + lunr.stemmerSupport = { + Among: function(s, substring_i, result, method) { + this.toCharArray = function(s) { + var sLength = s.length, charArr = new Array(sLength); + for (var i = 0; i < sLength; i++) + charArr[i] = s.charCodeAt(i); + return charArr; + }; + + if ((!s && s != "") || (!substring_i && (substring_i != 0)) || !result) + throw ("Bad Among initialisation: s:" + s + ", substring_i: " + + substring_i + ", result: " + result); + this.s_size = s.length; + this.s = this.toCharArray(s); + this.substring_i = substring_i; + this.result = result; + this.method = method; + }, + SnowballProgram: function() { + var current; + return { + bra : 0, + ket : 0, + limit : 0, + cursor : 0, + limit_backward : 0, + setCurrent : function(word) { + current = word; + this.cursor = 0; + this.limit = word.length; + this.limit_backward = 0; + this.bra = this.cursor; + this.ket = this.limit; + }, + getCurrent : function() { + var result = current; + current = null; + return result; + }, + in_grouping : function(s, min, max) { + if (this.cursor < this.limit) { + var ch = current.charCodeAt(this.cursor); + if (ch <= max && ch >= min) { + ch -= min; + if (s[ch >> 3] & (0X1 << (ch & 0X7))) { + this.cursor++; + return true; + } + } + } + return false; + }, + in_grouping_b : function(s, min, max) { + if (this.cursor > this.limit_backward) { + var ch = current.charCodeAt(this.cursor - 1); + if (ch <= max && ch >= min) { + ch -= min; + if (s[ch >> 3] & (0X1 << (ch & 0X7))) { + this.cursor--; + return true; + } + } + } + return false; + }, + out_grouping : function(s, min, max) { + if (this.cursor < this.limit) { + var ch = current.charCodeAt(this.cursor); + if (ch > max || ch < min) { + this.cursor++; + return true; + } + ch -= min; + if (!(s[ch >> 3] & (0X1 << (ch & 0X7)))) { + this.cursor++; + return true; + } + } + return false; + }, + out_grouping_b : function(s, min, max) { + if (this.cursor > this.limit_backward) { + var ch = current.charCodeAt(this.cursor - 1); + if (ch > max || ch < min) { + this.cursor--; + return true; + } + ch -= min; + if (!(s[ch >> 3] & (0X1 << (ch & 0X7)))) { + this.cursor--; + return true; + } + } + return false; + }, + eq_s : function(s_size, s) { + if (this.limit - this.cursor < s_size) + return false; + for (var i = 0; i < s_size; i++) + if (current.charCodeAt(this.cursor + i) != s.charCodeAt(i)) + return false; + this.cursor += s_size; + return true; + }, + eq_s_b : function(s_size, s) { + if (this.cursor - this.limit_backward < s_size) + return false; + for (var i = 0; i < s_size; i++) + if (current.charCodeAt(this.cursor - s_size + i) != s + .charCodeAt(i)) + return false; + this.cursor -= s_size; + return true; + }, + find_among : function(v, v_size) { + var i = 0, j = v_size, c = this.cursor, l = this.limit, common_i = 0, common_j = 0, first_key_inspected = false; + while (true) { + var k = i + ((j - i) >> 1), diff = 0, common = common_i < common_j + ? common_i + : common_j, w = v[k]; + for (var i2 = common; i2 < w.s_size; i2++) { + if (c + common == l) { + diff = -1; + break; + } + diff = current.charCodeAt(c + common) - w.s[i2]; + if (diff) + break; + common++; + } + if (diff < 0) { + j = k; + common_j = common; + } else { + i = k; + common_i = common; + } + if (j - i <= 1) { + if (i > 0 || j == i || first_key_inspected) + break; + first_key_inspected = true; + } + } + while (true) { + var w = v[i]; + if (common_i >= w.s_size) { + this.cursor = c + w.s_size; + if (!w.method) + return w.result; + var res = w.method(); + this.cursor = c + w.s_size; + if (res) + return w.result; + } + i = w.substring_i; + if (i < 0) + return 0; + } + }, + find_among_b : function(v, v_size) { + var i = 0, j = v_size, c = this.cursor, lb = this.limit_backward, common_i = 0, common_j = 0, first_key_inspected = false; + while (true) { + var k = i + ((j - i) >> 1), diff = 0, common = common_i < common_j + ? common_i + : common_j, w = v[k]; + for (var i2 = w.s_size - 1 - common; i2 >= 0; i2--) { + if (c - common == lb) { + diff = -1; + break; + } + diff = current.charCodeAt(c - 1 - common) - w.s[i2]; + if (diff) + break; + common++; + } + if (diff < 0) { + j = k; + common_j = common; + } else { + i = k; + common_i = common; + } + if (j - i <= 1) { + if (i > 0 || j == i || first_key_inspected) + break; + first_key_inspected = true; + } + } + while (true) { + var w = v[i]; + if (common_i >= w.s_size) { + this.cursor = c - w.s_size; + if (!w.method) + return w.result; + var res = w.method(); + this.cursor = c - w.s_size; + if (res) + return w.result; + } + i = w.substring_i; + if (i < 0) + return 0; + } + }, + replace_s : function(c_bra, c_ket, s) { + var adjustment = s.length - (c_ket - c_bra), left = current + .substring(0, c_bra), right = current.substring(c_ket); + current = left + s + right; + this.limit += adjustment; + if (this.cursor >= c_ket) + this.cursor += adjustment; + else if (this.cursor > c_bra) + this.cursor = c_bra; + return adjustment; + }, + slice_check : function() { + if (this.bra < 0 || this.bra > this.ket || this.ket > this.limit + || this.limit > current.length) + throw ("faulty slice operation"); + }, + slice_from : function(s) { + this.slice_check(); + this.replace_s(this.bra, this.ket, s); + }, + slice_del : function() { + this.slice_from(""); + }, + insert : function(c_bra, c_ket, s) { + var adjustment = this.replace_s(c_bra, c_ket, s); + if (c_bra <= this.bra) + this.bra += adjustment; + if (c_bra <= this.ket) + this.ket += adjustment; + }, + slice_to : function() { + this.slice_check(); + return current.substring(this.bra, this.ket); + }, + eq_v_b : function(s) { + return this.eq_s_b(s.length, s); + } + }; + } + }; + + lunr.trimmerSupport = { + generateTrimmer: function(wordCharacters) { + var startRegex = new RegExp("^[^" + wordCharacters + "]+") + var endRegex = new RegExp("[^" + wordCharacters + "]+$") + + return function(token) { + // for lunr version 2 + if (typeof token.update === "function") { + return token.update(function (s) { + return s + .replace(startRegex, '') + .replace(endRegex, ''); + }) + } else { // for lunr version 1 + return token + .replace(startRegex, '') + .replace(endRegex, ''); + } + }; + } + } + } +})); diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.sv.js b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.sv.js new file mode 100644 index 0000000000000000000000000000000000000000..6a7d93202b2746319cec63c8efedbdb0da1bfadc --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.sv.js @@ -0,0 +1,256 @@ +/*! + * Lunr languages, `Swedish` language + * https://github.com/MihaiValentin/lunr-languages + * + * Copyright 2014, Mihai Valentin + * http://www.mozilla.org/MPL/ + */ +/*! + * based on + * Snowball JavaScript Library v0.3 + * http://code.google.com/p/urim/ + * http://snowball.tartarus.org/ + * + * Copyright 2010, Oleg Mazko + * http://www.mozilla.org/MPL/ + */ + +/** + * export the module via AMD, CommonJS or as a browser global + * Export code from https://github.com/umdjs/umd/blob/master/returnExports.js + */ +; +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(factory) + } else if (typeof exports === 'object') { + /** + * Node. Does not work with strict CommonJS, but + * only CommonJS-like environments that support module.exports, + * like Node. + */ + module.exports = factory() + } else { + // Browser globals (root is window) + factory()(root.lunr); + } +}(this, function() { + /** + * Just return a value to define the module export. + * This example returns an object, but the module + * can return a function as the exported value. + */ + return function(lunr) { + /* throw error if lunr is not yet included */ + if ('undefined' === typeof lunr) { + throw new Error('Lunr is not present. Please include / require Lunr before this script.'); + } + + /* throw error if lunr stemmer support is not yet included */ + if ('undefined' === typeof lunr.stemmerSupport) { + throw new Error('Lunr stemmer support is not present. Please include / require Lunr stemmer support before this script.'); + } + + /* register specific locale function */ + lunr.sv = function() { + this.pipeline.reset(); + this.pipeline.add( + lunr.sv.trimmer, + lunr.sv.stopWordFilter, + lunr.sv.stemmer + ); + + // for lunr version 2 + // this is necessary so that every searched word is also stemmed before + // in lunr <= 1 this is not needed, as it is done using the normal pipeline + if (this.searchPipeline) { + this.searchPipeline.reset(); + this.searchPipeline.add(lunr.sv.stemmer) + } + }; + + /* lunr trimmer function */ + lunr.sv.wordCharacters = "A-Za-z\xAA\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02B8\u02E0-\u02E4\u1D00-\u1D25\u1D2C-\u1D5C\u1D62-\u1D65\u1D6B-\u1D77\u1D79-\u1DBE\u1E00-\u1EFF\u2071\u207F\u2090-\u209C\u212A\u212B\u2132\u214E\u2160-\u2188\u2C60-\u2C7F\uA722-\uA787\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA7FF\uAB30-\uAB5A\uAB5C-\uAB64\uFB00-\uFB06\uFF21-\uFF3A\uFF41-\uFF5A"; + lunr.sv.trimmer = lunr.trimmerSupport.generateTrimmer(lunr.sv.wordCharacters); + + lunr.Pipeline.registerFunction(lunr.sv.trimmer, 'trimmer-sv'); + + /* lunr stemmer function */ + lunr.sv.stemmer = (function() { + /* create the wrapped stemmer object */ + var Among = lunr.stemmerSupport.Among, + SnowballProgram = lunr.stemmerSupport.SnowballProgram, + st = new function SwedishStemmer() { + var a_0 = [new Among("a", -1, 1), new Among("arna", 0, 1), + new Among("erna", 0, 1), new Among("heterna", 2, 1), + new Among("orna", 0, 1), new Among("ad", -1, 1), + new Among("e", -1, 1), new Among("ade", 6, 1), + new Among("ande", 6, 1), new Among("arne", 6, 1), + new Among("are", 6, 1), new Among("aste", 6, 1), + new Among("en", -1, 1), new Among("anden", 12, 1), + new Among("aren", 12, 1), new Among("heten", 12, 1), + new Among("ern", -1, 1), new Among("ar", -1, 1), + new Among("er", -1, 1), new Among("heter", 18, 1), + new Among("or", -1, 1), new Among("s", -1, 2), + new Among("as", 21, 1), new Among("arnas", 22, 1), + new Among("ernas", 22, 1), new Among("ornas", 22, 1), + new Among("es", 21, 1), new Among("ades", 26, 1), + new Among("andes", 26, 1), new Among("ens", 21, 1), + new Among("arens", 29, 1), new Among("hetens", 29, 1), + new Among("erns", 21, 1), new Among("at", -1, 1), + new Among("andet", -1, 1), new Among("het", -1, 1), + new Among("ast", -1, 1) + ], + a_1 = [new Among("dd", -1, -1), + new Among("gd", -1, -1), new Among("nn", -1, -1), + new Among("dt", -1, -1), new Among("gt", -1, -1), + new Among("kt", -1, -1), new Among("tt", -1, -1) + ], + a_2 = [ + new Among("ig", -1, 1), new Among("lig", 0, 1), + new Among("els", -1, 1), new Among("fullt", -1, 3), + new Among("l\u00F6st", -1, 2) + ], + g_v = [17, 65, 16, 1, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 24, 0, 32 + ], + g_s_ending = [119, 127, 149], + I_x, I_p1, sbp = new SnowballProgram(); + this.setCurrent = function(word) { + sbp.setCurrent(word); + }; + this.getCurrent = function() { + return sbp.getCurrent(); + }; + + function r_mark_regions() { + var v_1, c = sbp.cursor + 3; + I_p1 = sbp.limit; + if (0 <= c || c <= sbp.limit) { + I_x = c; + while (true) { + v_1 = sbp.cursor; + if (sbp.in_grouping(g_v, 97, 246)) { + sbp.cursor = v_1; + break; + } + sbp.cursor = v_1; + if (sbp.cursor >= sbp.limit) + return; + sbp.cursor++; + } + while (!sbp.out_grouping(g_v, 97, 246)) { + if (sbp.cursor >= sbp.limit) + return; + sbp.cursor++; + } + I_p1 = sbp.cursor; + if (I_p1 < I_x) + I_p1 = I_x; + } + } + + function r_main_suffix() { + var among_var, v_2 = sbp.limit_backward; + if (sbp.cursor >= I_p1) { + sbp.limit_backward = I_p1; + sbp.cursor = sbp.limit; + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_0, 37); + sbp.limit_backward = v_2; + if (among_var) { + sbp.bra = sbp.cursor; + switch (among_var) { + case 1: + sbp.slice_del(); + break; + case 2: + if (sbp.in_grouping_b(g_s_ending, 98, 121)) + sbp.slice_del(); + break; + } + } + } + } + + function r_consonant_pair() { + var v_1 = sbp.limit_backward; + if (sbp.cursor >= I_p1) { + sbp.limit_backward = I_p1; + sbp.cursor = sbp.limit; + if (sbp.find_among_b(a_1, 7)) { + sbp.cursor = sbp.limit; + sbp.ket = sbp.cursor; + if (sbp.cursor > sbp.limit_backward) { + sbp.bra = --sbp.cursor; + sbp.slice_del(); + } + } + sbp.limit_backward = v_1; + } + } + + function r_other_suffix() { + var among_var, v_2; + if (sbp.cursor >= I_p1) { + v_2 = sbp.limit_backward; + sbp.limit_backward = I_p1; + sbp.cursor = sbp.limit; + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_2, 5); + if (among_var) { + sbp.bra = sbp.cursor; + switch (among_var) { + case 1: + sbp.slice_del(); + break; + case 2: + sbp.slice_from("l\u00F6s"); + break; + case 3: + sbp.slice_from("full"); + break; + } + } + sbp.limit_backward = v_2; + } + } + this.stem = function() { + var v_1 = sbp.cursor; + r_mark_regions(); + sbp.limit_backward = v_1; + sbp.cursor = sbp.limit; + r_main_suffix(); + sbp.cursor = sbp.limit; + r_consonant_pair(); + sbp.cursor = sbp.limit; + r_other_suffix(); + return true; + } + }; + + /* and return a function that stems a word for the current locale */ + return function(token) { + // for lunr version 2 + if (typeof token.update === "function") { + return token.update(function(word) { + st.setCurrent(word); + st.stem(); + return st.getCurrent(); + }) + } else { // for lunr version <= 1 + st.setCurrent(token); + st.stem(); + return st.getCurrent(); + } + } + })(); + + lunr.Pipeline.registerFunction(lunr.sv.stemmer, 'stemmer-sv'); + + lunr.sv.stopWordFilter = lunr.generateStopWordFilter('alla allt att av blev bli blir blivit de dem den denna deras dess dessa det detta dig din dina ditt du där då efter ej eller en er era ert ett från för ha hade han hans har henne hennes hon honom hur här i icke ingen inom inte jag ju kan kunde man med mellan men mig min mina mitt mot mycket ni nu när någon något några och om oss på samma sedan sig sin sina sitta själv skulle som så sådan sådana sådant till under upp ut utan vad var vara varför varit varje vars vart vem vi vid vilka vilkas vilken vilket vår våra vårt än är åt över'.split(' ')); + + lunr.Pipeline.registerFunction(lunr.sv.stopWordFilter, 'stopWordFilter-sv'); + }; +})) \ No newline at end of file diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.ta.js b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.ta.js new file mode 100644 index 0000000000000000000000000000000000000000..1ffcfb58dc0bd2345ee00dfaed41fe5f28dc1e22 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.ta.js @@ -0,0 +1,123 @@ +/*! + * Lunr languages, `Tamil` language + * https://github.com/tvmani/lunr-languages + * + * Copyright 2021, Manikandan Venkatasubban + * http://www.mozilla.org/MPL/ + */ +/*! + * based on + * Snowball JavaScript Library v0.3 + * http://code.google.com/p/urim/ + * http://snowball.tartarus.org/ + * + * Copyright 2010, Oleg Mazko + * http://www.mozilla.org/MPL/ + */ + +/** + * export the module via AMD, CommonJS or as a browser global + * Export code from https://github.com/umdjs/umd/blob/master/returnExports.js + */ +; +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(factory) + } else if (typeof exports === 'object') { + /** + * Node. Does not work with strict CommonJS, but + * only CommonJS-like environments that support module.exports, + * like Node. + */ + module.exports = factory() + } else { + // Browser globals (root is window) + factory()(root.lunr); + } +}(this, function() { + /** + * Just return a value to define the module export. + * This example returns an object, but the module + * can return a function as the exported value. + */ + return function(lunr) { + /* throw error if lunr is not yet included */ + if ('undefined' === typeof lunr) { + throw new Error('Lunr is not present. Please include / require Lunr before this script.'); + } + + /* throw error if lunr stemmer support is not yet included */ + if ('undefined' === typeof lunr.stemmerSupport) { + throw new Error('Lunr stemmer support is not present. Please include / require Lunr stemmer support before this script.'); + } + + /* register specific locale function */ + lunr.ta = function() { + this.pipeline.reset(); + this.pipeline.add( + lunr.ta.trimmer, + lunr.ta.stopWordFilter, + lunr.ta.stemmer + ); + + // change the tokenizer for japanese one + // if (isLunr2) { // for lunr version 2.0.0 + // this.tokenizer = lunr.ta.tokenizer; + // } else { + // if (lunr.tokenizer) { // for lunr version 0.6.0 + // lunr.tokenizer = lunr.ta.tokenizer; + // } + // if (this.tokenizerFn) { // for lunr version 0.7.0 -> 1.0.0 + // this.tokenizerFn = lunr.ta.tokenizer; + // } + // } + + if (this.searchPipeline) { + this.searchPipeline.reset(); + this.searchPipeline.add(lunr.ta.stemmer) + } + }; + + /* lunr trimmer function */ + lunr.ta.wordCharacters = "\u0b80-\u0b89\u0b8a-\u0b8f\u0b90-\u0b99\u0b9a-\u0b9f\u0ba0-\u0ba9\u0baa-\u0baf\u0bb0-\u0bb9\u0bba-\u0bbf\u0bc0-\u0bc9\u0bca-\u0bcf\u0bd0-\u0bd9\u0bda-\u0bdf\u0be0-\u0be9\u0bea-\u0bef\u0bf0-\u0bf9\u0bfa-\u0bffa-zA-Za-zA-Z0-90-9"; + + lunr.ta.trimmer = lunr.trimmerSupport.generateTrimmer(lunr.ta.wordCharacters); + + lunr.Pipeline.registerFunction(lunr.ta.trimmer, 'trimmer-ta'); + /* lunr stop word filter */ + lunr.ta.stopWordFilter = lunr.generateStopWordFilter( + 'அங்கு அங்கே அது அதை அந்த அவர் அவர்கள் அவள் அவன் அவை ஆக ஆகவே ஆகையால் ஆதலால் ஆதலினால் ஆனாலும் ஆனால் இங்கு இங்கே இது இதை இந்த இப்படி இவர் இவர்கள் இவள் இவன் இவை இவ்வளவு உனக்கு உனது உன் உன்னால் எங்கு எங்கே எது எதை எந்த எப்படி எவர் எவர்கள் எவள் எவன் எவை எவ்வளவு எனக்கு எனது எனவே என் என்ன என்னால் ஏது ஏன் தனது தன்னால் தானே தான் நாங்கள் நாம் நான் நீ நீங்கள்'.split(' ')); + /* lunr stemmer function */ + lunr.ta.stemmer = (function() { + + return function(word) { + // for lunr version 2 + if (typeof word.update === "function") { + return word.update(function(word) { + return word; + }) + } else { // for lunr version <= 1 + return word; + } + + } + })(); + + var segmenter = lunr.wordcut; + segmenter.init(); + lunr.ta.tokenizer = function(obj) { + if (!arguments.length || obj == null || obj == undefined) return [] + if (Array.isArray(obj)) return obj.map(function(t) { + return isLunr2 ? new lunr.Token(t.toLowerCase()) : t.toLowerCase() + }); + + var str = obj.toString().toLowerCase().replace(/^\s+/, ''); + return segmenter.cut(str).split('|'); + } + + lunr.Pipeline.registerFunction(lunr.ta.stemmer, 'stemmer-ta'); + lunr.Pipeline.registerFunction(lunr.ta.stopWordFilter, 'stopWordFilter-ta'); + + }; +})) \ No newline at end of file diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.te.js b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.te.js new file mode 100644 index 0000000000000000000000000000000000000000..3d3cc07ffdb6faded2a221241dec93513592bf57 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.te.js @@ -0,0 +1,122 @@ +/*! + * Lunr languages, `Hindi` language + * https://github.com/MiKr13/lunr-languages + * + * Copyright 2023, India + * http://www.mozilla.org/MPL/ + */ +/*! + * based on + * Snowball JavaScript Library v0.3 + * http://code.google.com/p/urim/ + * http://snowball.tartarus.org/ + * + * Copyright 2010, Oleg Mazko + * http://www.mozilla.org/MPL/ + */ + +/** + * export the module via AMD, CommonJS or as a browser global + * Export code from https://github.com/umdjs/umd/blob/master/returnExports.js + */ +; +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(factory) + } else if (typeof exports === 'object') { + /** + * Node. Does not work with strict CommonJS, but + * only CommonJS-like environments that support module.exports, + * like Node. + */ + module.exports = factory() + } else { + // Browser globals (root is window) + factory()(root.lunr); + } +}(this, function() { + /** + * Just return a value to define the module export. + * This example returns an object, but the module + * can return a function as the exported value. + */ + return function(lunr) { + /* throw error if lunr is not yet included */ + if ('undefined' === typeof lunr) { + throw new Error('Lunr is not present. Please include / require Lunr before this script.'); + } + + /* throw error if lunr stemmer support is not yet included */ + if ('undefined' === typeof lunr.stemmerSupport) { + throw new Error('Lunr stemmer support is not present. Please include / require Lunr stemmer support before this script.'); + } + + /* register specific locale function */ + lunr.te = function() { + this.pipeline.reset(); + this.pipeline.add( + lunr.te.trimmer, + lunr.te.stopWordFilter, + lunr.te.stemmer + ); + + // change the tokenizer for japanese one + // if (isLunr2) { // for lunr version 2.0.0 + // this.tokenizer = lunr.hi.tokenizer; + // } else { + // if (lunr.tokenizer) { // for lunr version 0.6.0 + // lunr.tokenizer = lunr.hi.tokenizer; + // } + // if (this.tokenizerFn) { // for lunr version 0.7.0 -> 1.0.0 + // this.tokenizerFn = lunr.hi.tokenizer; + // } + // } + + if (this.searchPipeline) { + this.searchPipeline.reset(); + this.searchPipeline.add(lunr.te.stemmer) + } + }; + + /* lunr trimmer function */ + lunr.te.wordCharacters = "\u0C00-\u0C04\u0C05-\u0C14\u0C15-\u0C39\u0C3E-\u0C4C\u0C55-\u0C56\u0C58-\u0C5A\u0C60-\u0C61\u0C62-\u0C63\u0C66-\u0C6F\u0C78-\u0C7F\u0C3C\u0C3D\u0C4D\u0C5D\u0C77\u0C64\u0C65"; + lunr.te.trimmer = lunr.trimmerSupport.generateTrimmer(lunr.te.wordCharacters); + + lunr.Pipeline.registerFunction(lunr.te.trimmer, 'trimmer-te'); + /* lunr stop word filter */ + lunr.te.stopWordFilter = lunr.generateStopWordFilter( + 'అందరూ అందుబాటులో అడగండి అడగడం అడ్డంగా అనుగుణంగా అనుమతించు అనుమతిస్తుంది అయితే ఇప్పటికే ఉన్నారు ఎక్కడైనా ఎప్పుడు ఎవరైనా ఎవరో ఏ ఏదైనా ఏమైనప్పటికి ఒక ఒకరు కనిపిస్తాయి కాదు కూడా గా గురించి చుట్టూ చేయగలిగింది తగిన తర్వాత దాదాపు దూరంగా నిజంగా పై ప్రకారం ప్రక్కన మధ్య మరియు మరొక మళ్ళీ మాత్రమే మెచ్చుకో వద్ద వెంట వేరుగా వ్యతిరేకంగా సంబంధం'.split(' ')); + /* lunr stemmer function */ + lunr.te.stemmer = (function() { + + return function(word) { + // for lunr version 2 + if (typeof word.update === "function") { + return word.update(function(word) { + return word; + }) + } else { // for lunr version <= 1 + return word; + } + + } + })(); + + var segmenter = lunr.wordcut; + segmenter.init(); + lunr.te.tokenizer = function(obj) { + if (!arguments.length || obj == null || obj == undefined) return [] + if (Array.isArray(obj)) return obj.map(function(t) { + return isLunr2 ? new lunr.Token(t.toLowerCase()) : t.toLowerCase() + }); + + var str = obj.toString().toLowerCase().replace(/^\s+/, ''); + return segmenter.cut(str).split('|'); + } + + lunr.Pipeline.registerFunction(lunr.te.stemmer, 'stemmer-te'); + lunr.Pipeline.registerFunction(lunr.te.stopWordFilter, 'stopWordFilter-te'); + + }; +})) \ No newline at end of file diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.th.js b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.th.js new file mode 100644 index 0000000000000000000000000000000000000000..d21d1771e3992fdabd54ab4ed7f31b2595548ea1 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.th.js @@ -0,0 +1,99 @@ +/*! + * Lunr languages, `Thai` language + * https://github.com/MihaiValentin/lunr-languages + * + * Copyright 2017, Keerati Thiwanruk + * http://www.mozilla.org/MPL/ + */ +/*! + * based on + * Snowball JavaScript Library v0.3 + * http://code.google.com/p/urim/ + * http://snowball.tartarus.org/ + * + * Copyright 2010, Oleg Mazko + * http://www.mozilla.org/MPL/ + */ + +/** + * export the module via AMD, CommonJS or as a browser global + * Export code from https://github.com/umdjs/umd/blob/master/returnExports.js + */ +; +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(factory) + } else if (typeof exports === 'object') { + /** + * Node. Does not work with strict CommonJS, but + * only CommonJS-like environments that support module.exports, + * like Node. + */ + module.exports = factory() + } else { + // Browser globals (root is window) + factory()(root.lunr); + } +}(this, function() { + /** + * Just return a value to define the module export. + * This example returns an object, but the module + * can return a function as the exported value. + */ + return function(lunr) { + /* throw error if lunr is not yet included */ + if ('undefined' === typeof lunr) { + throw new Error('Lunr is not present. Please include / require Lunr before this script.'); + } + + /* throw error if lunr stemmer support is not yet included */ + if ('undefined' === typeof lunr.stemmerSupport) { + throw new Error('Lunr stemmer support is not present. Please include / require Lunr stemmer support before this script.'); + } + + /* + Thai tokenization is the same to Japanense, which does not take into account spaces. + So, it uses the same logic to assign tokenization function due to different Lunr versions. + */ + var isLunr2 = lunr.version[0] == "2"; + + /* register specific locale function */ + lunr.th = function() { + this.pipeline.reset(); + this.pipeline.add( + /*lunr.th.stopWordFilter,*/ + lunr.th.trimmer + ); + + if (isLunr2) { // for lunr version 2.0.0 + this.tokenizer = lunr.th.tokenizer; + } else { + if (lunr.tokenizer) { // for lunr version 0.6.0 + lunr.tokenizer = lunr.th.tokenizer; + } + if (this.tokenizerFn) { // for lunr version 0.7.0 -> 1.0.0 + this.tokenizerFn = lunr.th.tokenizer; + } + } + }; + + /* lunr trimmer function */ + lunr.th.wordCharacters = "[\u0e00-\u0e7f]"; + lunr.th.trimmer = lunr.trimmerSupport.generateTrimmer(lunr.th.wordCharacters); + lunr.Pipeline.registerFunction(lunr.th.trimmer, 'trimmer-th'); + + var segmenter = lunr.wordcut; + segmenter.init(); + lunr.th.tokenizer = function(obj) { + //console.log(obj); + if (!arguments.length || obj == null || obj == undefined) return [] + if (Array.isArray(obj)) return obj.map(function(t) { + return isLunr2 ? new lunr.Token(t) : t + }) + + var str = obj.toString().replace(/^\s+/, ''); + return segmenter.cut(str).split('|'); + } + }; +})) \ No newline at end of file diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.tr.js b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.tr.js new file mode 100644 index 0000000000000000000000000000000000000000..5b4bad814c01ca6523b410629665efd07f4b2474 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.tr.js @@ -0,0 +1,1087 @@ +/*! + * Lunr languages, `Turkish` language + * https://github.com/MihaiValentin/lunr-languages + * + * Copyright 2014, Mihai Valentin + * http://www.mozilla.org/MPL/ + */ +/*! + * based on + * Snowball JavaScript Library v0.3 + * http://code.google.com/p/urim/ + * http://snowball.tartarus.org/ + * + * Copyright 2010, Oleg Mazko + * http://www.mozilla.org/MPL/ + */ + +/** + * export the module via AMD, CommonJS or as a browser global + * Export code from https://github.com/umdjs/umd/blob/master/returnExports.js + */ +; +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(factory) + } else if (typeof exports === 'object') { + /** + * Node. Does not work with strict CommonJS, but + * only CommonJS-like environments that support module.exports, + * like Node. + */ + module.exports = factory() + } else { + // Browser globals (root is window) + factory()(root.lunr); + } +}(this, function() { + /** + * Just return a value to define the module export. + * This example returns an object, but the module + * can return a function as the exported value. + */ + return function(lunr) { + /* throw error if lunr is not yet included */ + if ('undefined' === typeof lunr) { + throw new Error('Lunr is not present. Please include / require Lunr before this script.'); + } + + /* throw error if lunr stemmer support is not yet included */ + if ('undefined' === typeof lunr.stemmerSupport) { + throw new Error('Lunr stemmer support is not present. Please include / require Lunr stemmer support before this script.'); + } + + /* register specific locale function */ + lunr.tr = function() { + this.pipeline.reset(); + this.pipeline.add( + lunr.tr.trimmer, + lunr.tr.stopWordFilter, + lunr.tr.stemmer + ); + + // for lunr version 2 + // this is necessary so that every searched word is also stemmed before + // in lunr <= 1 this is not needed, as it is done using the normal pipeline + if (this.searchPipeline) { + this.searchPipeline.reset(); + this.searchPipeline.add(lunr.tr.stemmer) + } + }; + + /* lunr trimmer function */ + lunr.tr.wordCharacters = "A-Za-z\xAA\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02B8\u02E0-\u02E4\u1D00-\u1D25\u1D2C-\u1D5C\u1D62-\u1D65\u1D6B-\u1D77\u1D79-\u1DBE\u1E00-\u1EFF\u2071\u207F\u2090-\u209C\u212A\u212B\u2132\u214E\u2160-\u2188\u2C60-\u2C7F\uA722-\uA787\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA7FF\uAB30-\uAB5A\uAB5C-\uAB64\uFB00-\uFB06\uFF21-\uFF3A\uFF41-\uFF5A"; + lunr.tr.trimmer = lunr.trimmerSupport.generateTrimmer(lunr.tr.wordCharacters); + + lunr.Pipeline.registerFunction(lunr.tr.trimmer, 'trimmer-tr'); + + /* lunr stemmer function */ + lunr.tr.stemmer = (function() { + /* create the wrapped stemmer object */ + var Among = lunr.stemmerSupport.Among, + SnowballProgram = lunr.stemmerSupport.SnowballProgram, + st = new function TurkishStemmer() { + var a_0 = [new Among("m", -1, -1), new Among("n", -1, -1), + new Among("miz", -1, -1), new Among("niz", -1, -1), + new Among("muz", -1, -1), new Among("nuz", -1, -1), + new Among("m\u00FCz", -1, -1), new Among("n\u00FCz", -1, -1), + new Among("m\u0131z", -1, -1), new Among("n\u0131z", -1, -1) + ], + a_1 = [ + new Among("leri", -1, -1), new Among("lar\u0131", -1, -1) + ], + a_2 = [ + new Among("ni", -1, -1), new Among("nu", -1, -1), + new Among("n\u00FC", -1, -1), new Among("n\u0131", -1, -1) + ], + a_3 = [ + new Among("in", -1, -1), new Among("un", -1, -1), + new Among("\u00FCn", -1, -1), new Among("\u0131n", -1, -1) + ], + a_4 = [ + new Among("a", -1, -1), new Among("e", -1, -1) + ], + a_5 = [ + new Among("na", -1, -1), new Among("ne", -1, -1) + ], + a_6 = [ + new Among("da", -1, -1), new Among("ta", -1, -1), + new Among("de", -1, -1), new Among("te", -1, -1) + ], + a_7 = [ + new Among("nda", -1, -1), new Among("nde", -1, -1) + ], + a_8 = [ + new Among("dan", -1, -1), new Among("tan", -1, -1), + new Among("den", -1, -1), new Among("ten", -1, -1) + ], + a_9 = [ + new Among("ndan", -1, -1), new Among("nden", -1, -1) + ], + a_10 = [ + new Among("la", -1, -1), new Among("le", -1, -1) + ], + a_11 = [ + new Among("ca", -1, -1), new Among("ce", -1, -1) + ], + a_12 = [ + new Among("im", -1, -1), new Among("um", -1, -1), + new Among("\u00FCm", -1, -1), new Among("\u0131m", -1, -1) + ], + a_13 = [ + new Among("sin", -1, -1), new Among("sun", -1, -1), + new Among("s\u00FCn", -1, -1), new Among("s\u0131n", -1, -1) + ], + a_14 = [ + new Among("iz", -1, -1), new Among("uz", -1, -1), + new Among("\u00FCz", -1, -1), new Among("\u0131z", -1, -1) + ], + a_15 = [ + new Among("siniz", -1, -1), new Among("sunuz", -1, -1), + new Among("s\u00FCn\u00FCz", -1, -1), + new Among("s\u0131n\u0131z", -1, -1) + ], + a_16 = [ + new Among("lar", -1, -1), new Among("ler", -1, -1) + ], + a_17 = [ + new Among("niz", -1, -1), new Among("nuz", -1, -1), + new Among("n\u00FCz", -1, -1), new Among("n\u0131z", -1, -1) + ], + a_18 = [ + new Among("dir", -1, -1), new Among("tir", -1, -1), + new Among("dur", -1, -1), new Among("tur", -1, -1), + new Among("d\u00FCr", -1, -1), new Among("t\u00FCr", -1, -1), + new Among("d\u0131r", -1, -1), new Among("t\u0131r", -1, -1) + ], + a_19 = [ + new Among("cas\u0131na", -1, -1), new Among("cesine", -1, -1) + ], + a_20 = [ + new Among("di", -1, -1), new Among("ti", -1, -1), + new Among("dik", -1, -1), new Among("tik", -1, -1), + new Among("duk", -1, -1), new Among("tuk", -1, -1), + new Among("d\u00FCk", -1, -1), new Among("t\u00FCk", -1, -1), + new Among("d\u0131k", -1, -1), new Among("t\u0131k", -1, -1), + new Among("dim", -1, -1), new Among("tim", -1, -1), + new Among("dum", -1, -1), new Among("tum", -1, -1), + new Among("d\u00FCm", -1, -1), new Among("t\u00FCm", -1, -1), + new Among("d\u0131m", -1, -1), new Among("t\u0131m", -1, -1), + new Among("din", -1, -1), new Among("tin", -1, -1), + new Among("dun", -1, -1), new Among("tun", -1, -1), + new Among("d\u00FCn", -1, -1), new Among("t\u00FCn", -1, -1), + new Among("d\u0131n", -1, -1), new Among("t\u0131n", -1, -1), + new Among("du", -1, -1), new Among("tu", -1, -1), + new Among("d\u00FC", -1, -1), new Among("t\u00FC", -1, -1), + new Among("d\u0131", -1, -1), new Among("t\u0131", -1, -1) + ], + a_21 = [ + new Among("sa", -1, -1), new Among("se", -1, -1), + new Among("sak", -1, -1), new Among("sek", -1, -1), + new Among("sam", -1, -1), new Among("sem", -1, -1), + new Among("san", -1, -1), new Among("sen", -1, -1) + ], + a_22 = [ + new Among("mi\u015F", -1, -1), new Among("mu\u015F", -1, -1), + new Among("m\u00FC\u015F", -1, -1), + new Among("m\u0131\u015F", -1, -1) + ], + a_23 = [new Among("b", -1, 1), + new Among("c", -1, 2), new Among("d", -1, 3), + new Among("\u011F", -1, 4) + ], + g_vowel = [17, 65, 16, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 8, 0, 0, 0, 0, 0, 0, 1 + ], + g_U = [ + 1, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, + 0, 0, 0, 1 + ], + g_vowel1 = [1, 64, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 + ], + g_vowel2 = [17, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 130 + ], + g_vowel3 = [1, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 1 + ], + g_vowel4 = [17], + g_vowel5 = [65], + g_vowel6 = [65], + B_c_s_n_s, I_strlen, g_habr = [ + ["a", g_vowel1, 97, 305], + ["e", g_vowel2, 101, 252], + ["\u0131", g_vowel3, 97, 305], + ["i", g_vowel4, 101, 105], + ["o", g_vowel5, 111, 117], + ["\u00F6", g_vowel6, 246, 252], + ["u", g_vowel5, 111, 117] + ], + sbp = new SnowballProgram(); + this.setCurrent = function(word) { + sbp.setCurrent(word); + }; + this.getCurrent = function() { + return sbp.getCurrent(); + }; + + function habr1(g_v, n1, n2) { + while (true) { + var v_1 = sbp.limit - sbp.cursor; + if (sbp.in_grouping_b(g_v, n1, n2)) { + sbp.cursor = sbp.limit - v_1; + break; + } + sbp.cursor = sbp.limit - v_1; + if (sbp.cursor <= sbp.limit_backward) + return false; + sbp.cursor--; + } + return true; + } + + function r_check_vowel_harmony() { + var v_1, v_2; + v_1 = sbp.limit - sbp.cursor; + habr1(g_vowel, 97, 305); + for (var i = 0; i < g_habr.length; i++) { + v_2 = sbp.limit - sbp.cursor; + var habr = g_habr[i]; + if (sbp.eq_s_b(1, habr[0]) && habr1(habr[1], habr[2], habr[3])) { + sbp.cursor = sbp.limit - v_1; + return true; + } + sbp.cursor = sbp.limit - v_2; + } + sbp.cursor = sbp.limit - v_2; + if (!sbp.eq_s_b(1, "\u00FC") || !habr1(g_vowel6, 246, 252)) + return false; + sbp.cursor = sbp.limit - v_1; + return true; + } + + function habr2(f1, f2) { + var v_1 = sbp.limit - sbp.cursor, + v_2; + if (f1()) { + sbp.cursor = sbp.limit - v_1; + if (sbp.cursor > sbp.limit_backward) { + sbp.cursor--; + v_2 = sbp.limit - sbp.cursor; + if (f2()) { + sbp.cursor = sbp.limit - v_2; + return true; + } + } + } + sbp.cursor = sbp.limit - v_1; + if (f1()) { + sbp.cursor = sbp.limit - v_1; + return false; + } + sbp.cursor = sbp.limit - v_1; + if (sbp.cursor <= sbp.limit_backward) + return false; + sbp.cursor--; + if (!f2()) + return false; + sbp.cursor = sbp.limit - v_1; + return true; + } + + function habr3(f1) { + return habr2(f1, function() { + return sbp.in_grouping_b(g_vowel, 97, 305); + }); + } + + function r_mark_suffix_with_optional_n_consonant() { + return habr3(function() { + return sbp.eq_s_b(1, "n"); + }); + } + + function r_mark_suffix_with_optional_s_consonant() { + return habr3(function() { + return sbp.eq_s_b(1, "s"); + }); + } + + function r_mark_suffix_with_optional_y_consonant() { + return habr3(function() { + return sbp.eq_s_b(1, "y"); + }); + } + + function r_mark_suffix_with_optional_U_vowel() { + return habr2(function() { + return sbp.in_grouping_b(g_U, 105, 305); + }, function() { + return sbp.out_grouping_b(g_vowel, 97, 305); + }); + } + + function r_mark_possessives() { + return sbp.find_among_b(a_0, 10) && + r_mark_suffix_with_optional_U_vowel(); + } + + function r_mark_sU() { + return r_check_vowel_harmony() && sbp.in_grouping_b(g_U, 105, 305) && + r_mark_suffix_with_optional_s_consonant(); + } + + function r_mark_lArI() { + return sbp.find_among_b(a_1, 2); + } + + function r_mark_yU() { + return r_check_vowel_harmony() && sbp.in_grouping_b(g_U, 105, 305) && + r_mark_suffix_with_optional_y_consonant(); + } + + function r_mark_nU() { + return r_check_vowel_harmony() && sbp.find_among_b(a_2, 4); + } + + function r_mark_nUn() { + return r_check_vowel_harmony() && sbp.find_among_b(a_3, 4) && + r_mark_suffix_with_optional_n_consonant(); + } + + function r_mark_yA() { + return r_check_vowel_harmony() && sbp.find_among_b(a_4, 2) && + r_mark_suffix_with_optional_y_consonant(); + } + + function r_mark_nA() { + return r_check_vowel_harmony() && sbp.find_among_b(a_5, 2); + } + + function r_mark_DA() { + return r_check_vowel_harmony() && sbp.find_among_b(a_6, 4); + } + + function r_mark_ndA() { + return r_check_vowel_harmony() && sbp.find_among_b(a_7, 2); + } + + function r_mark_DAn() { + return r_check_vowel_harmony() && sbp.find_among_b(a_8, 4); + } + + function r_mark_ndAn() { + return r_check_vowel_harmony() && sbp.find_among_b(a_9, 2); + } + + function r_mark_ylA() { + return r_check_vowel_harmony() && sbp.find_among_b(a_10, 2) && + r_mark_suffix_with_optional_y_consonant(); + } + + function r_mark_ki() { + return sbp.eq_s_b(2, "ki"); + } + + function r_mark_ncA() { + return r_check_vowel_harmony() && sbp.find_among_b(a_11, 2) && + r_mark_suffix_with_optional_n_consonant(); + } + + function r_mark_yUm() { + return r_check_vowel_harmony() && sbp.find_among_b(a_12, 4) && + r_mark_suffix_with_optional_y_consonant(); + } + + function r_mark_sUn() { + return r_check_vowel_harmony() && sbp.find_among_b(a_13, 4); + } + + function r_mark_yUz() { + return r_check_vowel_harmony() && sbp.find_among_b(a_14, 4) && + r_mark_suffix_with_optional_y_consonant(); + } + + function r_mark_sUnUz() { + return sbp.find_among_b(a_15, 4); + } + + function r_mark_lAr() { + return r_check_vowel_harmony() && sbp.find_among_b(a_16, 2); + } + + function r_mark_nUz() { + return r_check_vowel_harmony() && sbp.find_among_b(a_17, 4); + } + + function r_mark_DUr() { + return r_check_vowel_harmony() && sbp.find_among_b(a_18, 8); + } + + function r_mark_cAsInA() { + return sbp.find_among_b(a_19, 2); + } + + function r_mark_yDU() { + return r_check_vowel_harmony() && sbp.find_among_b(a_20, 32) && + r_mark_suffix_with_optional_y_consonant(); + } + + function r_mark_ysA() { + return sbp.find_among_b(a_21, 8) && + r_mark_suffix_with_optional_y_consonant(); + } + + function r_mark_ymUs_() { + return r_check_vowel_harmony() && sbp.find_among_b(a_22, 4) && + r_mark_suffix_with_optional_y_consonant(); + } + + function r_mark_yken() { + return sbp.eq_s_b(3, "ken") && + r_mark_suffix_with_optional_y_consonant(); + } + + function habr4() { + var v_1 = sbp.limit - sbp.cursor; + if (!r_mark_ymUs_()) { + sbp.cursor = sbp.limit - v_1; + if (!r_mark_yDU()) { + sbp.cursor = sbp.limit - v_1; + if (!r_mark_ysA()) { + sbp.cursor = sbp.limit - v_1; + if (!r_mark_yken()) + return true; + } + } + } + return false; + } + + function habr5() { + if (r_mark_cAsInA()) { + var v_1 = sbp.limit - sbp.cursor; + if (!r_mark_sUnUz()) { + sbp.cursor = sbp.limit - v_1; + if (!r_mark_lAr()) { + sbp.cursor = sbp.limit - v_1; + if (!r_mark_yUm()) { + sbp.cursor = sbp.limit - v_1; + if (!r_mark_sUn()) { + sbp.cursor = sbp.limit - v_1; + if (!r_mark_yUz()) + sbp.cursor = sbp.limit - v_1; + } + } + } + } + if (r_mark_ymUs_()) + return false; + } + return true; + } + + function habr6() { + if (r_mark_lAr()) { + sbp.bra = sbp.cursor; + sbp.slice_del(); + var v_1 = sbp.limit - sbp.cursor; + sbp.ket = sbp.cursor; + if (!r_mark_DUr()) { + sbp.cursor = sbp.limit - v_1; + if (!r_mark_yDU()) { + sbp.cursor = sbp.limit - v_1; + if (!r_mark_ysA()) { + sbp.cursor = sbp.limit - v_1; + if (!r_mark_ymUs_()) + sbp.cursor = sbp.limit - v_1; + } + } + } + B_c_s_n_s = false; + return false; + } + return true; + } + + function habr7() { + if (!r_mark_nUz()) + return true; + var v_1 = sbp.limit - sbp.cursor; + if (!r_mark_yDU()) { + sbp.cursor = sbp.limit - v_1; + if (!r_mark_ysA()) + return true; + } + return false; + } + + function habr8() { + var v_1 = sbp.limit - sbp.cursor, + v_2; + if (!r_mark_sUnUz()) { + sbp.cursor = sbp.limit - v_1; + if (!r_mark_yUz()) { + sbp.cursor = sbp.limit - v_1; + if (!r_mark_sUn()) { + sbp.cursor = sbp.limit - v_1; + if (!r_mark_yUm()) + return true; + } + } + } + sbp.bra = sbp.cursor; + sbp.slice_del(); + v_2 = sbp.limit - sbp.cursor; + sbp.ket = sbp.cursor; + if (!r_mark_ymUs_()) + sbp.cursor = sbp.limit - v_2; + return false; + } + + function r_stem_nominal_verb_suffixes() { + var v_1 = sbp.limit - sbp.cursor, + v_2; + sbp.ket = sbp.cursor; + B_c_s_n_s = true; + if (habr4()) { + sbp.cursor = sbp.limit - v_1; + if (habr5()) { + sbp.cursor = sbp.limit - v_1; + if (habr6()) { + sbp.cursor = sbp.limit - v_1; + if (habr7()) { + sbp.cursor = sbp.limit - v_1; + if (habr8()) { + sbp.cursor = sbp.limit - v_1; + if (!r_mark_DUr()) + return; + sbp.bra = sbp.cursor; + sbp.slice_del(); + sbp.ket = sbp.cursor; + v_2 = sbp.limit - sbp.cursor; + if (!r_mark_sUnUz()) { + sbp.cursor = sbp.limit - v_2; + if (!r_mark_lAr()) { + sbp.cursor = sbp.limit - v_2; + if (!r_mark_yUm()) { + sbp.cursor = sbp.limit - v_2; + if (!r_mark_sUn()) { + sbp.cursor = sbp.limit - v_2; + if (!r_mark_yUz()) + sbp.cursor = sbp.limit - v_2; + } + } + } + } + if (!r_mark_ymUs_()) + sbp.cursor = sbp.limit - v_2; + } + } + } + } + } + sbp.bra = sbp.cursor; + sbp.slice_del(); + } + + function r_stem_suffix_chain_before_ki() { + var v_1, v_2, v_3, v_4; + sbp.ket = sbp.cursor; + if (r_mark_ki()) { + v_1 = sbp.limit - sbp.cursor; + if (r_mark_DA()) { + sbp.bra = sbp.cursor; + sbp.slice_del(); + v_2 = sbp.limit - sbp.cursor; + sbp.ket = sbp.cursor; + if (r_mark_lAr()) { + sbp.bra = sbp.cursor; + sbp.slice_del(); + r_stem_suffix_chain_before_ki(); + } else { + sbp.cursor = sbp.limit - v_2; + if (r_mark_possessives()) { + sbp.bra = sbp.cursor; + sbp.slice_del(); + sbp.ket = sbp.cursor; + if (r_mark_lAr()) { + sbp.bra = sbp.cursor; + sbp.slice_del(); + r_stem_suffix_chain_before_ki(); + } + } + } + return true; + } + sbp.cursor = sbp.limit - v_1; + if (r_mark_nUn()) { + sbp.bra = sbp.cursor; + sbp.slice_del(); + sbp.ket = sbp.cursor; + v_3 = sbp.limit - sbp.cursor; + if (r_mark_lArI()) { + sbp.bra = sbp.cursor; + sbp.slice_del(); + } else { + sbp.cursor = sbp.limit - v_3; + sbp.ket = sbp.cursor; + if (!r_mark_possessives()) { + sbp.cursor = sbp.limit - v_3; + if (!r_mark_sU()) { + sbp.cursor = sbp.limit - v_3; + if (!r_stem_suffix_chain_before_ki()) + return true; + } + } + sbp.bra = sbp.cursor; + sbp.slice_del(); + sbp.ket = sbp.cursor; + if (r_mark_lAr()) { + sbp.bra = sbp.cursor; + sbp.slice_del(); + r_stem_suffix_chain_before_ki() + } + } + return true; + } + sbp.cursor = sbp.limit - v_1; + if (r_mark_ndA()) { + v_4 = sbp.limit - sbp.cursor; + if (r_mark_lArI()) { + sbp.bra = sbp.cursor; + sbp.slice_del(); + } else { + sbp.cursor = sbp.limit - v_4; + if (r_mark_sU()) { + sbp.bra = sbp.cursor; + sbp.slice_del(); + sbp.ket = sbp.cursor; + if (r_mark_lAr()) { + sbp.bra = sbp.cursor; + sbp.slice_del(); + r_stem_suffix_chain_before_ki(); + } + } else { + sbp.cursor = sbp.limit - v_4; + if (!r_stem_suffix_chain_before_ki()) + return false; + } + } + return true; + } + } + return false; + } + + function habr9(v_1) { + sbp.ket = sbp.cursor; + if (!r_mark_ndA()) { + sbp.cursor = sbp.limit - v_1; + if (!r_mark_nA()) + return false; + } + var v_2 = sbp.limit - sbp.cursor; + if (r_mark_lArI()) { + sbp.bra = sbp.cursor; + sbp.slice_del(); + } else { + sbp.cursor = sbp.limit - v_2; + if (r_mark_sU()) { + sbp.bra = sbp.cursor; + sbp.slice_del(); + sbp.ket = sbp.cursor; + if (r_mark_lAr()) { + sbp.bra = sbp.cursor; + sbp.slice_del(); + r_stem_suffix_chain_before_ki(); + } + } else { + sbp.cursor = sbp.limit - v_2; + if (!r_stem_suffix_chain_before_ki()) + return false; + } + } + return true; + } + + function habr10(v_1) { + sbp.ket = sbp.cursor; + if (!r_mark_ndAn()) { + sbp.cursor = sbp.limit - v_1; + if (!r_mark_nU()) + return false; + } + var v_2 = sbp.limit - sbp.cursor; + if (!r_mark_sU()) { + sbp.cursor = sbp.limit - v_2; + if (!r_mark_lArI()) + return false; + } + sbp.bra = sbp.cursor; + sbp.slice_del(); + sbp.ket = sbp.cursor; + if (r_mark_lAr()) { + sbp.bra = sbp.cursor; + sbp.slice_del(); + r_stem_suffix_chain_before_ki(); + } + return true; + } + + function habr11() { + var v_1 = sbp.limit - sbp.cursor, + v_2; + sbp.ket = sbp.cursor; + if (!r_mark_nUn()) { + sbp.cursor = sbp.limit - v_1; + if (!r_mark_ylA()) + return false; + } + sbp.bra = sbp.cursor; + sbp.slice_del(); + v_2 = sbp.limit - sbp.cursor; + sbp.ket = sbp.cursor; + if (r_mark_lAr()) { + sbp.bra = sbp.cursor; + sbp.slice_del(); + if (r_stem_suffix_chain_before_ki()) + return true; + } + sbp.cursor = sbp.limit - v_2; + sbp.ket = sbp.cursor; + if (!r_mark_possessives()) { + sbp.cursor = sbp.limit - v_2; + if (!r_mark_sU()) { + sbp.cursor = sbp.limit - v_2; + if (!r_stem_suffix_chain_before_ki()) + return true; + } + } + sbp.bra = sbp.cursor; + sbp.slice_del(); + sbp.ket = sbp.cursor; + if (r_mark_lAr()) { + sbp.bra = sbp.cursor; + sbp.slice_del(); + r_stem_suffix_chain_before_ki(); + } + return true; + } + + function habr12() { + var v_1 = sbp.limit - sbp.cursor, + v_2, v_3; + sbp.ket = sbp.cursor; + if (!r_mark_DA()) { + sbp.cursor = sbp.limit - v_1; + if (!r_mark_yU()) { + sbp.cursor = sbp.limit - v_1; + if (!r_mark_yA()) + return false; + } + } + sbp.bra = sbp.cursor; + sbp.slice_del(); + sbp.ket = sbp.cursor; + v_2 = sbp.limit - sbp.cursor; + if (r_mark_possessives()) { + sbp.bra = sbp.cursor; + sbp.slice_del(); + v_3 = sbp.limit - sbp.cursor; + sbp.ket = sbp.cursor; + if (!r_mark_lAr()) + sbp.cursor = sbp.limit - v_3; + } else { + sbp.cursor = sbp.limit - v_2; + if (!r_mark_lAr()) + return true; + } + sbp.bra = sbp.cursor; + sbp.slice_del(); + sbp.ket = sbp.cursor; + r_stem_suffix_chain_before_ki(); + return true; + } + + function r_stem_noun_suffixes() { + var v_1 = sbp.limit - sbp.cursor, + v_2, v_3; + sbp.ket = sbp.cursor; + if (r_mark_lAr()) { + sbp.bra = sbp.cursor; + sbp.slice_del(); + r_stem_suffix_chain_before_ki(); + return; + } + sbp.cursor = sbp.limit - v_1; + sbp.ket = sbp.cursor; + if (r_mark_ncA()) { + sbp.bra = sbp.cursor; + sbp.slice_del(); + v_2 = sbp.limit - sbp.cursor; + sbp.ket = sbp.cursor; + if (r_mark_lArI()) { + sbp.bra = sbp.cursor; + sbp.slice_del(); + } else { + sbp.cursor = sbp.limit - v_2; + sbp.ket = sbp.cursor; + if (!r_mark_possessives()) { + sbp.cursor = sbp.limit - v_2; + if (!r_mark_sU()) { + sbp.cursor = sbp.limit - v_2; + sbp.ket = sbp.cursor; + if (!r_mark_lAr()) + return; + sbp.bra = sbp.cursor; + sbp.slice_del(); + if (!r_stem_suffix_chain_before_ki()) + return; + } + } + sbp.bra = sbp.cursor; + sbp.slice_del(); + sbp.ket = sbp.cursor; + if (r_mark_lAr()) { + sbp.bra = sbp.cursor; + sbp.slice_del(); + r_stem_suffix_chain_before_ki(); + } + } + return; + } + sbp.cursor = sbp.limit - v_1; + if (habr9(v_1)) + return; + sbp.cursor = sbp.limit - v_1; + if (habr10(v_1)) + return; + sbp.cursor = sbp.limit - v_1; + sbp.ket = sbp.cursor; + if (r_mark_DAn()) { + sbp.bra = sbp.cursor; + sbp.slice_del(); + sbp.ket = sbp.cursor; + v_3 = sbp.limit - sbp.cursor; + if (r_mark_possessives()) { + sbp.bra = sbp.cursor; + sbp.slice_del(); + sbp.ket = sbp.cursor; + if (r_mark_lAr()) { + sbp.bra = sbp.cursor; + sbp.slice_del(); + r_stem_suffix_chain_before_ki(); + } + } else { + sbp.cursor = sbp.limit - v_3; + if (r_mark_lAr()) { + sbp.bra = sbp.cursor; + sbp.slice_del(); + r_stem_suffix_chain_before_ki(); + } else { + sbp.cursor = sbp.limit - v_3; + r_stem_suffix_chain_before_ki(); + } + } + return; + } + sbp.cursor = sbp.limit - v_1; + if (habr11()) + return; + sbp.cursor = sbp.limit - v_1; + if (r_mark_lArI()) { + sbp.bra = sbp.cursor; + sbp.slice_del(); + return; + } + sbp.cursor = sbp.limit - v_1; + if (r_stem_suffix_chain_before_ki()) + return; + sbp.cursor = sbp.limit - v_1; + if (habr12()) + return; + sbp.cursor = sbp.limit - v_1; + sbp.ket = sbp.cursor; + if (!r_mark_possessives()) { + sbp.cursor = sbp.limit - v_1; + if (!r_mark_sU()) + return; + } + sbp.bra = sbp.cursor; + sbp.slice_del(); + sbp.ket = sbp.cursor; + if (r_mark_lAr()) { + sbp.bra = sbp.cursor; + sbp.slice_del(); + r_stem_suffix_chain_before_ki(); + } + } + + function r_post_process_last_consonants() { + var among_var; + sbp.ket = sbp.cursor; + among_var = sbp.find_among_b(a_23, 4); + if (among_var) { + sbp.bra = sbp.cursor; + switch (among_var) { + case 1: + sbp.slice_from("p"); + break; + case 2: + sbp.slice_from("\u00E7"); + break; + case 3: + sbp.slice_from("t"); + break; + case 4: + sbp.slice_from("k"); + break; + } + } + } + + function habr13() { + while (true) { + var v_1 = sbp.limit - sbp.cursor; + if (sbp.in_grouping_b(g_vowel, 97, 305)) { + sbp.cursor = sbp.limit - v_1; + break; + } + sbp.cursor = sbp.limit - v_1; + if (sbp.cursor <= sbp.limit_backward) + return false; + sbp.cursor--; + } + return true; + } + + function habr14(v_1, c1, c2) { + sbp.cursor = sbp.limit - v_1; + if (habr13()) { + var v_2 = sbp.limit - sbp.cursor; + if (!sbp.eq_s_b(1, c1)) { + sbp.cursor = sbp.limit - v_2; + if (!sbp.eq_s_b(1, c2)) + return true; + } + sbp.cursor = sbp.limit - v_1; + var c = sbp.cursor; + sbp.insert(sbp.cursor, sbp.cursor, c2); + sbp.cursor = c; + return false; + } + return true; + } + + function r_append_U_to_stems_ending_with_d_or_g() { + var v_1 = sbp.limit - sbp.cursor; + if (!sbp.eq_s_b(1, "d")) { + sbp.cursor = sbp.limit - v_1; + if (!sbp.eq_s_b(1, "g")) + return; + } + if (habr14(v_1, "a", "\u0131")) + if (habr14(v_1, "e", "i")) + if (habr14(v_1, "o", "u")) + habr14(v_1, "\u00F6", "\u00FC") + } + + function r_more_than_one_syllable_word() { + var v_1 = sbp.cursor, + v_2 = 2, + v_3; + while (true) { + v_3 = sbp.cursor; + while (!sbp.in_grouping(g_vowel, 97, 305)) { + if (sbp.cursor >= sbp.limit) { + sbp.cursor = v_3; + if (v_2 > 0) + return false; + sbp.cursor = v_1; + return true; + } + sbp.cursor++; + } + v_2--; + } + } + + function habr15(v_1, n1, c1) { + while (!sbp.eq_s(n1, c1)) { + if (sbp.cursor >= sbp.limit) + return true; + sbp.cursor++; + } + I_strlen = n1; + if (I_strlen != sbp.limit) + return true; + sbp.cursor = v_1; + return false; + } + + function r_is_reserved_word() { + var v_1 = sbp.cursor; + if (habr15(v_1, 2, "ad")) { + sbp.cursor = v_1; + if (habr15(v_1, 5, "soyad")) + return false; + } + return true; + } + + function r_postlude() { + var v_1 = sbp.cursor; + if (r_is_reserved_word()) + return false; + sbp.limit_backward = v_1; + sbp.cursor = sbp.limit; + r_append_U_to_stems_ending_with_d_or_g(); + sbp.cursor = sbp.limit; + r_post_process_last_consonants(); + return true; + } + this.stem = function() { + if (r_more_than_one_syllable_word()) { + sbp.limit_backward = sbp.cursor; + sbp.cursor = sbp.limit; + r_stem_nominal_verb_suffixes(); + sbp.cursor = sbp.limit; + if (B_c_s_n_s) { + r_stem_noun_suffixes(); + sbp.cursor = sbp.limit_backward; + if (r_postlude()) + return true; + } + } + return false; + } + }; + + /* and return a function that stems a word for the current locale */ + return function(token) { + // for lunr version 2 + if (typeof token.update === "function") { + return token.update(function(word) { + st.setCurrent(word); + st.stem(); + return st.getCurrent(); + }) + } else { // for lunr version <= 1 + st.setCurrent(token); + st.stem(); + return st.getCurrent(); + } + } + })(); + + lunr.Pipeline.registerFunction(lunr.tr.stemmer, 'stemmer-tr'); + + lunr.tr.stopWordFilter = lunr.generateStopWordFilter('acaba altmış altı ama ancak arada aslında ayrıca bana bazı belki ben benden beni benim beri beş bile bin bir biri birkaç birkez birçok birşey birşeyi biz bizden bize bizi bizim bu buna bunda bundan bunlar bunları bunların bunu bunun burada böyle böylece da daha dahi de defa değil diye diğer doksan dokuz dolayı dolayısıyla dört edecek eden ederek edilecek ediliyor edilmesi ediyor elli en etmesi etti ettiği ettiğini eğer gibi göre halen hangi hatta hem henüz hep hepsi her herhangi herkesin hiç hiçbir iki ile ilgili ise itibaren itibariyle için işte kadar karşın katrilyon kendi kendilerine kendini kendisi kendisine kendisini kez ki kim kimden kime kimi kimse kırk milyar milyon mu mü mı nasıl ne neden nedenle nerde nerede nereye niye niçin o olan olarak oldu olduklarını olduğu olduğunu olmadı olmadığı olmak olması olmayan olmaz olsa olsun olup olur olursa oluyor on ona ondan onlar onlardan onları onların onu onun otuz oysa pek rağmen sadece sanki sekiz seksen sen senden seni senin siz sizden sizi sizin tarafından trilyon tüm var vardı ve veya ya yani yapacak yapmak yaptı yaptıkları yaptığı yaptığını yapılan yapılması yapıyor yedi yerine yetmiş yine yirmi yoksa yüz zaten çok çünkü öyle üzere üç şey şeyden şeyi şeyler şu şuna şunda şundan şunları şunu şöyle'.split(' ')); + + lunr.Pipeline.registerFunction(lunr.tr.stopWordFilter, 'stopWordFilter-tr'); + }; +})) \ No newline at end of file diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.vi.js b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.vi.js new file mode 100644 index 0000000000000000000000000000000000000000..e7a65b2345d6f4e705c72cf49b3610aa2d0f4e5b --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.vi.js @@ -0,0 +1,84 @@ +/*! + * Lunr languages, `Vietnamese` language + * https://github.com/MihaiValentin/lunr-languages + * + * Copyright 2017, Keerati Thiwanruk + * http://www.mozilla.org/MPL/ + */ +/*! + * based on + * Snowball JavaScript Library v0.3 + * http://code.google.com/p/urim/ + * http://snowball.tartarus.org/ + * + * Copyright 2010, Oleg Mazko + * http://www.mozilla.org/MPL/ + */ + +/** + * export the module via AMD, CommonJS or as a browser global + * Export code from https://github.com/umdjs/umd/blob/master/returnExports.js + */ +; +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(factory) + } else if (typeof exports === 'object') { + /** + * Node. Does not work with strict CommonJS, but + * only CommonJS-like environments that support module.exports, + * like Node. + */ + module.exports = factory() + } else { + // Browser globals (root is window) + factory()(root.lunr); + } +}(this, function() { + /** + * Just return a value to define the module export. + * This example returns an object, but the module + * can return a function as the exported value. + */ + return function(lunr) { + /* throw error if lunr is not yet included */ + if ('undefined' === typeof lunr) { + throw new Error('Lunr is not present. Please include / require Lunr before this script.'); + } + + /* throw error if lunr stemmer support is not yet included */ + if ('undefined' === typeof lunr.stemmerSupport) { + throw new Error('Lunr stemmer support is not present. Please include / require Lunr stemmer support before this script.'); + } + + /* register specific locale function */ + lunr.vi = function() { + this.pipeline.reset(); + this.pipeline.add( + lunr.vi.stopWordFilter, + lunr.vi.trimmer + ); + }; + + /* lunr trimmer function */ + lunr.vi.wordCharacters = "[" + + "A-Za-z" + + "\u0300\u0350" + // dấu huyền + "\u0301\u0351" + // dấu sắc + "\u0309" + // dấu hỏi + "\u0323" + // dấu nặng + "\u0303\u0343" + // dấu ngã + "\u00C2\u00E2" + // Â + "\u00CA\u00EA" + // Ê + "\u00D4\u00F4" + // Ô + "\u0102-\u0103" + // Ă + "\u0110-\u0111" + // Đ + "\u01A0-\u01A1" + // Ơ + "\u01AF-\u01B0" + // Ư + "]"; + lunr.vi.trimmer = lunr.trimmerSupport.generateTrimmer(lunr.vi.wordCharacters); + lunr.Pipeline.registerFunction(lunr.vi.trimmer, 'trimmer-vi'); + lunr.vi.stopWordFilter = lunr.generateStopWordFilter('là cái nhưng mà'.split(' ')); + }; +})) \ No newline at end of file diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.zh.js b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.zh.js new file mode 100644 index 0000000000000000000000000000000000000000..48f5890d964e4e66500e21b6ed2b099f98527ea2 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/lunr.zh.js @@ -0,0 +1,145 @@ +/*! + * Lunr languages, `Chinese` language + * https://github.com/MihaiValentin/lunr-languages + * + * Copyright 2019, Felix Lian (repairearth) + * http://www.mozilla.org/MPL/ + */ +/*! + * based on + * Snowball zhvaScript Library v0.3 + * http://code.google.com/p/urim/ + * http://snowball.tartarus.org/ + * + * Copyright 2010, Oleg Mazko + * http://www.mozilla.org/MPL/ + */ + +/** + * export the module via AMD, CommonJS or as a browser global + * Export code from https://github.com/umdjs/umd/blob/master/returnExports.js + */ +; +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(factory) + } else if (typeof exports === 'object') { + /** + * Node. Does not work with strict CommonJS, but + * only CommonJS-like environments that support module.exports, + * like Node. + */ + module.exports = factory(require('@node-rs/jieba')) + } else { + // Browser globals (root is window) + factory()(root.lunr); + } +}(this, function(nodejieba) { + /** + * Just return a value to define the module export. + * This example returns an object, but the module + * can return a function as the exported value. + */ + return function(lunr, nodejiebaDictJson) { + /* throw error if lunr is not yet included */ + if ('undefined' === typeof lunr) { + throw new Error('Lunr is not present. Please include / require Lunr before this script.'); + } + + /* throw error if lunr stemmer support is not yet included */ + if ('undefined' === typeof lunr.stemmerSupport) { + throw new Error('Lunr stemmer support is not present. Please include / require Lunr stemmer support before this script.'); + } + + /* + Chinese tokenization is trickier, since it does not + take into account spaces. + Since the tokenization function is represented different + internally for each of the Lunr versions, this had to be done + in order to try to try to pick the best way of doing this based + on the Lunr version + */ + var isLunr2 = lunr.version[0] == "2"; + + /* register specific locale function */ + lunr.zh = function() { + this.pipeline.reset(); + this.pipeline.add( + lunr.zh.trimmer, + lunr.zh.stopWordFilter, + lunr.zh.stemmer + ); + + // change the tokenizer for Chinese one + if (isLunr2) { // for lunr version 2.0.0 + this.tokenizer = lunr.zh.tokenizer; + } else { + if (lunr.tokenizer) { // for lunr version 0.6.0 + lunr.tokenizer = lunr.zh.tokenizer; + } + if (this.tokenizerFn) { // for lunr version 0.7.0 -> 1.0.0 + this.tokenizerFn = lunr.zh.tokenizer; + } + } + }; + + lunr.zh.tokenizer = function(obj) { + if (!arguments.length || obj == null || obj == undefined) return [] + if (Array.isArray(obj)) return obj.map(function(t) { + return isLunr2 ? new lunr.Token(t.toLowerCase()) : t.toLowerCase() + }) + + nodejiebaDictJson && nodejieba.load(nodejiebaDictJson) + + var str = obj.toString().trim().toLowerCase(); + var tokens = []; + + nodejieba.cut(str, true).forEach(function(seg) { + tokens = tokens.concat(seg.split(' ')) + }) + + tokens = tokens.filter(function(token) { + return !!token; + }); + + var fromIndex = 0 + + return tokens.map(function(token, index) { + if (isLunr2) { + var start = str.indexOf(token, fromIndex) + + var tokenMetadata = {} + tokenMetadata["position"] = [start, token.length] + tokenMetadata["index"] = index + + fromIndex = start + + return new lunr.Token(token, tokenMetadata); + } else { + return token + } + }); + } + + /* lunr trimmer function */ + lunr.zh.wordCharacters = "\\w\u4e00-\u9fa5"; + lunr.zh.trimmer = lunr.trimmerSupport.generateTrimmer(lunr.zh.wordCharacters); + lunr.Pipeline.registerFunction(lunr.zh.trimmer, 'trimmer-zh'); + + /* lunr stemmer function */ + lunr.zh.stemmer = (function() { + + /* TODO Chinese stemmer */ + return function(word) { + return word; + } + })(); + lunr.Pipeline.registerFunction(lunr.zh.stemmer, 'stemmer-zh'); + + /* lunr stop word filter. see https://www.ranks.nl/stopwords/chinese-stopwords */ + lunr.zh.stopWordFilter = lunr.generateStopWordFilter( + '的 一 不 在 人 有 是 为 為 以 于 於 上 他 而 后 後 之 来 來 及 了 因 下 可 到 由 这 這 与 與 也 此 但 并 並 个 個 其 已 无 無 小 我 们 們 起 最 再 今 去 好 只 又 或 很 亦 某 把 那 你 乃 它 吧 被 比 别 趁 当 當 从 從 得 打 凡 儿 兒 尔 爾 该 該 各 给 給 跟 和 何 还 還 即 几 幾 既 看 据 據 距 靠 啦 另 么 麽 每 嘛 拿 哪 您 凭 憑 且 却 卻 让 讓 仍 啥 如 若 使 谁 誰 虽 雖 随 隨 同 所 她 哇 嗡 往 些 向 沿 哟 喲 用 咱 则 則 怎 曾 至 致 着 著 诸 諸 自'.split(' ')); + lunr.Pipeline.registerFunction(lunr.zh.stopWordFilter, 'stopWordFilter-zh'); + }; +})) \ No newline at end of file diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/tinyseg.js b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/tinyseg.js new file mode 100644 index 0000000000000000000000000000000000000000..167fa6dd69e074b43de3aa48005d0b748b8e83e7 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/lunr-language/tinyseg.js @@ -0,0 +1,206 @@ +/** + * export the module via AMD, CommonJS or as a browser global + * Export code from https://github.com/umdjs/umd/blob/master/returnExports.js + */ +;(function (root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(factory) + } else if (typeof exports === 'object') { + /** + * Node. Does not work with strict CommonJS, but + * only CommonJS-like environments that support module.exports, + * like Node. + */ + module.exports = factory() + } else { + // Browser globals (root is window) + factory()(root.lunr); + } +}(this, function () { + /** + * Just return a value to define the module export. + * This example returns an object, but the module + * can return a function as the exported value. + */ + + return function(lunr) { + // TinySegmenter 0.1 -- Super compact Japanese tokenizer in Javascript + // (c) 2008 Taku Kudo + // TinySegmenter is freely distributable under the terms of a new BSD licence. + // For details, see http://chasen.org/~taku/software/TinySegmenter/LICENCE.txt + + function TinySegmenter() { + var patterns = { + "[一二三四五六七八九十百千万億兆]":"M", + "[一-龠々〆ヵヶ]":"H", + "[ぁ-ん]":"I", + "[ァ-ヴーア-ン゙ー]":"K", + "[a-zA-Za-zA-Z]":"A", + "[0-90-9]":"N" + } + this.chartype_ = []; + for (var i in patterns) { + var regexp = new RegExp(i); + this.chartype_.push([regexp, patterns[i]]); + } + + this.BIAS__ = -332 + this.BC1__ = {"HH":6,"II":2461,"KH":406,"OH":-1378}; + this.BC2__ = {"AA":-3267,"AI":2744,"AN":-878,"HH":-4070,"HM":-1711,"HN":4012,"HO":3761,"IA":1327,"IH":-1184,"II":-1332,"IK":1721,"IO":5492,"KI":3831,"KK":-8741,"MH":-3132,"MK":3334,"OO":-2920}; + this.BC3__ = {"HH":996,"HI":626,"HK":-721,"HN":-1307,"HO":-836,"IH":-301,"KK":2762,"MK":1079,"MM":4034,"OA":-1652,"OH":266}; + this.BP1__ = {"BB":295,"OB":304,"OO":-125,"UB":352}; + this.BP2__ = {"BO":60,"OO":-1762}; + this.BQ1__ = {"BHH":1150,"BHM":1521,"BII":-1158,"BIM":886,"BMH":1208,"BNH":449,"BOH":-91,"BOO":-2597,"OHI":451,"OIH":-296,"OKA":1851,"OKH":-1020,"OKK":904,"OOO":2965}; + this.BQ2__ = {"BHH":118,"BHI":-1159,"BHM":466,"BIH":-919,"BKK":-1720,"BKO":864,"OHH":-1139,"OHM":-181,"OIH":153,"UHI":-1146}; + this.BQ3__ = {"BHH":-792,"BHI":2664,"BII":-299,"BKI":419,"BMH":937,"BMM":8335,"BNN":998,"BOH":775,"OHH":2174,"OHM":439,"OII":280,"OKH":1798,"OKI":-793,"OKO":-2242,"OMH":-2402,"OOO":11699}; + this.BQ4__ = {"BHH":-3895,"BIH":3761,"BII":-4654,"BIK":1348,"BKK":-1806,"BMI":-3385,"BOO":-12396,"OAH":926,"OHH":266,"OHK":-2036,"ONN":-973}; + this.BW1__ = {",と":660,",同":727,"B1あ":1404,"B1同":542,"、と":660,"、同":727,"」と":1682,"あっ":1505,"いう":1743,"いっ":-2055,"いる":672,"うし":-4817,"うん":665,"から":3472,"がら":600,"こう":-790,"こと":2083,"こん":-1262,"さら":-4143,"さん":4573,"した":2641,"して":1104,"すで":-3399,"そこ":1977,"それ":-871,"たち":1122,"ため":601,"った":3463,"つい":-802,"てい":805,"てき":1249,"でき":1127,"です":3445,"では":844,"とい":-4915,"とみ":1922,"どこ":3887,"ない":5713,"なっ":3015,"など":7379,"なん":-1113,"にし":2468,"には":1498,"にも":1671,"に対":-912,"の一":-501,"の中":741,"ませ":2448,"まで":1711,"まま":2600,"まる":-2155,"やむ":-1947,"よっ":-2565,"れた":2369,"れで":-913,"をし":1860,"を見":731,"亡く":-1886,"京都":2558,"取り":-2784,"大き":-2604,"大阪":1497,"平方":-2314,"引き":-1336,"日本":-195,"本当":-2423,"毎日":-2113,"目指":-724,"B1あ":1404,"B1同":542,"」と":1682}; + this.BW2__ = {"..":-11822,"11":-669,"――":-5730,"−−":-13175,"いう":-1609,"うか":2490,"かし":-1350,"かも":-602,"から":-7194,"かれ":4612,"がい":853,"がら":-3198,"きた":1941,"くな":-1597,"こと":-8392,"この":-4193,"させ":4533,"され":13168,"さん":-3977,"しい":-1819,"しか":-545,"した":5078,"して":972,"しな":939,"その":-3744,"たい":-1253,"たた":-662,"ただ":-3857,"たち":-786,"たと":1224,"たは":-939,"った":4589,"って":1647,"っと":-2094,"てい":6144,"てき":3640,"てく":2551,"ては":-3110,"ても":-3065,"でい":2666,"でき":-1528,"でし":-3828,"です":-4761,"でも":-4203,"とい":1890,"とこ":-1746,"とと":-2279,"との":720,"とみ":5168,"とも":-3941,"ない":-2488,"なが":-1313,"など":-6509,"なの":2614,"なん":3099,"にお":-1615,"にし":2748,"にな":2454,"によ":-7236,"に対":-14943,"に従":-4688,"に関":-11388,"のか":2093,"ので":-7059,"のに":-6041,"のの":-6125,"はい":1073,"はが":-1033,"はず":-2532,"ばれ":1813,"まし":-1316,"まで":-6621,"まれ":5409,"めて":-3153,"もい":2230,"もの":-10713,"らか":-944,"らし":-1611,"らに":-1897,"りし":651,"りま":1620,"れた":4270,"れて":849,"れば":4114,"ろう":6067,"われ":7901,"を通":-11877,"んだ":728,"んな":-4115,"一人":602,"一方":-1375,"一日":970,"一部":-1051,"上が":-4479,"会社":-1116,"出て":2163,"分の":-7758,"同党":970,"同日":-913,"大阪":-2471,"委員":-1250,"少な":-1050,"年度":-8669,"年間":-1626,"府県":-2363,"手権":-1982,"新聞":-4066,"日新":-722,"日本":-7068,"日米":3372,"曜日":-601,"朝鮮":-2355,"本人":-2697,"東京":-1543,"然と":-1384,"社会":-1276,"立て":-990,"第に":-1612,"米国":-4268,"11":-669}; + this.BW3__ = {"あた":-2194,"あり":719,"ある":3846,"い.":-1185,"い。":-1185,"いい":5308,"いえ":2079,"いく":3029,"いた":2056,"いっ":1883,"いる":5600,"いわ":1527,"うち":1117,"うと":4798,"えと":1454,"か.":2857,"か。":2857,"かけ":-743,"かっ":-4098,"かに":-669,"から":6520,"かり":-2670,"が,":1816,"が、":1816,"がき":-4855,"がけ":-1127,"がっ":-913,"がら":-4977,"がり":-2064,"きた":1645,"けど":1374,"こと":7397,"この":1542,"ころ":-2757,"さい":-714,"さを":976,"し,":1557,"し、":1557,"しい":-3714,"した":3562,"して":1449,"しな":2608,"しま":1200,"す.":-1310,"す。":-1310,"する":6521,"ず,":3426,"ず、":3426,"ずに":841,"そう":428,"た.":8875,"た。":8875,"たい":-594,"たの":812,"たり":-1183,"たる":-853,"だ.":4098,"だ。":4098,"だっ":1004,"った":-4748,"って":300,"てい":6240,"てお":855,"ても":302,"です":1437,"でに":-1482,"では":2295,"とう":-1387,"とし":2266,"との":541,"とも":-3543,"どう":4664,"ない":1796,"なく":-903,"など":2135,"に,":-1021,"に、":-1021,"にし":1771,"にな":1906,"には":2644,"の,":-724,"の、":-724,"の子":-1000,"は,":1337,"は、":1337,"べき":2181,"まし":1113,"ます":6943,"まっ":-1549,"まで":6154,"まれ":-793,"らし":1479,"られ":6820,"るる":3818,"れ,":854,"れ、":854,"れた":1850,"れて":1375,"れば":-3246,"れる":1091,"われ":-605,"んだ":606,"んで":798,"カ月":990,"会議":860,"入り":1232,"大会":2217,"始め":1681,"市":965,"新聞":-5055,"日,":974,"日、":974,"社会":2024,"カ月":990}; + this.TC1__ = {"AAA":1093,"HHH":1029,"HHM":580,"HII":998,"HOH":-390,"HOM":-331,"IHI":1169,"IOH":-142,"IOI":-1015,"IOM":467,"MMH":187,"OOI":-1832}; + this.TC2__ = {"HHO":2088,"HII":-1023,"HMM":-1154,"IHI":-1965,"KKH":703,"OII":-2649}; + this.TC3__ = {"AAA":-294,"HHH":346,"HHI":-341,"HII":-1088,"HIK":731,"HOH":-1486,"IHH":128,"IHI":-3041,"IHO":-1935,"IIH":-825,"IIM":-1035,"IOI":-542,"KHH":-1216,"KKA":491,"KKH":-1217,"KOK":-1009,"MHH":-2694,"MHM":-457,"MHO":123,"MMH":-471,"NNH":-1689,"NNO":662,"OHO":-3393}; + this.TC4__ = {"HHH":-203,"HHI":1344,"HHK":365,"HHM":-122,"HHN":182,"HHO":669,"HIH":804,"HII":679,"HOH":446,"IHH":695,"IHO":-2324,"IIH":321,"III":1497,"IIO":656,"IOO":54,"KAK":4845,"KKA":3386,"KKK":3065,"MHH":-405,"MHI":201,"MMH":-241,"MMM":661,"MOM":841}; + this.TQ1__ = {"BHHH":-227,"BHHI":316,"BHIH":-132,"BIHH":60,"BIII":1595,"BNHH":-744,"BOHH":225,"BOOO":-908,"OAKK":482,"OHHH":281,"OHIH":249,"OIHI":200,"OIIH":-68}; + this.TQ2__ = {"BIHH":-1401,"BIII":-1033,"BKAK":-543,"BOOO":-5591}; + this.TQ3__ = {"BHHH":478,"BHHM":-1073,"BHIH":222,"BHII":-504,"BIIH":-116,"BIII":-105,"BMHI":-863,"BMHM":-464,"BOMH":620,"OHHH":346,"OHHI":1729,"OHII":997,"OHMH":481,"OIHH":623,"OIIH":1344,"OKAK":2792,"OKHH":587,"OKKA":679,"OOHH":110,"OOII":-685}; + this.TQ4__ = {"BHHH":-721,"BHHM":-3604,"BHII":-966,"BIIH":-607,"BIII":-2181,"OAAA":-2763,"OAKK":180,"OHHH":-294,"OHHI":2446,"OHHO":480,"OHIH":-1573,"OIHH":1935,"OIHI":-493,"OIIH":626,"OIII":-4007,"OKAK":-8156}; + this.TW1__ = {"につい":-4681,"東京都":2026}; + this.TW2__ = {"ある程":-2049,"いった":-1256,"ころが":-2434,"しょう":3873,"その後":-4430,"だって":-1049,"ていた":1833,"として":-4657,"ともに":-4517,"もので":1882,"一気に":-792,"初めて":-1512,"同時に":-8097,"大きな":-1255,"対して":-2721,"社会党":-3216}; + this.TW3__ = {"いただ":-1734,"してい":1314,"として":-4314,"につい":-5483,"にとっ":-5989,"に当た":-6247,"ので,":-727,"ので、":-727,"のもの":-600,"れから":-3752,"十二月":-2287}; + this.TW4__ = {"いう.":8576,"いう。":8576,"からな":-2348,"してい":2958,"たが,":1516,"たが、":1516,"ている":1538,"という":1349,"ました":5543,"ません":1097,"ようと":-4258,"よると":5865}; + this.UC1__ = {"A":484,"K":93,"M":645,"O":-505}; + this.UC2__ = {"A":819,"H":1059,"I":409,"M":3987,"N":5775,"O":646}; + this.UC3__ = {"A":-1370,"I":2311}; + this.UC4__ = {"A":-2643,"H":1809,"I":-1032,"K":-3450,"M":3565,"N":3876,"O":6646}; + this.UC5__ = {"H":313,"I":-1238,"K":-799,"M":539,"O":-831}; + this.UC6__ = {"H":-506,"I":-253,"K":87,"M":247,"O":-387}; + this.UP1__ = {"O":-214}; + this.UP2__ = {"B":69,"O":935}; + this.UP3__ = {"B":189}; + this.UQ1__ = {"BH":21,"BI":-12,"BK":-99,"BN":142,"BO":-56,"OH":-95,"OI":477,"OK":410,"OO":-2422}; + this.UQ2__ = {"BH":216,"BI":113,"OK":1759}; + this.UQ3__ = {"BA":-479,"BH":42,"BI":1913,"BK":-7198,"BM":3160,"BN":6427,"BO":14761,"OI":-827,"ON":-3212}; + this.UW1__ = {",":156,"、":156,"「":-463,"あ":-941,"う":-127,"が":-553,"き":121,"こ":505,"で":-201,"と":-547,"ど":-123,"に":-789,"の":-185,"は":-847,"も":-466,"や":-470,"よ":182,"ら":-292,"り":208,"れ":169,"を":-446,"ん":-137,"・":-135,"主":-402,"京":-268,"区":-912,"午":871,"国":-460,"大":561,"委":729,"市":-411,"日":-141,"理":361,"生":-408,"県":-386,"都":-718,"「":-463,"・":-135}; + this.UW2__ = {",":-829,"、":-829,"〇":892,"「":-645,"」":3145,"あ":-538,"い":505,"う":134,"お":-502,"か":1454,"が":-856,"く":-412,"こ":1141,"さ":878,"ざ":540,"し":1529,"す":-675,"せ":300,"そ":-1011,"た":188,"だ":1837,"つ":-949,"て":-291,"で":-268,"と":-981,"ど":1273,"な":1063,"に":-1764,"の":130,"は":-409,"ひ":-1273,"べ":1261,"ま":600,"も":-1263,"や":-402,"よ":1639,"り":-579,"る":-694,"れ":571,"を":-2516,"ん":2095,"ア":-587,"カ":306,"キ":568,"ッ":831,"三":-758,"不":-2150,"世":-302,"中":-968,"主":-861,"事":492,"人":-123,"会":978,"保":362,"入":548,"初":-3025,"副":-1566,"北":-3414,"区":-422,"大":-1769,"天":-865,"太":-483,"子":-1519,"学":760,"実":1023,"小":-2009,"市":-813,"年":-1060,"強":1067,"手":-1519,"揺":-1033,"政":1522,"文":-1355,"新":-1682,"日":-1815,"明":-1462,"最":-630,"朝":-1843,"本":-1650,"東":-931,"果":-665,"次":-2378,"民":-180,"気":-1740,"理":752,"発":529,"目":-1584,"相":-242,"県":-1165,"立":-763,"第":810,"米":509,"自":-1353,"行":838,"西":-744,"見":-3874,"調":1010,"議":1198,"込":3041,"開":1758,"間":-1257,"「":-645,"」":3145,"ッ":831,"ア":-587,"カ":306,"キ":568}; + this.UW3__ = {",":4889,"1":-800,"−":-1723,"、":4889,"々":-2311,"〇":5827,"」":2670,"〓":-3573,"あ":-2696,"い":1006,"う":2342,"え":1983,"お":-4864,"か":-1163,"が":3271,"く":1004,"け":388,"げ":401,"こ":-3552,"ご":-3116,"さ":-1058,"し":-395,"す":584,"せ":3685,"そ":-5228,"た":842,"ち":-521,"っ":-1444,"つ":-1081,"て":6167,"で":2318,"と":1691,"ど":-899,"な":-2788,"に":2745,"の":4056,"は":4555,"ひ":-2171,"ふ":-1798,"へ":1199,"ほ":-5516,"ま":-4384,"み":-120,"め":1205,"も":2323,"や":-788,"よ":-202,"ら":727,"り":649,"る":5905,"れ":2773,"わ":-1207,"を":6620,"ん":-518,"ア":551,"グ":1319,"ス":874,"ッ":-1350,"ト":521,"ム":1109,"ル":1591,"ロ":2201,"ン":278,"・":-3794,"一":-1619,"下":-1759,"世":-2087,"両":3815,"中":653,"主":-758,"予":-1193,"二":974,"人":2742,"今":792,"他":1889,"以":-1368,"低":811,"何":4265,"作":-361,"保":-2439,"元":4858,"党":3593,"全":1574,"公":-3030,"六":755,"共":-1880,"円":5807,"再":3095,"分":457,"初":2475,"別":1129,"前":2286,"副":4437,"力":365,"動":-949,"務":-1872,"化":1327,"北":-1038,"区":4646,"千":-2309,"午":-783,"協":-1006,"口":483,"右":1233,"各":3588,"合":-241,"同":3906,"和":-837,"員":4513,"国":642,"型":1389,"場":1219,"外":-241,"妻":2016,"学":-1356,"安":-423,"実":-1008,"家":1078,"小":-513,"少":-3102,"州":1155,"市":3197,"平":-1804,"年":2416,"広":-1030,"府":1605,"度":1452,"建":-2352,"当":-3885,"得":1905,"思":-1291,"性":1822,"戸":-488,"指":-3973,"政":-2013,"教":-1479,"数":3222,"文":-1489,"新":1764,"日":2099,"旧":5792,"昨":-661,"時":-1248,"曜":-951,"最":-937,"月":4125,"期":360,"李":3094,"村":364,"東":-805,"核":5156,"森":2438,"業":484,"氏":2613,"民":-1694,"決":-1073,"法":1868,"海":-495,"無":979,"物":461,"特":-3850,"生":-273,"用":914,"町":1215,"的":7313,"直":-1835,"省":792,"県":6293,"知":-1528,"私":4231,"税":401,"立":-960,"第":1201,"米":7767,"系":3066,"約":3663,"級":1384,"統":-4229,"総":1163,"線":1255,"者":6457,"能":725,"自":-2869,"英":785,"見":1044,"調":-562,"財":-733,"費":1777,"車":1835,"軍":1375,"込":-1504,"通":-1136,"選":-681,"郎":1026,"郡":4404,"部":1200,"金":2163,"長":421,"開":-1432,"間":1302,"関":-1282,"雨":2009,"電":-1045,"非":2066,"駅":1620,"1":-800,"」":2670,"・":-3794,"ッ":-1350,"ア":551,"グ":1319,"ス":874,"ト":521,"ム":1109,"ル":1591,"ロ":2201,"ン":278}; + this.UW4__ = {",":3930,".":3508,"―":-4841,"、":3930,"。":3508,"〇":4999,"「":1895,"」":3798,"〓":-5156,"あ":4752,"い":-3435,"う":-640,"え":-2514,"お":2405,"か":530,"が":6006,"き":-4482,"ぎ":-3821,"く":-3788,"け":-4376,"げ":-4734,"こ":2255,"ご":1979,"さ":2864,"し":-843,"じ":-2506,"す":-731,"ず":1251,"せ":181,"そ":4091,"た":5034,"だ":5408,"ち":-3654,"っ":-5882,"つ":-1659,"て":3994,"で":7410,"と":4547,"な":5433,"に":6499,"ぬ":1853,"ね":1413,"の":7396,"は":8578,"ば":1940,"ひ":4249,"び":-4134,"ふ":1345,"へ":6665,"べ":-744,"ほ":1464,"ま":1051,"み":-2082,"む":-882,"め":-5046,"も":4169,"ゃ":-2666,"や":2795,"ょ":-1544,"よ":3351,"ら":-2922,"り":-9726,"る":-14896,"れ":-2613,"ろ":-4570,"わ":-1783,"を":13150,"ん":-2352,"カ":2145,"コ":1789,"セ":1287,"ッ":-724,"ト":-403,"メ":-1635,"ラ":-881,"リ":-541,"ル":-856,"ン":-3637,"・":-4371,"ー":-11870,"一":-2069,"中":2210,"予":782,"事":-190,"井":-1768,"人":1036,"以":544,"会":950,"体":-1286,"作":530,"側":4292,"先":601,"党":-2006,"共":-1212,"内":584,"円":788,"初":1347,"前":1623,"副":3879,"力":-302,"動":-740,"務":-2715,"化":776,"区":4517,"協":1013,"参":1555,"合":-1834,"和":-681,"員":-910,"器":-851,"回":1500,"国":-619,"園":-1200,"地":866,"場":-1410,"塁":-2094,"士":-1413,"多":1067,"大":571,"子":-4802,"学":-1397,"定":-1057,"寺":-809,"小":1910,"屋":-1328,"山":-1500,"島":-2056,"川":-2667,"市":2771,"年":374,"庁":-4556,"後":456,"性":553,"感":916,"所":-1566,"支":856,"改":787,"政":2182,"教":704,"文":522,"方":-856,"日":1798,"時":1829,"最":845,"月":-9066,"木":-485,"来":-442,"校":-360,"業":-1043,"氏":5388,"民":-2716,"気":-910,"沢":-939,"済":-543,"物":-735,"率":672,"球":-1267,"生":-1286,"産":-1101,"田":-2900,"町":1826,"的":2586,"目":922,"省":-3485,"県":2997,"空":-867,"立":-2112,"第":788,"米":2937,"系":786,"約":2171,"経":1146,"統":-1169,"総":940,"線":-994,"署":749,"者":2145,"能":-730,"般":-852,"行":-792,"規":792,"警":-1184,"議":-244,"谷":-1000,"賞":730,"車":-1481,"軍":1158,"輪":-1433,"込":-3370,"近":929,"道":-1291,"選":2596,"郎":-4866,"都":1192,"野":-1100,"銀":-2213,"長":357,"間":-2344,"院":-2297,"際":-2604,"電":-878,"領":-1659,"題":-792,"館":-1984,"首":1749,"高":2120,"「":1895,"」":3798,"・":-4371,"ッ":-724,"ー":-11870,"カ":2145,"コ":1789,"セ":1287,"ト":-403,"メ":-1635,"ラ":-881,"リ":-541,"ル":-856,"ン":-3637}; + this.UW5__ = {",":465,".":-299,"1":-514,"E2":-32768,"]":-2762,"、":465,"。":-299,"「":363,"あ":1655,"い":331,"う":-503,"え":1199,"お":527,"か":647,"が":-421,"き":1624,"ぎ":1971,"く":312,"げ":-983,"さ":-1537,"し":-1371,"す":-852,"だ":-1186,"ち":1093,"っ":52,"つ":921,"て":-18,"で":-850,"と":-127,"ど":1682,"な":-787,"に":-1224,"の":-635,"は":-578,"べ":1001,"み":502,"め":865,"ゃ":3350,"ょ":854,"り":-208,"る":429,"れ":504,"わ":419,"を":-1264,"ん":327,"イ":241,"ル":451,"ン":-343,"中":-871,"京":722,"会":-1153,"党":-654,"務":3519,"区":-901,"告":848,"員":2104,"大":-1296,"学":-548,"定":1785,"嵐":-1304,"市":-2991,"席":921,"年":1763,"思":872,"所":-814,"挙":1618,"新":-1682,"日":218,"月":-4353,"査":932,"格":1356,"機":-1508,"氏":-1347,"田":240,"町":-3912,"的":-3149,"相":1319,"省":-1052,"県":-4003,"研":-997,"社":-278,"空":-813,"統":1955,"者":-2233,"表":663,"語":-1073,"議":1219,"選":-1018,"郎":-368,"長":786,"間":1191,"題":2368,"館":-689,"1":-514,"E2":-32768,"「":363,"イ":241,"ル":451,"ン":-343}; + this.UW6__ = {",":227,".":808,"1":-270,"E1":306,"、":227,"。":808,"あ":-307,"う":189,"か":241,"が":-73,"く":-121,"こ":-200,"じ":1782,"す":383,"た":-428,"っ":573,"て":-1014,"で":101,"と":-105,"な":-253,"に":-149,"の":-417,"は":-236,"も":-206,"り":187,"る":-135,"を":195,"ル":-673,"ン":-496,"一":-277,"中":201,"件":-800,"会":624,"前":302,"区":1792,"員":-1212,"委":798,"学":-960,"市":887,"広":-695,"後":535,"業":-697,"相":753,"社":-507,"福":974,"空":-822,"者":1811,"連":463,"郎":1082,"1":-270,"E1":306,"ル":-673,"ン":-496}; + + return this; + } + TinySegmenter.prototype.ctype_ = function(str) { + for (var i in this.chartype_) { + if (str.match(this.chartype_[i][0])) { + return this.chartype_[i][1]; + } + } + return "O"; + } + + TinySegmenter.prototype.ts_ = function(v) { + if (v) { return v; } + return 0; + } + + TinySegmenter.prototype.segment = function(input) { + if (input == null || input == undefined || input == "") { + return []; + } + var result = []; + var seg = ["B3","B2","B1"]; + var ctype = ["O","O","O"]; + var o = input.split(""); + for (i = 0; i < o.length; ++i) { + seg.push(o[i]); + ctype.push(this.ctype_(o[i])) + } + seg.push("E1"); + seg.push("E2"); + seg.push("E3"); + ctype.push("O"); + ctype.push("O"); + ctype.push("O"); + var word = seg[3]; + var p1 = "U"; + var p2 = "U"; + var p3 = "U"; + for (var i = 4; i < seg.length - 3; ++i) { + var score = this.BIAS__; + var w1 = seg[i-3]; + var w2 = seg[i-2]; + var w3 = seg[i-1]; + var w4 = seg[i]; + var w5 = seg[i+1]; + var w6 = seg[i+2]; + var c1 = ctype[i-3]; + var c2 = ctype[i-2]; + var c3 = ctype[i-1]; + var c4 = ctype[i]; + var c5 = ctype[i+1]; + var c6 = ctype[i+2]; + score += this.ts_(this.UP1__[p1]); + score += this.ts_(this.UP2__[p2]); + score += this.ts_(this.UP3__[p3]); + score += this.ts_(this.BP1__[p1 + p2]); + score += this.ts_(this.BP2__[p2 + p3]); + score += this.ts_(this.UW1__[w1]); + score += this.ts_(this.UW2__[w2]); + score += this.ts_(this.UW3__[w3]); + score += this.ts_(this.UW4__[w4]); + score += this.ts_(this.UW5__[w5]); + score += this.ts_(this.UW6__[w6]); + score += this.ts_(this.BW1__[w2 + w3]); + score += this.ts_(this.BW2__[w3 + w4]); + score += this.ts_(this.BW3__[w4 + w5]); + score += this.ts_(this.TW1__[w1 + w2 + w3]); + score += this.ts_(this.TW2__[w2 + w3 + w4]); + score += this.ts_(this.TW3__[w3 + w4 + w5]); + score += this.ts_(this.TW4__[w4 + w5 + w6]); + score += this.ts_(this.UC1__[c1]); + score += this.ts_(this.UC2__[c2]); + score += this.ts_(this.UC3__[c3]); + score += this.ts_(this.UC4__[c4]); + score += this.ts_(this.UC5__[c5]); + score += this.ts_(this.UC6__[c6]); + score += this.ts_(this.BC1__[c2 + c3]); + score += this.ts_(this.BC2__[c3 + c4]); + score += this.ts_(this.BC3__[c4 + c5]); + score += this.ts_(this.TC1__[c1 + c2 + c3]); + score += this.ts_(this.TC2__[c2 + c3 + c4]); + score += this.ts_(this.TC3__[c3 + c4 + c5]); + score += this.ts_(this.TC4__[c4 + c5 + c6]); + // score += this.ts_(this.TC5__[c4 + c5 + c6]); + score += this.ts_(this.UQ1__[p1 + c1]); + score += this.ts_(this.UQ2__[p2 + c2]); + score += this.ts_(this.UQ3__[p3 + c3]); + score += this.ts_(this.BQ1__[p2 + c2 + c3]); + score += this.ts_(this.BQ2__[p2 + c3 + c4]); + score += this.ts_(this.BQ3__[p3 + c2 + c3]); + score += this.ts_(this.BQ4__[p3 + c3 + c4]); + score += this.ts_(this.TQ1__[p2 + c1 + c2 + c3]); + score += this.ts_(this.TQ2__[p2 + c2 + c3 + c4]); + score += this.ts_(this.TQ3__[p3 + c1 + c2 + c3]); + score += this.ts_(this.TQ4__[p3 + c2 + c3 + c4]); + var p = "O"; + if (score > 0) { + result.push(word); + word = ""; + p = "B"; + } + p1 = p2; + p2 = p3; + p3 = p; + word += seg[i]; + } + result.push(word); + + return result; + } + + lunr.TinySegmenter = TinySegmenter; + }; + +})); \ No newline at end of file diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/prebuild-index.js b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/prebuild-index.js new file mode 100644 index 0000000000000000000000000000000000000000..835d17ba3784fc5ae3de6e0a44004380312f8ca4 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/prebuild-index.js @@ -0,0 +1,56 @@ +var lunr = require('./templates/search/lunr'), + stdin = process.stdin, + stdout = process.stdout, + buffer = []; + +stdin.resume(); +stdin.setEncoding('utf8'); + +stdin.on('data', function (data) { + buffer.push(data); +}); + +stdin.on('end', function () { + var data = JSON.parse(buffer.join('')), + lang = ['en']; + + if (data.config) { + if (data.config.lang && data.config.lang.length) { + lang = data.config.lang; + if (lang.length > 1 || lang[0] !== "en") { + require('./lunr-language/lunr.stemmer.support')(lunr); + if (lang.length > 1) { + require('./lunr-language/lunr.multi')(lunr); + } + if (lang.includes("ja") || lang.includes("jp")) { + require('./lunr-language/tinyseg')(lunr); + } + for (var i=0; i < lang.length; i++) { + if (lang[i] != 'en') { + require('./lunr-language/lunr.' + lang[i])(lunr); + } + } + } + } + if (data.config.separator && data.config.separator.length) { + lunr.tokenizer.separator = new RegExp(data.config.separator); + } + } + + var idx = lunr(function () { + if (lang.length === 1 && lang[0] !== "en" && lunr[lang[0]]) { + this.use(lunr[lang[0]]); + } else if (lang.length > 1) { + this.use(lunr.multiLanguage.apply(null, lang)); + } + this.field('title'); + this.field('text'); + this.ref('location'); + + data.docs.forEach(function (doc) { + this.add(doc); + }, this); + }); + + stdout.write(JSON.stringify(idx)); +}); diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/search_index.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/search_index.py new file mode 100644 index 0000000000000000000000000000000000000000..f73612194cabe2d8426c4341361f21566d409a7a --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/search_index.py @@ -0,0 +1,231 @@ +from __future__ import annotations + +import json +import logging +import os +import re +import subprocess +from html.parser import HTMLParser +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from mkdocs.structure.pages import Page + from mkdocs.structure.toc import AnchorLink, TableOfContents + +try: + from lunr import lunr + + haslunrpy = True +except ImportError: + haslunrpy = False + +log = logging.getLogger(__name__) + + +class SearchIndex: + """ + Search index is a collection of pages and sections (heading + tags and their following content are sections). + """ + + def __init__(self, **config) -> None: + self._entries: list[dict] = [] + self.config = config + + def _find_toc_by_id(self, toc, id_: str | None) -> AnchorLink | None: + """ + Given a table of contents and HTML ID, iterate through + and return the matched item in the TOC. + """ + for toc_item in toc: + if toc_item.id == id_: + return toc_item + toc_item_r = self._find_toc_by_id(toc_item.children, id_) + if toc_item_r is not None: + return toc_item_r + return None + + def _add_entry(self, title: str | None, text: str, loc: str) -> None: + """ + A simple wrapper to add an entry, dropping bad characters. + """ + text = text.replace('\u00a0', ' ') + text = re.sub(r'[ \t\n\r\f\v]+', ' ', text.strip()) + + self._entries.append({'title': title, 'text': text, 'location': loc}) + + def add_entry_from_context(self, page: Page) -> None: + """ + Create a set of entries in the index for a page. One for + the page itself and then one for each of its' heading + tags. + """ + # Create the content parser and feed in the HTML for the + # full page. This handles all the parsing and prepares + # us to iterate through it. + parser = ContentParser() + assert page.content is not None + parser.feed(page.content) + parser.close() + + # Get the absolute URL for the page, this is then + # prepended to the urls of the sections + url = page.url + + # Create an entry for the full page. + text = parser.stripped_html.rstrip('\n') if self.config['indexing'] == 'full' else '' + self._add_entry(title=page.title, text=text, loc=url) + + if self.config['indexing'] in ['full', 'sections']: + for section in parser.data: + self.create_entry_for_section(section, page.toc, url) + + def create_entry_for_section( + self, section: ContentSection, toc: TableOfContents, abs_url: str + ) -> None: + """ + Given a section on the page, the table of contents and + the absolute url for the page create an entry in the + index + """ + toc_item = self._find_toc_by_id(toc, section.id) + + text = ' '.join(section.text) if self.config['indexing'] == 'full' else '' + if toc_item is not None: + self._add_entry(title=toc_item.title, text=text, loc=abs_url + toc_item.url) + + def generate_search_index(self) -> str: + """python to json conversion""" + page_dicts = {'docs': self._entries, 'config': self.config} + data = json.dumps(page_dicts, sort_keys=True, separators=(',', ':'), default=str) + + if self.config['prebuild_index'] in (True, 'node'): + try: + script_path = os.path.join( + os.path.dirname(os.path.abspath(__file__)), 'prebuild-index.js' + ) + p = subprocess.Popen( + ['node', script_path], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + encoding='utf-8', + ) + idx, err = p.communicate(data) + if not err: + page_dicts['index'] = json.loads(idx) + data = json.dumps(page_dicts, sort_keys=True, separators=(',', ':')) + log.debug('Pre-built search index created successfully.') + else: + log.warning(f'Failed to pre-build search index. Error: {err}') + except (OSError, ValueError) as e: + log.warning(f'Failed to pre-build search index. Error: {e}') + elif self.config['prebuild_index'] == 'python': + if haslunrpy: + lunr_idx = lunr( + ref='location', + fields=('title', 'text'), + documents=self._entries, + languages=self.config['lang'], + ) + page_dicts['index'] = lunr_idx.serialize() + data = json.dumps(page_dicts, sort_keys=True, separators=(',', ':')) + else: + log.warning( + "Failed to pre-build search index. The 'python' method was specified; " + "however, the 'lunr.py' library does not appear to be installed. Try " + "installing it with 'pip install lunr'. If you are using any language " + "other than English you will also need to install 'lunr[languages]'." + ) + + return data + + +class ContentSection: + """ + Used by the ContentParser class to capture the information we + need when it is parsing the HTML. + """ + + def __init__( + self, + text: list[str] | None = None, + id_: str | None = None, + title: str | None = None, + ) -> None: + self.text = text or [] + self.id = id_ + self.title = title + + def __eq__(self, other): + return self.text == other.text and self.id == other.id and self.title == other.title + + +_HEADER_TAGS = tuple(f"h{x}" for x in range(1, 7)) + + +class ContentParser(HTMLParser): + """ + Given a block of HTML, group the content under the preceding + heading tags which can then be used for creating an index + for that section. + """ + + def __init__(self, *args, **kwargs) -> None: + super().__init__(*args, **kwargs) + + self.data: list[ContentSection] = [] + self.section: ContentSection | None = None + self.is_header_tag = False + self._stripped_html: list[str] = [] + + def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: + """Called at the start of every HTML tag.""" + + # We only care about the opening tag for headings. + if tag not in _HEADER_TAGS: + return + + # We are dealing with a new header, create a new section + # for it and assign the ID if it has one. + self.is_header_tag = True + self.section = ContentSection() + self.data.append(self.section) + + for attr in attrs: + if attr[0] == "id": + self.section.id = attr[1] + + def handle_endtag(self, tag: str) -> None: + """Called at the end of every HTML tag.""" + + # We only care about the opening tag for headings. + if tag not in _HEADER_TAGS: + return + + self.is_header_tag = False + + def handle_data(self, data: str) -> None: + """ + Called for the text contents of each tag. + """ + self._stripped_html.append(data) + + if self.section is None: + # This means we have some content at the start of the + # HTML before we reach a heading tag. We don't actually + # care about that content as it will be added to the + # overall page entry in the search. So just skip it. + return + + # If this is a header, then the data is the title. + # Otherwise it is content of something under that header + # section. + if self.is_header_tag: + self.section.title = data + else: + self.section.text.append(data.rstrip('\n')) + + @property + def stripped_html(self) -> str: + return '\n'.join(self._stripped_html) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/templates/search/lunr.js b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/templates/search/lunr.js new file mode 100644 index 0000000000000000000000000000000000000000..aca0a167f39f894d2d120b07b6e99265882c049c --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/templates/search/lunr.js @@ -0,0 +1,3475 @@ +/** + * lunr - http://lunrjs.com - A bit like Solr, but much smaller and not as bright - 2.3.9 + * Copyright (C) 2020 Oliver Nightingale + * @license MIT + */ + +;(function(){ + +/** + * A convenience function for configuring and constructing + * a new lunr Index. + * + * A lunr.Builder instance is created and the pipeline setup + * with a trimmer, stop word filter and stemmer. + * + * This builder object is yielded to the configuration function + * that is passed as a parameter, allowing the list of fields + * and other builder parameters to be customised. + * + * All documents _must_ be added within the passed config function. + * + * @example + * var idx = lunr(function () { + * this.field('title') + * this.field('body') + * this.ref('id') + * + * documents.forEach(function (doc) { + * this.add(doc) + * }, this) + * }) + * + * @see {@link lunr.Builder} + * @see {@link lunr.Pipeline} + * @see {@link lunr.trimmer} + * @see {@link lunr.stopWordFilter} + * @see {@link lunr.stemmer} + * @namespace {function} lunr + */ +var lunr = function (config) { + var builder = new lunr.Builder + + builder.pipeline.add( + lunr.trimmer, + lunr.stopWordFilter, + lunr.stemmer + ) + + builder.searchPipeline.add( + lunr.stemmer + ) + + config.call(builder, builder) + return builder.build() +} + +lunr.version = "2.3.9" +/*! + * lunr.utils + * Copyright (C) 2020 Oliver Nightingale + */ + +/** + * A namespace containing utils for the rest of the lunr library + * @namespace lunr.utils + */ +lunr.utils = {} + +/** + * Print a warning message to the console. + * + * @param {String} message The message to be printed. + * @memberOf lunr.utils + * @function + */ +lunr.utils.warn = (function (global) { + /* eslint-disable no-console */ + return function (message) { + if (global.console && console.warn) { + console.warn(message) + } + } + /* eslint-enable no-console */ +})(this) + +/** + * Convert an object to a string. + * + * In the case of `null` and `undefined` the function returns + * the empty string, in all other cases the result of calling + * `toString` on the passed object is returned. + * + * @param {Any} obj The object to convert to a string. + * @return {String} string representation of the passed object. + * @memberOf lunr.utils + */ +lunr.utils.asString = function (obj) { + if (obj === void 0 || obj === null) { + return "" + } else { + return obj.toString() + } +} + +/** + * Clones an object. + * + * Will create a copy of an existing object such that any mutations + * on the copy cannot affect the original. + * + * Only shallow objects are supported, passing a nested object to this + * function will cause a TypeError. + * + * Objects with primitives, and arrays of primitives are supported. + * + * @param {Object} obj The object to clone. + * @return {Object} a clone of the passed object. + * @throws {TypeError} when a nested object is passed. + * @memberOf Utils + */ +lunr.utils.clone = function (obj) { + if (obj === null || obj === undefined) { + return obj + } + + var clone = Object.create(null), + keys = Object.keys(obj) + + for (var i = 0; i < keys.length; i++) { + var key = keys[i], + val = obj[key] + + if (Array.isArray(val)) { + clone[key] = val.slice() + continue + } + + if (typeof val === 'string' || + typeof val === 'number' || + typeof val === 'boolean') { + clone[key] = val + continue + } + + throw new TypeError("clone is not deep and does not support nested objects") + } + + return clone +} +lunr.FieldRef = function (docRef, fieldName, stringValue) { + this.docRef = docRef + this.fieldName = fieldName + this._stringValue = stringValue +} + +lunr.FieldRef.joiner = "/" + +lunr.FieldRef.fromString = function (s) { + var n = s.indexOf(lunr.FieldRef.joiner) + + if (n === -1) { + throw "malformed field ref string" + } + + var fieldRef = s.slice(0, n), + docRef = s.slice(n + 1) + + return new lunr.FieldRef (docRef, fieldRef, s) +} + +lunr.FieldRef.prototype.toString = function () { + if (this._stringValue == undefined) { + this._stringValue = this.fieldName + lunr.FieldRef.joiner + this.docRef + } + + return this._stringValue +} +/*! + * lunr.Set + * Copyright (C) 2020 Oliver Nightingale + */ + +/** + * A lunr set. + * + * @constructor + */ +lunr.Set = function (elements) { + this.elements = Object.create(null) + + if (elements) { + this.length = elements.length + + for (var i = 0; i < this.length; i++) { + this.elements[elements[i]] = true + } + } else { + this.length = 0 + } +} + +/** + * A complete set that contains all elements. + * + * @static + * @readonly + * @type {lunr.Set} + */ +lunr.Set.complete = { + intersect: function (other) { + return other + }, + + union: function () { + return this + }, + + contains: function () { + return true + } +} + +/** + * An empty set that contains no elements. + * + * @static + * @readonly + * @type {lunr.Set} + */ +lunr.Set.empty = { + intersect: function () { + return this + }, + + union: function (other) { + return other + }, + + contains: function () { + return false + } +} + +/** + * Returns true if this set contains the specified object. + * + * @param {object} object - Object whose presence in this set is to be tested. + * @returns {boolean} - True if this set contains the specified object. + */ +lunr.Set.prototype.contains = function (object) { + return !!this.elements[object] +} + +/** + * Returns a new set containing only the elements that are present in both + * this set and the specified set. + * + * @param {lunr.Set} other - set to intersect with this set. + * @returns {lunr.Set} a new set that is the intersection of this and the specified set. + */ + +lunr.Set.prototype.intersect = function (other) { + var a, b, elements, intersection = [] + + if (other === lunr.Set.complete) { + return this + } + + if (other === lunr.Set.empty) { + return other + } + + if (this.length < other.length) { + a = this + b = other + } else { + a = other + b = this + } + + elements = Object.keys(a.elements) + + for (var i = 0; i < elements.length; i++) { + var element = elements[i] + if (element in b.elements) { + intersection.push(element) + } + } + + return new lunr.Set (intersection) +} + +/** + * Returns a new set combining the elements of this and the specified set. + * + * @param {lunr.Set} other - set to union with this set. + * @return {lunr.Set} a new set that is the union of this and the specified set. + */ + +lunr.Set.prototype.union = function (other) { + if (other === lunr.Set.complete) { + return lunr.Set.complete + } + + if (other === lunr.Set.empty) { + return this + } + + return new lunr.Set(Object.keys(this.elements).concat(Object.keys(other.elements))) +} +/** + * A function to calculate the inverse document frequency for + * a posting. This is shared between the builder and the index + * + * @private + * @param {object} posting - The posting for a given term + * @param {number} documentCount - The total number of documents. + */ +lunr.idf = function (posting, documentCount) { + var documentsWithTerm = 0 + + for (var fieldName in posting) { + if (fieldName == '_index') continue // Ignore the term index, its not a field + documentsWithTerm += Object.keys(posting[fieldName]).length + } + + var x = (documentCount - documentsWithTerm + 0.5) / (documentsWithTerm + 0.5) + + return Math.log(1 + Math.abs(x)) +} + +/** + * A token wraps a string representation of a token + * as it is passed through the text processing pipeline. + * + * @constructor + * @param {string} [str=''] - The string token being wrapped. + * @param {object} [metadata={}] - Metadata associated with this token. + */ +lunr.Token = function (str, metadata) { + this.str = str || "" + this.metadata = metadata || {} +} + +/** + * Returns the token string that is being wrapped by this object. + * + * @returns {string} + */ +lunr.Token.prototype.toString = function () { + return this.str +} + +/** + * A token update function is used when updating or optionally + * when cloning a token. + * + * @callback lunr.Token~updateFunction + * @param {string} str - The string representation of the token. + * @param {Object} metadata - All metadata associated with this token. + */ + +/** + * Applies the given function to the wrapped string token. + * + * @example + * token.update(function (str, metadata) { + * return str.toUpperCase() + * }) + * + * @param {lunr.Token~updateFunction} fn - A function to apply to the token string. + * @returns {lunr.Token} + */ +lunr.Token.prototype.update = function (fn) { + this.str = fn(this.str, this.metadata) + return this +} + +/** + * Creates a clone of this token. Optionally a function can be + * applied to the cloned token. + * + * @param {lunr.Token~updateFunction} [fn] - An optional function to apply to the cloned token. + * @returns {lunr.Token} + */ +lunr.Token.prototype.clone = function (fn) { + fn = fn || function (s) { return s } + return new lunr.Token (fn(this.str, this.metadata), this.metadata) +} +/*! + * lunr.tokenizer + * Copyright (C) 2020 Oliver Nightingale + */ + +/** + * A function for splitting a string into tokens ready to be inserted into + * the search index. Uses `lunr.tokenizer.separator` to split strings, change + * the value of this property to change how strings are split into tokens. + * + * This tokenizer will convert its parameter to a string by calling `toString` and + * then will split this string on the character in `lunr.tokenizer.separator`. + * Arrays will have their elements converted to strings and wrapped in a lunr.Token. + * + * Optional metadata can be passed to the tokenizer, this metadata will be cloned and + * added as metadata to every token that is created from the object to be tokenized. + * + * @static + * @param {?(string|object|object[])} obj - The object to convert into tokens + * @param {?object} metadata - Optional metadata to associate with every token + * @returns {lunr.Token[]} + * @see {@link lunr.Pipeline} + */ +lunr.tokenizer = function (obj, metadata) { + if (obj == null || obj == undefined) { + return [] + } + + if (Array.isArray(obj)) { + return obj.map(function (t) { + return new lunr.Token( + lunr.utils.asString(t).toLowerCase(), + lunr.utils.clone(metadata) + ) + }) + } + + var str = obj.toString().toLowerCase(), + len = str.length, + tokens = [] + + for (var sliceEnd = 0, sliceStart = 0; sliceEnd <= len; sliceEnd++) { + var char = str.charAt(sliceEnd), + sliceLength = sliceEnd - sliceStart + + if ((char.match(lunr.tokenizer.separator) || sliceEnd == len)) { + + if (sliceLength > 0) { + var tokenMetadata = lunr.utils.clone(metadata) || {} + tokenMetadata["position"] = [sliceStart, sliceLength] + tokenMetadata["index"] = tokens.length + + tokens.push( + new lunr.Token ( + str.slice(sliceStart, sliceEnd), + tokenMetadata + ) + ) + } + + sliceStart = sliceEnd + 1 + } + + } + + return tokens +} + +/** + * The separator used to split a string into tokens. Override this property to change the behaviour of + * `lunr.tokenizer` behaviour when tokenizing strings. By default this splits on whitespace and hyphens. + * + * @static + * @see lunr.tokenizer + */ +lunr.tokenizer.separator = /[\s\-]+/ +/*! + * lunr.Pipeline + * Copyright (C) 2020 Oliver Nightingale + */ + +/** + * lunr.Pipelines maintain an ordered list of functions to be applied to all + * tokens in documents entering the search index and queries being ran against + * the index. + * + * An instance of lunr.Index created with the lunr shortcut will contain a + * pipeline with a stop word filter and an English language stemmer. Extra + * functions can be added before or after either of these functions or these + * default functions can be removed. + * + * When run the pipeline will call each function in turn, passing a token, the + * index of that token in the original list of all tokens and finally a list of + * all the original tokens. + * + * The output of functions in the pipeline will be passed to the next function + * in the pipeline. To exclude a token from entering the index the function + * should return undefined, the rest of the pipeline will not be called with + * this token. + * + * For serialisation of pipelines to work, all functions used in an instance of + * a pipeline should be registered with lunr.Pipeline. Registered functions can + * then be loaded. If trying to load a serialised pipeline that uses functions + * that are not registered an error will be thrown. + * + * If not planning on serialising the pipeline then registering pipeline functions + * is not necessary. + * + * @constructor + */ +lunr.Pipeline = function () { + this._stack = [] +} + +lunr.Pipeline.registeredFunctions = Object.create(null) + +/** + * A pipeline function maps lunr.Token to lunr.Token. A lunr.Token contains the token + * string as well as all known metadata. A pipeline function can mutate the token string + * or mutate (or add) metadata for a given token. + * + * A pipeline function can indicate that the passed token should be discarded by returning + * null, undefined or an empty string. This token will not be passed to any downstream pipeline + * functions and will not be added to the index. + * + * Multiple tokens can be returned by returning an array of tokens. Each token will be passed + * to any downstream pipeline functions and all will returned tokens will be added to the index. + * + * Any number of pipeline functions may be chained together using a lunr.Pipeline. + * + * @interface lunr.PipelineFunction + * @param {lunr.Token} token - A token from the document being processed. + * @param {number} i - The index of this token in the complete list of tokens for this document/field. + * @param {lunr.Token[]} tokens - All tokens for this document/field. + * @returns {(?lunr.Token|lunr.Token[])} + */ + +/** + * Register a function with the pipeline. + * + * Functions that are used in the pipeline should be registered if the pipeline + * needs to be serialised, or a serialised pipeline needs to be loaded. + * + * Registering a function does not add it to a pipeline, functions must still be + * added to instances of the pipeline for them to be used when running a pipeline. + * + * @param {lunr.PipelineFunction} fn - The function to check for. + * @param {String} label - The label to register this function with + */ +lunr.Pipeline.registerFunction = function (fn, label) { + if (label in this.registeredFunctions) { + lunr.utils.warn('Overwriting existing registered function: ' + label) + } + + fn.label = label + lunr.Pipeline.registeredFunctions[fn.label] = fn +} + +/** + * Warns if the function is not registered as a Pipeline function. + * + * @param {lunr.PipelineFunction} fn - The function to check for. + * @private + */ +lunr.Pipeline.warnIfFunctionNotRegistered = function (fn) { + var isRegistered = fn.label && (fn.label in this.registeredFunctions) + + if (!isRegistered) { + lunr.utils.warn('Function is not registered with pipeline. This may cause problems when serialising the index.\n', fn) + } +} + +/** + * Loads a previously serialised pipeline. + * + * All functions to be loaded must already be registered with lunr.Pipeline. + * If any function from the serialised data has not been registered then an + * error will be thrown. + * + * @param {Object} serialised - The serialised pipeline to load. + * @returns {lunr.Pipeline} + */ +lunr.Pipeline.load = function (serialised) { + var pipeline = new lunr.Pipeline + + serialised.forEach(function (fnName) { + var fn = lunr.Pipeline.registeredFunctions[fnName] + + if (fn) { + pipeline.add(fn) + } else { + throw new Error('Cannot load unregistered function: ' + fnName) + } + }) + + return pipeline +} + +/** + * Adds new functions to the end of the pipeline. + * + * Logs a warning if the function has not been registered. + * + * @param {lunr.PipelineFunction[]} functions - Any number of functions to add to the pipeline. + */ +lunr.Pipeline.prototype.add = function () { + var fns = Array.prototype.slice.call(arguments) + + fns.forEach(function (fn) { + lunr.Pipeline.warnIfFunctionNotRegistered(fn) + this._stack.push(fn) + }, this) +} + +/** + * Adds a single function after a function that already exists in the + * pipeline. + * + * Logs a warning if the function has not been registered. + * + * @param {lunr.PipelineFunction} existingFn - A function that already exists in the pipeline. + * @param {lunr.PipelineFunction} newFn - The new function to add to the pipeline. + */ +lunr.Pipeline.prototype.after = function (existingFn, newFn) { + lunr.Pipeline.warnIfFunctionNotRegistered(newFn) + + var pos = this._stack.indexOf(existingFn) + if (pos == -1) { + throw new Error('Cannot find existingFn') + } + + pos = pos + 1 + this._stack.splice(pos, 0, newFn) +} + +/** + * Adds a single function before a function that already exists in the + * pipeline. + * + * Logs a warning if the function has not been registered. + * + * @param {lunr.PipelineFunction} existingFn - A function that already exists in the pipeline. + * @param {lunr.PipelineFunction} newFn - The new function to add to the pipeline. + */ +lunr.Pipeline.prototype.before = function (existingFn, newFn) { + lunr.Pipeline.warnIfFunctionNotRegistered(newFn) + + var pos = this._stack.indexOf(existingFn) + if (pos == -1) { + throw new Error('Cannot find existingFn') + } + + this._stack.splice(pos, 0, newFn) +} + +/** + * Removes a function from the pipeline. + * + * @param {lunr.PipelineFunction} fn The function to remove from the pipeline. + */ +lunr.Pipeline.prototype.remove = function (fn) { + var pos = this._stack.indexOf(fn) + if (pos == -1) { + return + } + + this._stack.splice(pos, 1) +} + +/** + * Runs the current list of functions that make up the pipeline against the + * passed tokens. + * + * @param {Array} tokens The tokens to run through the pipeline. + * @returns {Array} + */ +lunr.Pipeline.prototype.run = function (tokens) { + var stackLength = this._stack.length + + for (var i = 0; i < stackLength; i++) { + var fn = this._stack[i] + var memo = [] + + for (var j = 0; j < tokens.length; j++) { + var result = fn(tokens[j], j, tokens) + + if (result === null || result === void 0 || result === '') continue + + if (Array.isArray(result)) { + for (var k = 0; k < result.length; k++) { + memo.push(result[k]) + } + } else { + memo.push(result) + } + } + + tokens = memo + } + + return tokens +} + +/** + * Convenience method for passing a string through a pipeline and getting + * strings out. This method takes care of wrapping the passed string in a + * token and mapping the resulting tokens back to strings. + * + * @param {string} str - The string to pass through the pipeline. + * @param {?object} metadata - Optional metadata to associate with the token + * passed to the pipeline. + * @returns {string[]} + */ +lunr.Pipeline.prototype.runString = function (str, metadata) { + var token = new lunr.Token (str, metadata) + + return this.run([token]).map(function (t) { + return t.toString() + }) +} + +/** + * Resets the pipeline by removing any existing processors. + * + */ +lunr.Pipeline.prototype.reset = function () { + this._stack = [] +} + +/** + * Returns a representation of the pipeline ready for serialisation. + * + * Logs a warning if the function has not been registered. + * + * @returns {Array} + */ +lunr.Pipeline.prototype.toJSON = function () { + return this._stack.map(function (fn) { + lunr.Pipeline.warnIfFunctionNotRegistered(fn) + + return fn.label + }) +} +/*! + * lunr.Vector + * Copyright (C) 2020 Oliver Nightingale + */ + +/** + * A vector is used to construct the vector space of documents and queries. These + * vectors support operations to determine the similarity between two documents or + * a document and a query. + * + * Normally no parameters are required for initializing a vector, but in the case of + * loading a previously dumped vector the raw elements can be provided to the constructor. + * + * For performance reasons vectors are implemented with a flat array, where an elements + * index is immediately followed by its value. E.g. [index, value, index, value]. This + * allows the underlying array to be as sparse as possible and still offer decent + * performance when being used for vector calculations. + * + * @constructor + * @param {Number[]} [elements] - The flat list of element index and element value pairs. + */ +lunr.Vector = function (elements) { + this._magnitude = 0 + this.elements = elements || [] +} + + +/** + * Calculates the position within the vector to insert a given index. + * + * This is used internally by insert and upsert. If there are duplicate indexes then + * the position is returned as if the value for that index were to be updated, but it + * is the callers responsibility to check whether there is a duplicate at that index + * + * @param {Number} insertIdx - The index at which the element should be inserted. + * @returns {Number} + */ +lunr.Vector.prototype.positionForIndex = function (index) { + // For an empty vector the tuple can be inserted at the beginning + if (this.elements.length == 0) { + return 0 + } + + var start = 0, + end = this.elements.length / 2, + sliceLength = end - start, + pivotPoint = Math.floor(sliceLength / 2), + pivotIndex = this.elements[pivotPoint * 2] + + while (sliceLength > 1) { + if (pivotIndex < index) { + start = pivotPoint + } + + if (pivotIndex > index) { + end = pivotPoint + } + + if (pivotIndex == index) { + break + } + + sliceLength = end - start + pivotPoint = start + Math.floor(sliceLength / 2) + pivotIndex = this.elements[pivotPoint * 2] + } + + if (pivotIndex == index) { + return pivotPoint * 2 + } + + if (pivotIndex > index) { + return pivotPoint * 2 + } + + if (pivotIndex < index) { + return (pivotPoint + 1) * 2 + } +} + +/** + * Inserts an element at an index within the vector. + * + * Does not allow duplicates, will throw an error if there is already an entry + * for this index. + * + * @param {Number} insertIdx - The index at which the element should be inserted. + * @param {Number} val - The value to be inserted into the vector. + */ +lunr.Vector.prototype.insert = function (insertIdx, val) { + this.upsert(insertIdx, val, function () { + throw "duplicate index" + }) +} + +/** + * Inserts or updates an existing index within the vector. + * + * @param {Number} insertIdx - The index at which the element should be inserted. + * @param {Number} val - The value to be inserted into the vector. + * @param {function} fn - A function that is called for updates, the existing value and the + * requested value are passed as arguments + */ +lunr.Vector.prototype.upsert = function (insertIdx, val, fn) { + this._magnitude = 0 + var position = this.positionForIndex(insertIdx) + + if (this.elements[position] == insertIdx) { + this.elements[position + 1] = fn(this.elements[position + 1], val) + } else { + this.elements.splice(position, 0, insertIdx, val) + } +} + +/** + * Calculates the magnitude of this vector. + * + * @returns {Number} + */ +lunr.Vector.prototype.magnitude = function () { + if (this._magnitude) return this._magnitude + + var sumOfSquares = 0, + elementsLength = this.elements.length + + for (var i = 1; i < elementsLength; i += 2) { + var val = this.elements[i] + sumOfSquares += val * val + } + + return this._magnitude = Math.sqrt(sumOfSquares) +} + +/** + * Calculates the dot product of this vector and another vector. + * + * @param {lunr.Vector} otherVector - The vector to compute the dot product with. + * @returns {Number} + */ +lunr.Vector.prototype.dot = function (otherVector) { + var dotProduct = 0, + a = this.elements, b = otherVector.elements, + aLen = a.length, bLen = b.length, + aVal = 0, bVal = 0, + i = 0, j = 0 + + while (i < aLen && j < bLen) { + aVal = a[i], bVal = b[j] + if (aVal < bVal) { + i += 2 + } else if (aVal > bVal) { + j += 2 + } else if (aVal == bVal) { + dotProduct += a[i + 1] * b[j + 1] + i += 2 + j += 2 + } + } + + return dotProduct +} + +/** + * Calculates the similarity between this vector and another vector. + * + * @param {lunr.Vector} otherVector - The other vector to calculate the + * similarity with. + * @returns {Number} + */ +lunr.Vector.prototype.similarity = function (otherVector) { + return this.dot(otherVector) / this.magnitude() || 0 +} + +/** + * Converts the vector to an array of the elements within the vector. + * + * @returns {Number[]} + */ +lunr.Vector.prototype.toArray = function () { + var output = new Array (this.elements.length / 2) + + for (var i = 1, j = 0; i < this.elements.length; i += 2, j++) { + output[j] = this.elements[i] + } + + return output +} + +/** + * A JSON serializable representation of the vector. + * + * @returns {Number[]} + */ +lunr.Vector.prototype.toJSON = function () { + return this.elements +} +/* eslint-disable */ +/*! + * lunr.stemmer + * Copyright (C) 2020 Oliver Nightingale + * Includes code from - http://tartarus.org/~martin/PorterStemmer/js.txt + */ + +/** + * lunr.stemmer is an english language stemmer, this is a JavaScript + * implementation of the PorterStemmer taken from http://tartarus.org/~martin + * + * @static + * @implements {lunr.PipelineFunction} + * @param {lunr.Token} token - The string to stem + * @returns {lunr.Token} + * @see {@link lunr.Pipeline} + * @function + */ +lunr.stemmer = (function(){ + var step2list = { + "ational" : "ate", + "tional" : "tion", + "enci" : "ence", + "anci" : "ance", + "izer" : "ize", + "bli" : "ble", + "alli" : "al", + "entli" : "ent", + "eli" : "e", + "ousli" : "ous", + "ization" : "ize", + "ation" : "ate", + "ator" : "ate", + "alism" : "al", + "iveness" : "ive", + "fulness" : "ful", + "ousness" : "ous", + "aliti" : "al", + "iviti" : "ive", + "biliti" : "ble", + "logi" : "log" + }, + + step3list = { + "icate" : "ic", + "ative" : "", + "alize" : "al", + "iciti" : "ic", + "ical" : "ic", + "ful" : "", + "ness" : "" + }, + + c = "[^aeiou]", // consonant + v = "[aeiouy]", // vowel + C = c + "[^aeiouy]*", // consonant sequence + V = v + "[aeiou]*", // vowel sequence + + mgr0 = "^(" + C + ")?" + V + C, // [C]VC... is m>0 + meq1 = "^(" + C + ")?" + V + C + "(" + V + ")?$", // [C]VC[V] is m=1 + mgr1 = "^(" + C + ")?" + V + C + V + C, // [C]VCVC... is m>1 + s_v = "^(" + C + ")?" + v; // vowel in stem + + var re_mgr0 = new RegExp(mgr0); + var re_mgr1 = new RegExp(mgr1); + var re_meq1 = new RegExp(meq1); + var re_s_v = new RegExp(s_v); + + var re_1a = /^(.+?)(ss|i)es$/; + var re2_1a = /^(.+?)([^s])s$/; + var re_1b = /^(.+?)eed$/; + var re2_1b = /^(.+?)(ed|ing)$/; + var re_1b_2 = /.$/; + var re2_1b_2 = /(at|bl|iz)$/; + var re3_1b_2 = new RegExp("([^aeiouylsz])\\1$"); + var re4_1b_2 = new RegExp("^" + C + v + "[^aeiouwxy]$"); + + var re_1c = /^(.+?[^aeiou])y$/; + var re_2 = /^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/; + + var re_3 = /^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/; + + var re_4 = /^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/; + var re2_4 = /^(.+?)(s|t)(ion)$/; + + var re_5 = /^(.+?)e$/; + var re_5_1 = /ll$/; + var re3_5 = new RegExp("^" + C + v + "[^aeiouwxy]$"); + + var porterStemmer = function porterStemmer(w) { + var stem, + suffix, + firstch, + re, + re2, + re3, + re4; + + if (w.length < 3) { return w; } + + firstch = w.substr(0,1); + if (firstch == "y") { + w = firstch.toUpperCase() + w.substr(1); + } + + // Step 1a + re = re_1a + re2 = re2_1a; + + if (re.test(w)) { w = w.replace(re,"$1$2"); } + else if (re2.test(w)) { w = w.replace(re2,"$1$2"); } + + // Step 1b + re = re_1b; + re2 = re2_1b; + if (re.test(w)) { + var fp = re.exec(w); + re = re_mgr0; + if (re.test(fp[1])) { + re = re_1b_2; + w = w.replace(re,""); + } + } else if (re2.test(w)) { + var fp = re2.exec(w); + stem = fp[1]; + re2 = re_s_v; + if (re2.test(stem)) { + w = stem; + re2 = re2_1b_2; + re3 = re3_1b_2; + re4 = re4_1b_2; + if (re2.test(w)) { w = w + "e"; } + else if (re3.test(w)) { re = re_1b_2; w = w.replace(re,""); } + else if (re4.test(w)) { w = w + "e"; } + } + } + + // Step 1c - replace suffix y or Y by i if preceded by a non-vowel which is not the first letter of the word (so cry -> cri, by -> by, say -> say) + re = re_1c; + if (re.test(w)) { + var fp = re.exec(w); + stem = fp[1]; + w = stem + "i"; + } + + // Step 2 + re = re_2; + if (re.test(w)) { + var fp = re.exec(w); + stem = fp[1]; + suffix = fp[2]; + re = re_mgr0; + if (re.test(stem)) { + w = stem + step2list[suffix]; + } + } + + // Step 3 + re = re_3; + if (re.test(w)) { + var fp = re.exec(w); + stem = fp[1]; + suffix = fp[2]; + re = re_mgr0; + if (re.test(stem)) { + w = stem + step3list[suffix]; + } + } + + // Step 4 + re = re_4; + re2 = re2_4; + if (re.test(w)) { + var fp = re.exec(w); + stem = fp[1]; + re = re_mgr1; + if (re.test(stem)) { + w = stem; + } + } else if (re2.test(w)) { + var fp = re2.exec(w); + stem = fp[1] + fp[2]; + re2 = re_mgr1; + if (re2.test(stem)) { + w = stem; + } + } + + // Step 5 + re = re_5; + if (re.test(w)) { + var fp = re.exec(w); + stem = fp[1]; + re = re_mgr1; + re2 = re_meq1; + re3 = re3_5; + if (re.test(stem) || (re2.test(stem) && !(re3.test(stem)))) { + w = stem; + } + } + + re = re_5_1; + re2 = re_mgr1; + if (re.test(w) && re2.test(w)) { + re = re_1b_2; + w = w.replace(re,""); + } + + // and turn initial Y back to y + + if (firstch == "y") { + w = firstch.toLowerCase() + w.substr(1); + } + + return w; + }; + + return function (token) { + return token.update(porterStemmer); + } +})(); + +lunr.Pipeline.registerFunction(lunr.stemmer, 'stemmer') +/*! + * lunr.stopWordFilter + * Copyright (C) 2020 Oliver Nightingale + */ + +/** + * lunr.generateStopWordFilter builds a stopWordFilter function from the provided + * list of stop words. + * + * The built in lunr.stopWordFilter is built using this generator and can be used + * to generate custom stopWordFilters for applications or non English languages. + * + * @function + * @param {Array} token The token to pass through the filter + * @returns {lunr.PipelineFunction} + * @see lunr.Pipeline + * @see lunr.stopWordFilter + */ +lunr.generateStopWordFilter = function (stopWords) { + var words = stopWords.reduce(function (memo, stopWord) { + memo[stopWord] = stopWord + return memo + }, {}) + + return function (token) { + if (token && words[token.toString()] !== token.toString()) return token + } +} + +/** + * lunr.stopWordFilter is an English language stop word list filter, any words + * contained in the list will not be passed through the filter. + * + * This is intended to be used in the Pipeline. If the token does not pass the + * filter then undefined will be returned. + * + * @function + * @implements {lunr.PipelineFunction} + * @params {lunr.Token} token - A token to check for being a stop word. + * @returns {lunr.Token} + * @see {@link lunr.Pipeline} + */ +lunr.stopWordFilter = lunr.generateStopWordFilter([ + 'a', + 'able', + 'about', + 'across', + 'after', + 'all', + 'almost', + 'also', + 'am', + 'among', + 'an', + 'and', + 'any', + 'are', + 'as', + 'at', + 'be', + 'because', + 'been', + 'but', + 'by', + 'can', + 'cannot', + 'could', + 'dear', + 'did', + 'do', + 'does', + 'either', + 'else', + 'ever', + 'every', + 'for', + 'from', + 'get', + 'got', + 'had', + 'has', + 'have', + 'he', + 'her', + 'hers', + 'him', + 'his', + 'how', + 'however', + 'i', + 'if', + 'in', + 'into', + 'is', + 'it', + 'its', + 'just', + 'least', + 'let', + 'like', + 'likely', + 'may', + 'me', + 'might', + 'most', + 'must', + 'my', + 'neither', + 'no', + 'nor', + 'not', + 'of', + 'off', + 'often', + 'on', + 'only', + 'or', + 'other', + 'our', + 'own', + 'rather', + 'said', + 'say', + 'says', + 'she', + 'should', + 'since', + 'so', + 'some', + 'than', + 'that', + 'the', + 'their', + 'them', + 'then', + 'there', + 'these', + 'they', + 'this', + 'tis', + 'to', + 'too', + 'twas', + 'us', + 'wants', + 'was', + 'we', + 'were', + 'what', + 'when', + 'where', + 'which', + 'while', + 'who', + 'whom', + 'why', + 'will', + 'with', + 'would', + 'yet', + 'you', + 'your' +]) + +lunr.Pipeline.registerFunction(lunr.stopWordFilter, 'stopWordFilter') +/*! + * lunr.trimmer + * Copyright (C) 2020 Oliver Nightingale + */ + +/** + * lunr.trimmer is a pipeline function for trimming non word + * characters from the beginning and end of tokens before they + * enter the index. + * + * This implementation may not work correctly for non latin + * characters and should either be removed or adapted for use + * with languages with non-latin characters. + * + * @static + * @implements {lunr.PipelineFunction} + * @param {lunr.Token} token The token to pass through the filter + * @returns {lunr.Token} + * @see lunr.Pipeline + */ +lunr.trimmer = function (token) { + return token.update(function (s) { + return s.replace(/^\W+/, '').replace(/\W+$/, '') + }) +} + +lunr.Pipeline.registerFunction(lunr.trimmer, 'trimmer') +/*! + * lunr.TokenSet + * Copyright (C) 2020 Oliver Nightingale + */ + +/** + * A token set is used to store the unique list of all tokens + * within an index. Token sets are also used to represent an + * incoming query to the index, this query token set and index + * token set are then intersected to find which tokens to look + * up in the inverted index. + * + * A token set can hold multiple tokens, as in the case of the + * index token set, or it can hold a single token as in the + * case of a simple query token set. + * + * Additionally token sets are used to perform wildcard matching. + * Leading, contained and trailing wildcards are supported, and + * from this edit distance matching can also be provided. + * + * Token sets are implemented as a minimal finite state automata, + * where both common prefixes and suffixes are shared between tokens. + * This helps to reduce the space used for storing the token set. + * + * @constructor + */ +lunr.TokenSet = function () { + this.final = false + this.edges = {} + this.id = lunr.TokenSet._nextId + lunr.TokenSet._nextId += 1 +} + +/** + * Keeps track of the next, auto increment, identifier to assign + * to a new tokenSet. + * + * TokenSets require a unique identifier to be correctly minimised. + * + * @private + */ +lunr.TokenSet._nextId = 1 + +/** + * Creates a TokenSet instance from the given sorted array of words. + * + * @param {String[]} arr - A sorted array of strings to create the set from. + * @returns {lunr.TokenSet} + * @throws Will throw an error if the input array is not sorted. + */ +lunr.TokenSet.fromArray = function (arr) { + var builder = new lunr.TokenSet.Builder + + for (var i = 0, len = arr.length; i < len; i++) { + builder.insert(arr[i]) + } + + builder.finish() + return builder.root +} + +/** + * Creates a token set from a query clause. + * + * @private + * @param {Object} clause - A single clause from lunr.Query. + * @param {string} clause.term - The query clause term. + * @param {number} [clause.editDistance] - The optional edit distance for the term. + * @returns {lunr.TokenSet} + */ +lunr.TokenSet.fromClause = function (clause) { + if ('editDistance' in clause) { + return lunr.TokenSet.fromFuzzyString(clause.term, clause.editDistance) + } else { + return lunr.TokenSet.fromString(clause.term) + } +} + +/** + * Creates a token set representing a single string with a specified + * edit distance. + * + * Insertions, deletions, substitutions and transpositions are each + * treated as an edit distance of 1. + * + * Increasing the allowed edit distance will have a dramatic impact + * on the performance of both creating and intersecting these TokenSets. + * It is advised to keep the edit distance less than 3. + * + * @param {string} str - The string to create the token set from. + * @param {number} editDistance - The allowed edit distance to match. + * @returns {lunr.Vector} + */ +lunr.TokenSet.fromFuzzyString = function (str, editDistance) { + var root = new lunr.TokenSet + + var stack = [{ + node: root, + editsRemaining: editDistance, + str: str + }] + + while (stack.length) { + var frame = stack.pop() + + // no edit + if (frame.str.length > 0) { + var char = frame.str.charAt(0), + noEditNode + + if (char in frame.node.edges) { + noEditNode = frame.node.edges[char] + } else { + noEditNode = new lunr.TokenSet + frame.node.edges[char] = noEditNode + } + + if (frame.str.length == 1) { + noEditNode.final = true + } + + stack.push({ + node: noEditNode, + editsRemaining: frame.editsRemaining, + str: frame.str.slice(1) + }) + } + + if (frame.editsRemaining == 0) { + continue + } + + // insertion + if ("*" in frame.node.edges) { + var insertionNode = frame.node.edges["*"] + } else { + var insertionNode = new lunr.TokenSet + frame.node.edges["*"] = insertionNode + } + + if (frame.str.length == 0) { + insertionNode.final = true + } + + stack.push({ + node: insertionNode, + editsRemaining: frame.editsRemaining - 1, + str: frame.str + }) + + // deletion + // can only do a deletion if we have enough edits remaining + // and if there are characters left to delete in the string + if (frame.str.length > 1) { + stack.push({ + node: frame.node, + editsRemaining: frame.editsRemaining - 1, + str: frame.str.slice(1) + }) + } + + // deletion + // just removing the last character from the str + if (frame.str.length == 1) { + frame.node.final = true + } + + // substitution + // can only do a substitution if we have enough edits remaining + // and if there are characters left to substitute + if (frame.str.length >= 1) { + if ("*" in frame.node.edges) { + var substitutionNode = frame.node.edges["*"] + } else { + var substitutionNode = new lunr.TokenSet + frame.node.edges["*"] = substitutionNode + } + + if (frame.str.length == 1) { + substitutionNode.final = true + } + + stack.push({ + node: substitutionNode, + editsRemaining: frame.editsRemaining - 1, + str: frame.str.slice(1) + }) + } + + // transposition + // can only do a transposition if there are edits remaining + // and there are enough characters to transpose + if (frame.str.length > 1) { + var charA = frame.str.charAt(0), + charB = frame.str.charAt(1), + transposeNode + + if (charB in frame.node.edges) { + transposeNode = frame.node.edges[charB] + } else { + transposeNode = new lunr.TokenSet + frame.node.edges[charB] = transposeNode + } + + if (frame.str.length == 1) { + transposeNode.final = true + } + + stack.push({ + node: transposeNode, + editsRemaining: frame.editsRemaining - 1, + str: charA + frame.str.slice(2) + }) + } + } + + return root +} + +/** + * Creates a TokenSet from a string. + * + * The string may contain one or more wildcard characters (*) + * that will allow wildcard matching when intersecting with + * another TokenSet. + * + * @param {string} str - The string to create a TokenSet from. + * @returns {lunr.TokenSet} + */ +lunr.TokenSet.fromString = function (str) { + var node = new lunr.TokenSet, + root = node + + /* + * Iterates through all characters within the passed string + * appending a node for each character. + * + * When a wildcard character is found then a self + * referencing edge is introduced to continually match + * any number of any characters. + */ + for (var i = 0, len = str.length; i < len; i++) { + var char = str[i], + final = (i == len - 1) + + if (char == "*") { + node.edges[char] = node + node.final = final + + } else { + var next = new lunr.TokenSet + next.final = final + + node.edges[char] = next + node = next + } + } + + return root +} + +/** + * Converts this TokenSet into an array of strings + * contained within the TokenSet. + * + * This is not intended to be used on a TokenSet that + * contains wildcards, in these cases the results are + * undefined and are likely to cause an infinite loop. + * + * @returns {string[]} + */ +lunr.TokenSet.prototype.toArray = function () { + var words = [] + + var stack = [{ + prefix: "", + node: this + }] + + while (stack.length) { + var frame = stack.pop(), + edges = Object.keys(frame.node.edges), + len = edges.length + + if (frame.node.final) { + /* In Safari, at this point the prefix is sometimes corrupted, see: + * https://github.com/olivernn/lunr.js/issues/279 Calling any + * String.prototype method forces Safari to "cast" this string to what + * it's supposed to be, fixing the bug. */ + frame.prefix.charAt(0) + words.push(frame.prefix) + } + + for (var i = 0; i < len; i++) { + var edge = edges[i] + + stack.push({ + prefix: frame.prefix.concat(edge), + node: frame.node.edges[edge] + }) + } + } + + return words +} + +/** + * Generates a string representation of a TokenSet. + * + * This is intended to allow TokenSets to be used as keys + * in objects, largely to aid the construction and minimisation + * of a TokenSet. As such it is not designed to be a human + * friendly representation of the TokenSet. + * + * @returns {string} + */ +lunr.TokenSet.prototype.toString = function () { + // NOTE: Using Object.keys here as this.edges is very likely + // to enter 'hash-mode' with many keys being added + // + // avoiding a for-in loop here as it leads to the function + // being de-optimised (at least in V8). From some simple + // benchmarks the performance is comparable, but allowing + // V8 to optimize may mean easy performance wins in the future. + + if (this._str) { + return this._str + } + + var str = this.final ? '1' : '0', + labels = Object.keys(this.edges).sort(), + len = labels.length + + for (var i = 0; i < len; i++) { + var label = labels[i], + node = this.edges[label] + + str = str + label + node.id + } + + return str +} + +/** + * Returns a new TokenSet that is the intersection of + * this TokenSet and the passed TokenSet. + * + * This intersection will take into account any wildcards + * contained within the TokenSet. + * + * @param {lunr.TokenSet} b - An other TokenSet to intersect with. + * @returns {lunr.TokenSet} + */ +lunr.TokenSet.prototype.intersect = function (b) { + var output = new lunr.TokenSet, + frame = undefined + + var stack = [{ + qNode: b, + output: output, + node: this + }] + + while (stack.length) { + frame = stack.pop() + + // NOTE: As with the #toString method, we are using + // Object.keys and a for loop instead of a for-in loop + // as both of these objects enter 'hash' mode, causing + // the function to be de-optimised in V8 + var qEdges = Object.keys(frame.qNode.edges), + qLen = qEdges.length, + nEdges = Object.keys(frame.node.edges), + nLen = nEdges.length + + for (var q = 0; q < qLen; q++) { + var qEdge = qEdges[q] + + for (var n = 0; n < nLen; n++) { + var nEdge = nEdges[n] + + if (nEdge == qEdge || qEdge == '*') { + var node = frame.node.edges[nEdge], + qNode = frame.qNode.edges[qEdge], + final = node.final && qNode.final, + next = undefined + + if (nEdge in frame.output.edges) { + // an edge already exists for this character + // no need to create a new node, just set the finality + // bit unless this node is already final + next = frame.output.edges[nEdge] + next.final = next.final || final + + } else { + // no edge exists yet, must create one + // set the finality bit and insert it + // into the output + next = new lunr.TokenSet + next.final = final + frame.output.edges[nEdge] = next + } + + stack.push({ + qNode: qNode, + output: next, + node: node + }) + } + } + } + } + + return output +} +lunr.TokenSet.Builder = function () { + this.previousWord = "" + this.root = new lunr.TokenSet + this.uncheckedNodes = [] + this.minimizedNodes = {} +} + +lunr.TokenSet.Builder.prototype.insert = function (word) { + var node, + commonPrefix = 0 + + if (word < this.previousWord) { + throw new Error ("Out of order word insertion") + } + + for (var i = 0; i < word.length && i < this.previousWord.length; i++) { + if (word[i] != this.previousWord[i]) break + commonPrefix++ + } + + this.minimize(commonPrefix) + + if (this.uncheckedNodes.length == 0) { + node = this.root + } else { + node = this.uncheckedNodes[this.uncheckedNodes.length - 1].child + } + + for (var i = commonPrefix; i < word.length; i++) { + var nextNode = new lunr.TokenSet, + char = word[i] + + node.edges[char] = nextNode + + this.uncheckedNodes.push({ + parent: node, + char: char, + child: nextNode + }) + + node = nextNode + } + + node.final = true + this.previousWord = word +} + +lunr.TokenSet.Builder.prototype.finish = function () { + this.minimize(0) +} + +lunr.TokenSet.Builder.prototype.minimize = function (downTo) { + for (var i = this.uncheckedNodes.length - 1; i >= downTo; i--) { + var node = this.uncheckedNodes[i], + childKey = node.child.toString() + + if (childKey in this.minimizedNodes) { + node.parent.edges[node.char] = this.minimizedNodes[childKey] + } else { + // Cache the key for this node since + // we know it can't change anymore + node.child._str = childKey + + this.minimizedNodes[childKey] = node.child + } + + this.uncheckedNodes.pop() + } +} +/*! + * lunr.Index + * Copyright (C) 2020 Oliver Nightingale + */ + +/** + * An index contains the built index of all documents and provides a query interface + * to the index. + * + * Usually instances of lunr.Index will not be created using this constructor, instead + * lunr.Builder should be used to construct new indexes, or lunr.Index.load should be + * used to load previously built and serialized indexes. + * + * @constructor + * @param {Object} attrs - The attributes of the built search index. + * @param {Object} attrs.invertedIndex - An index of term/field to document reference. + * @param {Object} attrs.fieldVectors - Field vectors + * @param {lunr.TokenSet} attrs.tokenSet - An set of all corpus tokens. + * @param {string[]} attrs.fields - The names of indexed document fields. + * @param {lunr.Pipeline} attrs.pipeline - The pipeline to use for search terms. + */ +lunr.Index = function (attrs) { + this.invertedIndex = attrs.invertedIndex + this.fieldVectors = attrs.fieldVectors + this.tokenSet = attrs.tokenSet + this.fields = attrs.fields + this.pipeline = attrs.pipeline +} + +/** + * A result contains details of a document matching a search query. + * @typedef {Object} lunr.Index~Result + * @property {string} ref - The reference of the document this result represents. + * @property {number} score - A number between 0 and 1 representing how similar this document is to the query. + * @property {lunr.MatchData} matchData - Contains metadata about this match including which term(s) caused the match. + */ + +/** + * Although lunr provides the ability to create queries using lunr.Query, it also provides a simple + * query language which itself is parsed into an instance of lunr.Query. + * + * For programmatically building queries it is advised to directly use lunr.Query, the query language + * is best used for human entered text rather than program generated text. + * + * At its simplest queries can just be a single term, e.g. `hello`, multiple terms are also supported + * and will be combined with OR, e.g `hello world` will match documents that contain either 'hello' + * or 'world', though those that contain both will rank higher in the results. + * + * Wildcards can be included in terms to match one or more unspecified characters, these wildcards can + * be inserted anywhere within the term, and more than one wildcard can exist in a single term. Adding + * wildcards will increase the number of documents that will be found but can also have a negative + * impact on query performance, especially with wildcards at the beginning of a term. + * + * Terms can be restricted to specific fields, e.g. `title:hello`, only documents with the term + * hello in the title field will match this query. Using a field not present in the index will lead + * to an error being thrown. + * + * Modifiers can also be added to terms, lunr supports edit distance and boost modifiers on terms. A term + * boost will make documents matching that term score higher, e.g. `foo^5`. Edit distance is also supported + * to provide fuzzy matching, e.g. 'hello~2' will match documents with hello with an edit distance of 2. + * Avoid large values for edit distance to improve query performance. + * + * Each term also supports a presence modifier. By default a term's presence in document is optional, however + * this can be changed to either required or prohibited. For a term's presence to be required in a document the + * term should be prefixed with a '+', e.g. `+foo bar` is a search for documents that must contain 'foo' and + * optionally contain 'bar'. Conversely a leading '-' sets the terms presence to prohibited, i.e. it must not + * appear in a document, e.g. `-foo bar` is a search for documents that do not contain 'foo' but may contain 'bar'. + * + * To escape special characters the backslash character '\' can be used, this allows searches to include + * characters that would normally be considered modifiers, e.g. `foo\~2` will search for a term "foo~2" instead + * of attempting to apply a boost of 2 to the search term "foo". + * + * @typedef {string} lunr.Index~QueryString + * @example Simple single term query + * hello + * @example Multiple term query + * hello world + * @example term scoped to a field + * title:hello + * @example term with a boost of 10 + * hello^10 + * @example term with an edit distance of 2 + * hello~2 + * @example terms with presence modifiers + * -foo +bar baz + */ + +/** + * Performs a search against the index using lunr query syntax. + * + * Results will be returned sorted by their score, the most relevant results + * will be returned first. For details on how the score is calculated, please see + * the {@link https://lunrjs.com/guides/searching.html#scoring|guide}. + * + * For more programmatic querying use lunr.Index#query. + * + * @param {lunr.Index~QueryString} queryString - A string containing a lunr query. + * @throws {lunr.QueryParseError} If the passed query string cannot be parsed. + * @returns {lunr.Index~Result[]} + */ +lunr.Index.prototype.search = function (queryString) { + return this.query(function (query) { + var parser = new lunr.QueryParser(queryString, query) + parser.parse() + }) +} + +/** + * A query builder callback provides a query object to be used to express + * the query to perform on the index. + * + * @callback lunr.Index~queryBuilder + * @param {lunr.Query} query - The query object to build up. + * @this lunr.Query + */ + +/** + * Performs a query against the index using the yielded lunr.Query object. + * + * If performing programmatic queries against the index, this method is preferred + * over lunr.Index#search so as to avoid the additional query parsing overhead. + * + * A query object is yielded to the supplied function which should be used to + * express the query to be run against the index. + * + * Note that although this function takes a callback parameter it is _not_ an + * asynchronous operation, the callback is just yielded a query object to be + * customized. + * + * @param {lunr.Index~queryBuilder} fn - A function that is used to build the query. + * @returns {lunr.Index~Result[]} + */ +lunr.Index.prototype.query = function (fn) { + // for each query clause + // * process terms + // * expand terms from token set + // * find matching documents and metadata + // * get document vectors + // * score documents + + var query = new lunr.Query(this.fields), + matchingFields = Object.create(null), + queryVectors = Object.create(null), + termFieldCache = Object.create(null), + requiredMatches = Object.create(null), + prohibitedMatches = Object.create(null) + + /* + * To support field level boosts a query vector is created per + * field. An empty vector is eagerly created to support negated + * queries. + */ + for (var i = 0; i < this.fields.length; i++) { + queryVectors[this.fields[i]] = new lunr.Vector + } + + fn.call(query, query) + + for (var i = 0; i < query.clauses.length; i++) { + /* + * Unless the pipeline has been disabled for this term, which is + * the case for terms with wildcards, we need to pass the clause + * term through the search pipeline. A pipeline returns an array + * of processed terms. Pipeline functions may expand the passed + * term, which means we may end up performing multiple index lookups + * for a single query term. + */ + var clause = query.clauses[i], + terms = null, + clauseMatches = lunr.Set.empty + + if (clause.usePipeline) { + terms = this.pipeline.runString(clause.term, { + fields: clause.fields + }) + } else { + terms = [clause.term] + } + + for (var m = 0; m < terms.length; m++) { + var term = terms[m] + + /* + * Each term returned from the pipeline needs to use the same query + * clause object, e.g. the same boost and or edit distance. The + * simplest way to do this is to re-use the clause object but mutate + * its term property. + */ + clause.term = term + + /* + * From the term in the clause we create a token set which will then + * be used to intersect the indexes token set to get a list of terms + * to lookup in the inverted index + */ + var termTokenSet = lunr.TokenSet.fromClause(clause), + expandedTerms = this.tokenSet.intersect(termTokenSet).toArray() + + /* + * If a term marked as required does not exist in the tokenSet it is + * impossible for the search to return any matches. We set all the field + * scoped required matches set to empty and stop examining any further + * clauses. + */ + if (expandedTerms.length === 0 && clause.presence === lunr.Query.presence.REQUIRED) { + for (var k = 0; k < clause.fields.length; k++) { + var field = clause.fields[k] + requiredMatches[field] = lunr.Set.empty + } + + break + } + + for (var j = 0; j < expandedTerms.length; j++) { + /* + * For each term get the posting and termIndex, this is required for + * building the query vector. + */ + var expandedTerm = expandedTerms[j], + posting = this.invertedIndex[expandedTerm], + termIndex = posting._index + + for (var k = 0; k < clause.fields.length; k++) { + /* + * For each field that this query term is scoped by (by default + * all fields are in scope) we need to get all the document refs + * that have this term in that field. + * + * The posting is the entry in the invertedIndex for the matching + * term from above. + */ + var field = clause.fields[k], + fieldPosting = posting[field], + matchingDocumentRefs = Object.keys(fieldPosting), + termField = expandedTerm + "/" + field, + matchingDocumentsSet = new lunr.Set(matchingDocumentRefs) + + /* + * if the presence of this term is required ensure that the matching + * documents are added to the set of required matches for this clause. + * + */ + if (clause.presence == lunr.Query.presence.REQUIRED) { + clauseMatches = clauseMatches.union(matchingDocumentsSet) + + if (requiredMatches[field] === undefined) { + requiredMatches[field] = lunr.Set.complete + } + } + + /* + * if the presence of this term is prohibited ensure that the matching + * documents are added to the set of prohibited matches for this field, + * creating that set if it does not yet exist. + */ + if (clause.presence == lunr.Query.presence.PROHIBITED) { + if (prohibitedMatches[field] === undefined) { + prohibitedMatches[field] = lunr.Set.empty + } + + prohibitedMatches[field] = prohibitedMatches[field].union(matchingDocumentsSet) + + /* + * Prohibited matches should not be part of the query vector used for + * similarity scoring and no metadata should be extracted so we continue + * to the next field + */ + continue + } + + /* + * The query field vector is populated using the termIndex found for + * the term and a unit value with the appropriate boost applied. + * Using upsert because there could already be an entry in the vector + * for the term we are working with. In that case we just add the scores + * together. + */ + queryVectors[field].upsert(termIndex, clause.boost, function (a, b) { return a + b }) + + /** + * If we've already seen this term, field combo then we've already collected + * the matching documents and metadata, no need to go through all that again + */ + if (termFieldCache[termField]) { + continue + } + + for (var l = 0; l < matchingDocumentRefs.length; l++) { + /* + * All metadata for this term/field/document triple + * are then extracted and collected into an instance + * of lunr.MatchData ready to be returned in the query + * results + */ + var matchingDocumentRef = matchingDocumentRefs[l], + matchingFieldRef = new lunr.FieldRef (matchingDocumentRef, field), + metadata = fieldPosting[matchingDocumentRef], + fieldMatch + + if ((fieldMatch = matchingFields[matchingFieldRef]) === undefined) { + matchingFields[matchingFieldRef] = new lunr.MatchData (expandedTerm, field, metadata) + } else { + fieldMatch.add(expandedTerm, field, metadata) + } + + } + + termFieldCache[termField] = true + } + } + } + + /** + * If the presence was required we need to update the requiredMatches field sets. + * We do this after all fields for the term have collected their matches because + * the clause terms presence is required in _any_ of the fields not _all_ of the + * fields. + */ + if (clause.presence === lunr.Query.presence.REQUIRED) { + for (var k = 0; k < clause.fields.length; k++) { + var field = clause.fields[k] + requiredMatches[field] = requiredMatches[field].intersect(clauseMatches) + } + } + } + + /** + * Need to combine the field scoped required and prohibited + * matching documents into a global set of required and prohibited + * matches + */ + var allRequiredMatches = lunr.Set.complete, + allProhibitedMatches = lunr.Set.empty + + for (var i = 0; i < this.fields.length; i++) { + var field = this.fields[i] + + if (requiredMatches[field]) { + allRequiredMatches = allRequiredMatches.intersect(requiredMatches[field]) + } + + if (prohibitedMatches[field]) { + allProhibitedMatches = allProhibitedMatches.union(prohibitedMatches[field]) + } + } + + var matchingFieldRefs = Object.keys(matchingFields), + results = [], + matches = Object.create(null) + + /* + * If the query is negated (contains only prohibited terms) + * we need to get _all_ fieldRefs currently existing in the + * index. This is only done when we know that the query is + * entirely prohibited terms to avoid any cost of getting all + * fieldRefs unnecessarily. + * + * Additionally, blank MatchData must be created to correctly + * populate the results. + */ + if (query.isNegated()) { + matchingFieldRefs = Object.keys(this.fieldVectors) + + for (var i = 0; i < matchingFieldRefs.length; i++) { + var matchingFieldRef = matchingFieldRefs[i] + var fieldRef = lunr.FieldRef.fromString(matchingFieldRef) + matchingFields[matchingFieldRef] = new lunr.MatchData + } + } + + for (var i = 0; i < matchingFieldRefs.length; i++) { + /* + * Currently we have document fields that match the query, but we + * need to return documents. The matchData and scores are combined + * from multiple fields belonging to the same document. + * + * Scores are calculated by field, using the query vectors created + * above, and combined into a final document score using addition. + */ + var fieldRef = lunr.FieldRef.fromString(matchingFieldRefs[i]), + docRef = fieldRef.docRef + + if (!allRequiredMatches.contains(docRef)) { + continue + } + + if (allProhibitedMatches.contains(docRef)) { + continue + } + + var fieldVector = this.fieldVectors[fieldRef], + score = queryVectors[fieldRef.fieldName].similarity(fieldVector), + docMatch + + if ((docMatch = matches[docRef]) !== undefined) { + docMatch.score += score + docMatch.matchData.combine(matchingFields[fieldRef]) + } else { + var match = { + ref: docRef, + score: score, + matchData: matchingFields[fieldRef] + } + matches[docRef] = match + results.push(match) + } + } + + /* + * Sort the results objects by score, highest first. + */ + return results.sort(function (a, b) { + return b.score - a.score + }) +} + +/** + * Prepares the index for JSON serialization. + * + * The schema for this JSON blob will be described in a + * separate JSON schema file. + * + * @returns {Object} + */ +lunr.Index.prototype.toJSON = function () { + var invertedIndex = Object.keys(this.invertedIndex) + .sort() + .map(function (term) { + return [term, this.invertedIndex[term]] + }, this) + + var fieldVectors = Object.keys(this.fieldVectors) + .map(function (ref) { + return [ref, this.fieldVectors[ref].toJSON()] + }, this) + + return { + version: lunr.version, + fields: this.fields, + fieldVectors: fieldVectors, + invertedIndex: invertedIndex, + pipeline: this.pipeline.toJSON() + } +} + +/** + * Loads a previously serialized lunr.Index + * + * @param {Object} serializedIndex - A previously serialized lunr.Index + * @returns {lunr.Index} + */ +lunr.Index.load = function (serializedIndex) { + var attrs = {}, + fieldVectors = {}, + serializedVectors = serializedIndex.fieldVectors, + invertedIndex = Object.create(null), + serializedInvertedIndex = serializedIndex.invertedIndex, + tokenSetBuilder = new lunr.TokenSet.Builder, + pipeline = lunr.Pipeline.load(serializedIndex.pipeline) + + if (serializedIndex.version != lunr.version) { + lunr.utils.warn("Version mismatch when loading serialised index. Current version of lunr '" + lunr.version + "' does not match serialized index '" + serializedIndex.version + "'") + } + + for (var i = 0; i < serializedVectors.length; i++) { + var tuple = serializedVectors[i], + ref = tuple[0], + elements = tuple[1] + + fieldVectors[ref] = new lunr.Vector(elements) + } + + for (var i = 0; i < serializedInvertedIndex.length; i++) { + var tuple = serializedInvertedIndex[i], + term = tuple[0], + posting = tuple[1] + + tokenSetBuilder.insert(term) + invertedIndex[term] = posting + } + + tokenSetBuilder.finish() + + attrs.fields = serializedIndex.fields + + attrs.fieldVectors = fieldVectors + attrs.invertedIndex = invertedIndex + attrs.tokenSet = tokenSetBuilder.root + attrs.pipeline = pipeline + + return new lunr.Index(attrs) +} +/*! + * lunr.Builder + * Copyright (C) 2020 Oliver Nightingale + */ + +/** + * lunr.Builder performs indexing on a set of documents and + * returns instances of lunr.Index ready for querying. + * + * All configuration of the index is done via the builder, the + * fields to index, the document reference, the text processing + * pipeline and document scoring parameters are all set on the + * builder before indexing. + * + * @constructor + * @property {string} _ref - Internal reference to the document reference field. + * @property {string[]} _fields - Internal reference to the document fields to index. + * @property {object} invertedIndex - The inverted index maps terms to document fields. + * @property {object} documentTermFrequencies - Keeps track of document term frequencies. + * @property {object} documentLengths - Keeps track of the length of documents added to the index. + * @property {lunr.tokenizer} tokenizer - Function for splitting strings into tokens for indexing. + * @property {lunr.Pipeline} pipeline - The pipeline performs text processing on tokens before indexing. + * @property {lunr.Pipeline} searchPipeline - A pipeline for processing search terms before querying the index. + * @property {number} documentCount - Keeps track of the total number of documents indexed. + * @property {number} _b - A parameter to control field length normalization, setting this to 0 disabled normalization, 1 fully normalizes field lengths, the default value is 0.75. + * @property {number} _k1 - A parameter to control how quickly an increase in term frequency results in term frequency saturation, the default value is 1.2. + * @property {number} termIndex - A counter incremented for each unique term, used to identify a terms position in the vector space. + * @property {array} metadataWhitelist - A list of metadata keys that have been whitelisted for entry in the index. + */ +lunr.Builder = function () { + this._ref = "id" + this._fields = Object.create(null) + this._documents = Object.create(null) + this.invertedIndex = Object.create(null) + this.fieldTermFrequencies = {} + this.fieldLengths = {} + this.tokenizer = lunr.tokenizer + this.pipeline = new lunr.Pipeline + this.searchPipeline = new lunr.Pipeline + this.documentCount = 0 + this._b = 0.75 + this._k1 = 1.2 + this.termIndex = 0 + this.metadataWhitelist = [] +} + +/** + * Sets the document field used as the document reference. Every document must have this field. + * The type of this field in the document should be a string, if it is not a string it will be + * coerced into a string by calling toString. + * + * The default ref is 'id'. + * + * The ref should _not_ be changed during indexing, it should be set before any documents are + * added to the index. Changing it during indexing can lead to inconsistent results. + * + * @param {string} ref - The name of the reference field in the document. + */ +lunr.Builder.prototype.ref = function (ref) { + this._ref = ref +} + +/** + * A function that is used to extract a field from a document. + * + * Lunr expects a field to be at the top level of a document, if however the field + * is deeply nested within a document an extractor function can be used to extract + * the right field for indexing. + * + * @callback fieldExtractor + * @param {object} doc - The document being added to the index. + * @returns {?(string|object|object[])} obj - The object that will be indexed for this field. + * @example Extracting a nested field + * function (doc) { return doc.nested.field } + */ + +/** + * Adds a field to the list of document fields that will be indexed. Every document being + * indexed should have this field. Null values for this field in indexed documents will + * not cause errors but will limit the chance of that document being retrieved by searches. + * + * All fields should be added before adding documents to the index. Adding fields after + * a document has been indexed will have no effect on already indexed documents. + * + * Fields can be boosted at build time. This allows terms within that field to have more + * importance when ranking search results. Use a field boost to specify that matches within + * one field are more important than other fields. + * + * @param {string} fieldName - The name of a field to index in all documents. + * @param {object} attributes - Optional attributes associated with this field. + * @param {number} [attributes.boost=1] - Boost applied to all terms within this field. + * @param {fieldExtractor} [attributes.extractor] - Function to extract a field from a document. + * @throws {RangeError} fieldName cannot contain unsupported characters '/' + */ +lunr.Builder.prototype.field = function (fieldName, attributes) { + if (/\//.test(fieldName)) { + throw new RangeError ("Field '" + fieldName + "' contains illegal character '/'") + } + + this._fields[fieldName] = attributes || {} +} + +/** + * A parameter to tune the amount of field length normalisation that is applied when + * calculating relevance scores. A value of 0 will completely disable any normalisation + * and a value of 1 will fully normalise field lengths. The default is 0.75. Values of b + * will be clamped to the range 0 - 1. + * + * @param {number} number - The value to set for this tuning parameter. + */ +lunr.Builder.prototype.b = function (number) { + if (number < 0) { + this._b = 0 + } else if (number > 1) { + this._b = 1 + } else { + this._b = number + } +} + +/** + * A parameter that controls the speed at which a rise in term frequency results in term + * frequency saturation. The default value is 1.2. Setting this to a higher value will give + * slower saturation levels, a lower value will result in quicker saturation. + * + * @param {number} number - The value to set for this tuning parameter. + */ +lunr.Builder.prototype.k1 = function (number) { + this._k1 = number +} + +/** + * Adds a document to the index. + * + * Before adding fields to the index the index should have been fully setup, with the document + * ref and all fields to index already having been specified. + * + * The document must have a field name as specified by the ref (by default this is 'id') and + * it should have all fields defined for indexing, though null or undefined values will not + * cause errors. + * + * Entire documents can be boosted at build time. Applying a boost to a document indicates that + * this document should rank higher in search results than other documents. + * + * @param {object} doc - The document to add to the index. + * @param {object} attributes - Optional attributes associated with this document. + * @param {number} [attributes.boost=1] - Boost applied to all terms within this document. + */ +lunr.Builder.prototype.add = function (doc, attributes) { + var docRef = doc[this._ref], + fields = Object.keys(this._fields) + + this._documents[docRef] = attributes || {} + this.documentCount += 1 + + for (var i = 0; i < fields.length; i++) { + var fieldName = fields[i], + extractor = this._fields[fieldName].extractor, + field = extractor ? extractor(doc) : doc[fieldName], + tokens = this.tokenizer(field, { + fields: [fieldName] + }), + terms = this.pipeline.run(tokens), + fieldRef = new lunr.FieldRef (docRef, fieldName), + fieldTerms = Object.create(null) + + this.fieldTermFrequencies[fieldRef] = fieldTerms + this.fieldLengths[fieldRef] = 0 + + // store the length of this field for this document + this.fieldLengths[fieldRef] += terms.length + + // calculate term frequencies for this field + for (var j = 0; j < terms.length; j++) { + var term = terms[j] + + if (fieldTerms[term] == undefined) { + fieldTerms[term] = 0 + } + + fieldTerms[term] += 1 + + // add to inverted index + // create an initial posting if one doesn't exist + if (this.invertedIndex[term] == undefined) { + var posting = Object.create(null) + posting["_index"] = this.termIndex + this.termIndex += 1 + + for (var k = 0; k < fields.length; k++) { + posting[fields[k]] = Object.create(null) + } + + this.invertedIndex[term] = posting + } + + // add an entry for this term/fieldName/docRef to the invertedIndex + if (this.invertedIndex[term][fieldName][docRef] == undefined) { + this.invertedIndex[term][fieldName][docRef] = Object.create(null) + } + + // store all whitelisted metadata about this token in the + // inverted index + for (var l = 0; l < this.metadataWhitelist.length; l++) { + var metadataKey = this.metadataWhitelist[l], + metadata = term.metadata[metadataKey] + + if (this.invertedIndex[term][fieldName][docRef][metadataKey] == undefined) { + this.invertedIndex[term][fieldName][docRef][metadataKey] = [] + } + + this.invertedIndex[term][fieldName][docRef][metadataKey].push(metadata) + } + } + + } +} + +/** + * Calculates the average document length for this index + * + * @private + */ +lunr.Builder.prototype.calculateAverageFieldLengths = function () { + + var fieldRefs = Object.keys(this.fieldLengths), + numberOfFields = fieldRefs.length, + accumulator = {}, + documentsWithField = {} + + for (var i = 0; i < numberOfFields; i++) { + var fieldRef = lunr.FieldRef.fromString(fieldRefs[i]), + field = fieldRef.fieldName + + documentsWithField[field] || (documentsWithField[field] = 0) + documentsWithField[field] += 1 + + accumulator[field] || (accumulator[field] = 0) + accumulator[field] += this.fieldLengths[fieldRef] + } + + var fields = Object.keys(this._fields) + + for (var i = 0; i < fields.length; i++) { + var fieldName = fields[i] + accumulator[fieldName] = accumulator[fieldName] / documentsWithField[fieldName] + } + + this.averageFieldLength = accumulator +} + +/** + * Builds a vector space model of every document using lunr.Vector + * + * @private + */ +lunr.Builder.prototype.createFieldVectors = function () { + var fieldVectors = {}, + fieldRefs = Object.keys(this.fieldTermFrequencies), + fieldRefsLength = fieldRefs.length, + termIdfCache = Object.create(null) + + for (var i = 0; i < fieldRefsLength; i++) { + var fieldRef = lunr.FieldRef.fromString(fieldRefs[i]), + fieldName = fieldRef.fieldName, + fieldLength = this.fieldLengths[fieldRef], + fieldVector = new lunr.Vector, + termFrequencies = this.fieldTermFrequencies[fieldRef], + terms = Object.keys(termFrequencies), + termsLength = terms.length + + + var fieldBoost = this._fields[fieldName].boost || 1, + docBoost = this._documents[fieldRef.docRef].boost || 1 + + for (var j = 0; j < termsLength; j++) { + var term = terms[j], + tf = termFrequencies[term], + termIndex = this.invertedIndex[term]._index, + idf, score, scoreWithPrecision + + if (termIdfCache[term] === undefined) { + idf = lunr.idf(this.invertedIndex[term], this.documentCount) + termIdfCache[term] = idf + } else { + idf = termIdfCache[term] + } + + score = idf * ((this._k1 + 1) * tf) / (this._k1 * (1 - this._b + this._b * (fieldLength / this.averageFieldLength[fieldName])) + tf) + score *= fieldBoost + score *= docBoost + scoreWithPrecision = Math.round(score * 1000) / 1000 + // Converts 1.23456789 to 1.234. + // Reducing the precision so that the vectors take up less + // space when serialised. Doing it now so that they behave + // the same before and after serialisation. Also, this is + // the fastest approach to reducing a number's precision in + // JavaScript. + + fieldVector.insert(termIndex, scoreWithPrecision) + } + + fieldVectors[fieldRef] = fieldVector + } + + this.fieldVectors = fieldVectors +} + +/** + * Creates a token set of all tokens in the index using lunr.TokenSet + * + * @private + */ +lunr.Builder.prototype.createTokenSet = function () { + this.tokenSet = lunr.TokenSet.fromArray( + Object.keys(this.invertedIndex).sort() + ) +} + +/** + * Builds the index, creating an instance of lunr.Index. + * + * This completes the indexing process and should only be called + * once all documents have been added to the index. + * + * @returns {lunr.Index} + */ +lunr.Builder.prototype.build = function () { + this.calculateAverageFieldLengths() + this.createFieldVectors() + this.createTokenSet() + + return new lunr.Index({ + invertedIndex: this.invertedIndex, + fieldVectors: this.fieldVectors, + tokenSet: this.tokenSet, + fields: Object.keys(this._fields), + pipeline: this.searchPipeline + }) +} + +/** + * Applies a plugin to the index builder. + * + * A plugin is a function that is called with the index builder as its context. + * Plugins can be used to customise or extend the behaviour of the index + * in some way. A plugin is just a function, that encapsulated the custom + * behaviour that should be applied when building the index. + * + * The plugin function will be called with the index builder as its argument, additional + * arguments can also be passed when calling use. The function will be called + * with the index builder as its context. + * + * @param {Function} plugin The plugin to apply. + */ +lunr.Builder.prototype.use = function (fn) { + var args = Array.prototype.slice.call(arguments, 1) + args.unshift(this) + fn.apply(this, args) +} +/** + * Contains and collects metadata about a matching document. + * A single instance of lunr.MatchData is returned as part of every + * lunr.Index~Result. + * + * @constructor + * @param {string} term - The term this match data is associated with + * @param {string} field - The field in which the term was found + * @param {object} metadata - The metadata recorded about this term in this field + * @property {object} metadata - A cloned collection of metadata associated with this document. + * @see {@link lunr.Index~Result} + */ +lunr.MatchData = function (term, field, metadata) { + var clonedMetadata = Object.create(null), + metadataKeys = Object.keys(metadata || {}) + + // Cloning the metadata to prevent the original + // being mutated during match data combination. + // Metadata is kept in an array within the inverted + // index so cloning the data can be done with + // Array#slice + for (var i = 0; i < metadataKeys.length; i++) { + var key = metadataKeys[i] + clonedMetadata[key] = metadata[key].slice() + } + + this.metadata = Object.create(null) + + if (term !== undefined) { + this.metadata[term] = Object.create(null) + this.metadata[term][field] = clonedMetadata + } +} + +/** + * An instance of lunr.MatchData will be created for every term that matches a + * document. However only one instance is required in a lunr.Index~Result. This + * method combines metadata from another instance of lunr.MatchData with this + * objects metadata. + * + * @param {lunr.MatchData} otherMatchData - Another instance of match data to merge with this one. + * @see {@link lunr.Index~Result} + */ +lunr.MatchData.prototype.combine = function (otherMatchData) { + var terms = Object.keys(otherMatchData.metadata) + + for (var i = 0; i < terms.length; i++) { + var term = terms[i], + fields = Object.keys(otherMatchData.metadata[term]) + + if (this.metadata[term] == undefined) { + this.metadata[term] = Object.create(null) + } + + for (var j = 0; j < fields.length; j++) { + var field = fields[j], + keys = Object.keys(otherMatchData.metadata[term][field]) + + if (this.metadata[term][field] == undefined) { + this.metadata[term][field] = Object.create(null) + } + + for (var k = 0; k < keys.length; k++) { + var key = keys[k] + + if (this.metadata[term][field][key] == undefined) { + this.metadata[term][field][key] = otherMatchData.metadata[term][field][key] + } else { + this.metadata[term][field][key] = this.metadata[term][field][key].concat(otherMatchData.metadata[term][field][key]) + } + + } + } + } +} + +/** + * Add metadata for a term/field pair to this instance of match data. + * + * @param {string} term - The term this match data is associated with + * @param {string} field - The field in which the term was found + * @param {object} metadata - The metadata recorded about this term in this field + */ +lunr.MatchData.prototype.add = function (term, field, metadata) { + if (!(term in this.metadata)) { + this.metadata[term] = Object.create(null) + this.metadata[term][field] = metadata + return + } + + if (!(field in this.metadata[term])) { + this.metadata[term][field] = metadata + return + } + + var metadataKeys = Object.keys(metadata) + + for (var i = 0; i < metadataKeys.length; i++) { + var key = metadataKeys[i] + + if (key in this.metadata[term][field]) { + this.metadata[term][field][key] = this.metadata[term][field][key].concat(metadata[key]) + } else { + this.metadata[term][field][key] = metadata[key] + } + } +} +/** + * A lunr.Query provides a programmatic way of defining queries to be performed + * against a {@link lunr.Index}. + * + * Prefer constructing a lunr.Query using the {@link lunr.Index#query} method + * so the query object is pre-initialized with the right index fields. + * + * @constructor + * @property {lunr.Query~Clause[]} clauses - An array of query clauses. + * @property {string[]} allFields - An array of all available fields in a lunr.Index. + */ +lunr.Query = function (allFields) { + this.clauses = [] + this.allFields = allFields +} + +/** + * Constants for indicating what kind of automatic wildcard insertion will be used when constructing a query clause. + * + * This allows wildcards to be added to the beginning and end of a term without having to manually do any string + * concatenation. + * + * The wildcard constants can be bitwise combined to select both leading and trailing wildcards. + * + * @constant + * @default + * @property {number} wildcard.NONE - The term will have no wildcards inserted, this is the default behaviour + * @property {number} wildcard.LEADING - Prepend the term with a wildcard, unless a leading wildcard already exists + * @property {number} wildcard.TRAILING - Append a wildcard to the term, unless a trailing wildcard already exists + * @see lunr.Query~Clause + * @see lunr.Query#clause + * @see lunr.Query#term + * @example query term with trailing wildcard + * query.term('foo', { wildcard: lunr.Query.wildcard.TRAILING }) + * @example query term with leading and trailing wildcard + * query.term('foo', { + * wildcard: lunr.Query.wildcard.LEADING | lunr.Query.wildcard.TRAILING + * }) + */ + +lunr.Query.wildcard = new String ("*") +lunr.Query.wildcard.NONE = 0 +lunr.Query.wildcard.LEADING = 1 +lunr.Query.wildcard.TRAILING = 2 + +/** + * Constants for indicating what kind of presence a term must have in matching documents. + * + * @constant + * @enum {number} + * @see lunr.Query~Clause + * @see lunr.Query#clause + * @see lunr.Query#term + * @example query term with required presence + * query.term('foo', { presence: lunr.Query.presence.REQUIRED }) + */ +lunr.Query.presence = { + /** + * Term's presence in a document is optional, this is the default value. + */ + OPTIONAL: 1, + + /** + * Term's presence in a document is required, documents that do not contain + * this term will not be returned. + */ + REQUIRED: 2, + + /** + * Term's presence in a document is prohibited, documents that do contain + * this term will not be returned. + */ + PROHIBITED: 3 +} + +/** + * A single clause in a {@link lunr.Query} contains a term and details on how to + * match that term against a {@link lunr.Index}. + * + * @typedef {Object} lunr.Query~Clause + * @property {string[]} fields - The fields in an index this clause should be matched against. + * @property {number} [boost=1] - Any boost that should be applied when matching this clause. + * @property {number} [editDistance] - Whether the term should have fuzzy matching applied, and how fuzzy the match should be. + * @property {boolean} [usePipeline] - Whether the term should be passed through the search pipeline. + * @property {number} [wildcard=lunr.Query.wildcard.NONE] - Whether the term should have wildcards appended or prepended. + * @property {number} [presence=lunr.Query.presence.OPTIONAL] - The terms presence in any matching documents. + */ + +/** + * Adds a {@link lunr.Query~Clause} to this query. + * + * Unless the clause contains the fields to be matched all fields will be matched. In addition + * a default boost of 1 is applied to the clause. + * + * @param {lunr.Query~Clause} clause - The clause to add to this query. + * @see lunr.Query~Clause + * @returns {lunr.Query} + */ +lunr.Query.prototype.clause = function (clause) { + if (!('fields' in clause)) { + clause.fields = this.allFields + } + + if (!('boost' in clause)) { + clause.boost = 1 + } + + if (!('usePipeline' in clause)) { + clause.usePipeline = true + } + + if (!('wildcard' in clause)) { + clause.wildcard = lunr.Query.wildcard.NONE + } + + if ((clause.wildcard & lunr.Query.wildcard.LEADING) && (clause.term.charAt(0) != lunr.Query.wildcard)) { + clause.term = "*" + clause.term + } + + if ((clause.wildcard & lunr.Query.wildcard.TRAILING) && (clause.term.slice(-1) != lunr.Query.wildcard)) { + clause.term = "" + clause.term + "*" + } + + if (!('presence' in clause)) { + clause.presence = lunr.Query.presence.OPTIONAL + } + + this.clauses.push(clause) + + return this +} + +/** + * A negated query is one in which every clause has a presence of + * prohibited. These queries require some special processing to return + * the expected results. + * + * @returns boolean + */ +lunr.Query.prototype.isNegated = function () { + for (var i = 0; i < this.clauses.length; i++) { + if (this.clauses[i].presence != lunr.Query.presence.PROHIBITED) { + return false + } + } + + return true +} + +/** + * Adds a term to the current query, under the covers this will create a {@link lunr.Query~Clause} + * to the list of clauses that make up this query. + * + * The term is used as is, i.e. no tokenization will be performed by this method. Instead conversion + * to a token or token-like string should be done before calling this method. + * + * The term will be converted to a string by calling `toString`. Multiple terms can be passed as an + * array, each term in the array will share the same options. + * + * @param {object|object[]} term - The term(s) to add to the query. + * @param {object} [options] - Any additional properties to add to the query clause. + * @returns {lunr.Query} + * @see lunr.Query#clause + * @see lunr.Query~Clause + * @example adding a single term to a query + * query.term("foo") + * @example adding a single term to a query and specifying search fields, term boost and automatic trailing wildcard + * query.term("foo", { + * fields: ["title"], + * boost: 10, + * wildcard: lunr.Query.wildcard.TRAILING + * }) + * @example using lunr.tokenizer to convert a string to tokens before using them as terms + * query.term(lunr.tokenizer("foo bar")) + */ +lunr.Query.prototype.term = function (term, options) { + if (Array.isArray(term)) { + term.forEach(function (t) { this.term(t, lunr.utils.clone(options)) }, this) + return this + } + + var clause = options || {} + clause.term = term.toString() + + this.clause(clause) + + return this +} +lunr.QueryParseError = function (message, start, end) { + this.name = "QueryParseError" + this.message = message + this.start = start + this.end = end +} + +lunr.QueryParseError.prototype = new Error +lunr.QueryLexer = function (str) { + this.lexemes = [] + this.str = str + this.length = str.length + this.pos = 0 + this.start = 0 + this.escapeCharPositions = [] +} + +lunr.QueryLexer.prototype.run = function () { + var state = lunr.QueryLexer.lexText + + while (state) { + state = state(this) + } +} + +lunr.QueryLexer.prototype.sliceString = function () { + var subSlices = [], + sliceStart = this.start, + sliceEnd = this.pos + + for (var i = 0; i < this.escapeCharPositions.length; i++) { + sliceEnd = this.escapeCharPositions[i] + subSlices.push(this.str.slice(sliceStart, sliceEnd)) + sliceStart = sliceEnd + 1 + } + + subSlices.push(this.str.slice(sliceStart, this.pos)) + this.escapeCharPositions.length = 0 + + return subSlices.join('') +} + +lunr.QueryLexer.prototype.emit = function (type) { + this.lexemes.push({ + type: type, + str: this.sliceString(), + start: this.start, + end: this.pos + }) + + this.start = this.pos +} + +lunr.QueryLexer.prototype.escapeCharacter = function () { + this.escapeCharPositions.push(this.pos - 1) + this.pos += 1 +} + +lunr.QueryLexer.prototype.next = function () { + if (this.pos >= this.length) { + return lunr.QueryLexer.EOS + } + + var char = this.str.charAt(this.pos) + this.pos += 1 + return char +} + +lunr.QueryLexer.prototype.width = function () { + return this.pos - this.start +} + +lunr.QueryLexer.prototype.ignore = function () { + if (this.start == this.pos) { + this.pos += 1 + } + + this.start = this.pos +} + +lunr.QueryLexer.prototype.backup = function () { + this.pos -= 1 +} + +lunr.QueryLexer.prototype.acceptDigitRun = function () { + var char, charCode + + do { + char = this.next() + charCode = char.charCodeAt(0) + } while (charCode > 47 && charCode < 58) + + if (char != lunr.QueryLexer.EOS) { + this.backup() + } +} + +lunr.QueryLexer.prototype.more = function () { + return this.pos < this.length +} + +lunr.QueryLexer.EOS = 'EOS' +lunr.QueryLexer.FIELD = 'FIELD' +lunr.QueryLexer.TERM = 'TERM' +lunr.QueryLexer.EDIT_DISTANCE = 'EDIT_DISTANCE' +lunr.QueryLexer.BOOST = 'BOOST' +lunr.QueryLexer.PRESENCE = 'PRESENCE' + +lunr.QueryLexer.lexField = function (lexer) { + lexer.backup() + lexer.emit(lunr.QueryLexer.FIELD) + lexer.ignore() + return lunr.QueryLexer.lexText +} + +lunr.QueryLexer.lexTerm = function (lexer) { + if (lexer.width() > 1) { + lexer.backup() + lexer.emit(lunr.QueryLexer.TERM) + } + + lexer.ignore() + + if (lexer.more()) { + return lunr.QueryLexer.lexText + } +} + +lunr.QueryLexer.lexEditDistance = function (lexer) { + lexer.ignore() + lexer.acceptDigitRun() + lexer.emit(lunr.QueryLexer.EDIT_DISTANCE) + return lunr.QueryLexer.lexText +} + +lunr.QueryLexer.lexBoost = function (lexer) { + lexer.ignore() + lexer.acceptDigitRun() + lexer.emit(lunr.QueryLexer.BOOST) + return lunr.QueryLexer.lexText +} + +lunr.QueryLexer.lexEOS = function (lexer) { + if (lexer.width() > 0) { + lexer.emit(lunr.QueryLexer.TERM) + } +} + +// This matches the separator used when tokenising fields +// within a document. These should match otherwise it is +// not possible to search for some tokens within a document. +// +// It is possible for the user to change the separator on the +// tokenizer so it _might_ clash with any other of the special +// characters already used within the search string, e.g. :. +// +// This means that it is possible to change the separator in +// such a way that makes some words unsearchable using a search +// string. +lunr.QueryLexer.termSeparator = lunr.tokenizer.separator + +lunr.QueryLexer.lexText = function (lexer) { + while (true) { + var char = lexer.next() + + if (char == lunr.QueryLexer.EOS) { + return lunr.QueryLexer.lexEOS + } + + // Escape character is '\' + if (char.charCodeAt(0) == 92) { + lexer.escapeCharacter() + continue + } + + if (char == ":") { + return lunr.QueryLexer.lexField + } + + if (char == "~") { + lexer.backup() + if (lexer.width() > 0) { + lexer.emit(lunr.QueryLexer.TERM) + } + return lunr.QueryLexer.lexEditDistance + } + + if (char == "^") { + lexer.backup() + if (lexer.width() > 0) { + lexer.emit(lunr.QueryLexer.TERM) + } + return lunr.QueryLexer.lexBoost + } + + // "+" indicates term presence is required + // checking for length to ensure that only + // leading "+" are considered + if (char == "+" && lexer.width() === 1) { + lexer.emit(lunr.QueryLexer.PRESENCE) + return lunr.QueryLexer.lexText + } + + // "-" indicates term presence is prohibited + // checking for length to ensure that only + // leading "-" are considered + if (char == "-" && lexer.width() === 1) { + lexer.emit(lunr.QueryLexer.PRESENCE) + return lunr.QueryLexer.lexText + } + + if (char.match(lunr.QueryLexer.termSeparator)) { + return lunr.QueryLexer.lexTerm + } + } +} + +lunr.QueryParser = function (str, query) { + this.lexer = new lunr.QueryLexer (str) + this.query = query + this.currentClause = {} + this.lexemeIdx = 0 +} + +lunr.QueryParser.prototype.parse = function () { + this.lexer.run() + this.lexemes = this.lexer.lexemes + + var state = lunr.QueryParser.parseClause + + while (state) { + state = state(this) + } + + return this.query +} + +lunr.QueryParser.prototype.peekLexeme = function () { + return this.lexemes[this.lexemeIdx] +} + +lunr.QueryParser.prototype.consumeLexeme = function () { + var lexeme = this.peekLexeme() + this.lexemeIdx += 1 + return lexeme +} + +lunr.QueryParser.prototype.nextClause = function () { + var completedClause = this.currentClause + this.query.clause(completedClause) + this.currentClause = {} +} + +lunr.QueryParser.parseClause = function (parser) { + var lexeme = parser.peekLexeme() + + if (lexeme == undefined) { + return + } + + switch (lexeme.type) { + case lunr.QueryLexer.PRESENCE: + return lunr.QueryParser.parsePresence + case lunr.QueryLexer.FIELD: + return lunr.QueryParser.parseField + case lunr.QueryLexer.TERM: + return lunr.QueryParser.parseTerm + default: + var errorMessage = "expected either a field or a term, found " + lexeme.type + + if (lexeme.str.length >= 1) { + errorMessage += " with value '" + lexeme.str + "'" + } + + throw new lunr.QueryParseError (errorMessage, lexeme.start, lexeme.end) + } +} + +lunr.QueryParser.parsePresence = function (parser) { + var lexeme = parser.consumeLexeme() + + if (lexeme == undefined) { + return + } + + switch (lexeme.str) { + case "-": + parser.currentClause.presence = lunr.Query.presence.PROHIBITED + break + case "+": + parser.currentClause.presence = lunr.Query.presence.REQUIRED + break + default: + var errorMessage = "unrecognised presence operator'" + lexeme.str + "'" + throw new lunr.QueryParseError (errorMessage, lexeme.start, lexeme.end) + } + + var nextLexeme = parser.peekLexeme() + + if (nextLexeme == undefined) { + var errorMessage = "expecting term or field, found nothing" + throw new lunr.QueryParseError (errorMessage, lexeme.start, lexeme.end) + } + + switch (nextLexeme.type) { + case lunr.QueryLexer.FIELD: + return lunr.QueryParser.parseField + case lunr.QueryLexer.TERM: + return lunr.QueryParser.parseTerm + default: + var errorMessage = "expecting term or field, found '" + nextLexeme.type + "'" + throw new lunr.QueryParseError (errorMessage, nextLexeme.start, nextLexeme.end) + } +} + +lunr.QueryParser.parseField = function (parser) { + var lexeme = parser.consumeLexeme() + + if (lexeme == undefined) { + return + } + + if (parser.query.allFields.indexOf(lexeme.str) == -1) { + var possibleFields = parser.query.allFields.map(function (f) { return "'" + f + "'" }).join(', '), + errorMessage = "unrecognised field '" + lexeme.str + "', possible fields: " + possibleFields + + throw new lunr.QueryParseError (errorMessage, lexeme.start, lexeme.end) + } + + parser.currentClause.fields = [lexeme.str] + + var nextLexeme = parser.peekLexeme() + + if (nextLexeme == undefined) { + var errorMessage = "expecting term, found nothing" + throw new lunr.QueryParseError (errorMessage, lexeme.start, lexeme.end) + } + + switch (nextLexeme.type) { + case lunr.QueryLexer.TERM: + return lunr.QueryParser.parseTerm + default: + var errorMessage = "expecting term, found '" + nextLexeme.type + "'" + throw new lunr.QueryParseError (errorMessage, nextLexeme.start, nextLexeme.end) + } +} + +lunr.QueryParser.parseTerm = function (parser) { + var lexeme = parser.consumeLexeme() + + if (lexeme == undefined) { + return + } + + parser.currentClause.term = lexeme.str.toLowerCase() + + if (lexeme.str.indexOf("*") != -1) { + parser.currentClause.usePipeline = false + } + + var nextLexeme = parser.peekLexeme() + + if (nextLexeme == undefined) { + parser.nextClause() + return + } + + switch (nextLexeme.type) { + case lunr.QueryLexer.TERM: + parser.nextClause() + return lunr.QueryParser.parseTerm + case lunr.QueryLexer.FIELD: + parser.nextClause() + return lunr.QueryParser.parseField + case lunr.QueryLexer.EDIT_DISTANCE: + return lunr.QueryParser.parseEditDistance + case lunr.QueryLexer.BOOST: + return lunr.QueryParser.parseBoost + case lunr.QueryLexer.PRESENCE: + parser.nextClause() + return lunr.QueryParser.parsePresence + default: + var errorMessage = "Unexpected lexeme type '" + nextLexeme.type + "'" + throw new lunr.QueryParseError (errorMessage, nextLexeme.start, nextLexeme.end) + } +} + +lunr.QueryParser.parseEditDistance = function (parser) { + var lexeme = parser.consumeLexeme() + + if (lexeme == undefined) { + return + } + + var editDistance = parseInt(lexeme.str, 10) + + if (isNaN(editDistance)) { + var errorMessage = "edit distance must be numeric" + throw new lunr.QueryParseError (errorMessage, lexeme.start, lexeme.end) + } + + parser.currentClause.editDistance = editDistance + + var nextLexeme = parser.peekLexeme() + + if (nextLexeme == undefined) { + parser.nextClause() + return + } + + switch (nextLexeme.type) { + case lunr.QueryLexer.TERM: + parser.nextClause() + return lunr.QueryParser.parseTerm + case lunr.QueryLexer.FIELD: + parser.nextClause() + return lunr.QueryParser.parseField + case lunr.QueryLexer.EDIT_DISTANCE: + return lunr.QueryParser.parseEditDistance + case lunr.QueryLexer.BOOST: + return lunr.QueryParser.parseBoost + case lunr.QueryLexer.PRESENCE: + parser.nextClause() + return lunr.QueryParser.parsePresence + default: + var errorMessage = "Unexpected lexeme type '" + nextLexeme.type + "'" + throw new lunr.QueryParseError (errorMessage, nextLexeme.start, nextLexeme.end) + } +} + +lunr.QueryParser.parseBoost = function (parser) { + var lexeme = parser.consumeLexeme() + + if (lexeme == undefined) { + return + } + + var boost = parseInt(lexeme.str, 10) + + if (isNaN(boost)) { + var errorMessage = "boost must be numeric" + throw new lunr.QueryParseError (errorMessage, lexeme.start, lexeme.end) + } + + parser.currentClause.boost = boost + + var nextLexeme = parser.peekLexeme() + + if (nextLexeme == undefined) { + parser.nextClause() + return + } + + switch (nextLexeme.type) { + case lunr.QueryLexer.TERM: + parser.nextClause() + return lunr.QueryParser.parseTerm + case lunr.QueryLexer.FIELD: + parser.nextClause() + return lunr.QueryParser.parseField + case lunr.QueryLexer.EDIT_DISTANCE: + return lunr.QueryParser.parseEditDistance + case lunr.QueryLexer.BOOST: + return lunr.QueryParser.parseBoost + case lunr.QueryLexer.PRESENCE: + parser.nextClause() + return lunr.QueryParser.parsePresence + default: + var errorMessage = "Unexpected lexeme type '" + nextLexeme.type + "'" + throw new lunr.QueryParseError (errorMessage, nextLexeme.start, nextLexeme.end) + } +} + + /** + * export the module via AMD, CommonJS or as a browser global + * Export code from https://github.com/umdjs/umd/blob/master/returnExports.js + */ + ;(function (root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(factory) + } else if (typeof exports === 'object') { + /** + * Node. Does not work with strict CommonJS, but + * only CommonJS-like environments that support module.exports, + * like Node. + */ + module.exports = factory() + } else { + // Browser globals (root is window) + root.lunr = factory() + } + }(this, function () { + /** + * Just return a value to define the module export. + * This example returns an object, but the module + * can return a function as the exported value. + */ + return lunr + })) +})(); diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/templates/search/main.js b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/templates/search/main.js new file mode 100644 index 0000000000000000000000000000000000000000..a5e469d7c8d0d5e28fea196c244bc687fa3c9cd2 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/templates/search/main.js @@ -0,0 +1,109 @@ +function getSearchTermFromLocation() { + var sPageURL = window.location.search.substring(1); + var sURLVariables = sPageURL.split('&'); + for (var i = 0; i < sURLVariables.length; i++) { + var sParameterName = sURLVariables[i].split('='); + if (sParameterName[0] == 'q') { + return decodeURIComponent(sParameterName[1].replace(/\+/g, '%20')); + } + } +} + +function joinUrl (base, path) { + if (path.substring(0, 1) === "/") { + // path starts with `/`. Thus it is absolute. + return path; + } + if (base.substring(base.length-1) === "/") { + // base ends with `/` + return base + path; + } + return base + "/" + path; +} + +function escapeHtml (value) { + return value.replace(/&/g, '&') + .replace(/"/g, '"') + .replace(//g, '>'); +} + +function formatResult (location, title, summary) { + return ''; +} + +function displayResults (results) { + var search_results = document.getElementById("mkdocs-search-results"); + while (search_results.firstChild) { + search_results.removeChild(search_results.firstChild); + } + if (results.length > 0){ + for (var i=0; i < results.length; i++){ + var result = results[i]; + var html = formatResult(result.location, result.title, result.summary); + search_results.insertAdjacentHTML('beforeend', html); + } + } else { + var noResultsText = search_results.getAttribute('data-no-results-text'); + if (!noResultsText) { + noResultsText = "No results found"; + } + search_results.insertAdjacentHTML('beforeend', '

' + noResultsText + '

'); + } +} + +function doSearch () { + var query = document.getElementById('mkdocs-search-query').value; + if (query.length > min_search_length) { + if (!window.Worker) { + displayResults(search(query)); + } else { + searchWorker.postMessage({query: query}); + } + } else { + // Clear results for short queries + displayResults([]); + } +} + +function initSearch () { + var search_input = document.getElementById('mkdocs-search-query'); + if (search_input) { + search_input.addEventListener("keyup", doSearch); + } + var term = getSearchTermFromLocation(); + if (term) { + search_input.value = term; + doSearch(); + } +} + +function onWorkerMessage (e) { + if (e.data.allowSearch) { + initSearch(); + } else if (e.data.results) { + var results = e.data.results; + displayResults(results); + } else if (e.data.config) { + min_search_length = e.data.config.min_search_length-1; + } +} + +if (!window.Worker) { + console.log('Web Worker API not supported'); + // load index in main thread + $.getScript(joinUrl(base_url, "search/worker.js")).done(function () { + console.log('Loaded worker'); + init(); + window.postMessage = function (msg) { + onWorkerMessage({data: msg}); + }; + }).fail(function (jqxhr, settings, exception) { + console.error('Could not load worker.js'); + }); +} else { + // Wrap search in a web worker + var searchWorker = new Worker(joinUrl(base_url, "search/worker.js")); + searchWorker.postMessage({init: true}); + searchWorker.onmessage = onWorkerMessage; +} diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/templates/search/worker.js b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/templates/search/worker.js new file mode 100644 index 0000000000000000000000000000000000000000..8628dbce9442638095bf6ae885651b7dec0c91ea --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/contrib/search/templates/search/worker.js @@ -0,0 +1,133 @@ +var base_path = 'function' === typeof importScripts ? '.' : '/search/'; +var allowSearch = false; +var index; +var documents = {}; +var lang = ['en']; +var data; + +function getScript(script, callback) { + console.log('Loading script: ' + script); + $.getScript(base_path + script).done(function () { + callback(); + }).fail(function (jqxhr, settings, exception) { + console.log('Error: ' + exception); + }); +} + +function getScriptsInOrder(scripts, callback) { + if (scripts.length === 0) { + callback(); + return; + } + getScript(scripts[0], function() { + getScriptsInOrder(scripts.slice(1), callback); + }); +} + +function loadScripts(urls, callback) { + if( 'function' === typeof importScripts ) { + importScripts.apply(null, urls); + callback(); + } else { + getScriptsInOrder(urls, callback); + } +} + +function onJSONLoaded () { + data = JSON.parse(this.responseText); + var scriptsToLoad = ['lunr.js']; + if (data.config && data.config.lang && data.config.lang.length) { + lang = data.config.lang; + } + if (lang.length > 1 || lang[0] !== "en") { + scriptsToLoad.push('lunr.stemmer.support.js'); + if (lang.length > 1) { + scriptsToLoad.push('lunr.multi.js'); + } + if (lang.includes("ja") || lang.includes("jp")) { + scriptsToLoad.push('tinyseg.js'); + } + for (var i=0; i < lang.length; i++) { + if (lang[i] != 'en') { + scriptsToLoad.push(['lunr', lang[i], 'js'].join('.')); + } + } + } + loadScripts(scriptsToLoad, onScriptsLoaded); +} + +function onScriptsLoaded () { + console.log('All search scripts loaded, building Lunr index...'); + if (data.config && data.config.separator && data.config.separator.length) { + lunr.tokenizer.separator = new RegExp(data.config.separator); + } + + if (data.index) { + index = lunr.Index.load(data.index); + data.docs.forEach(function (doc) { + documents[doc.location] = doc; + }); + console.log('Lunr pre-built index loaded, search ready'); + } else { + index = lunr(function () { + if (lang.length === 1 && lang[0] !== "en" && lunr[lang[0]]) { + this.use(lunr[lang[0]]); + } else if (lang.length > 1) { + this.use(lunr.multiLanguage.apply(null, lang)); // spread operator not supported in all browsers: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator#Browser_compatibility + } + this.field('title'); + this.field('text'); + this.ref('location'); + + for (var i=0; i < data.docs.length; i++) { + var doc = data.docs[i]; + this.add(doc); + documents[doc.location] = doc; + } + }); + console.log('Lunr index built, search ready'); + } + allowSearch = true; + postMessage({config: data.config}); + postMessage({allowSearch: allowSearch}); +} + +function init () { + var oReq = new XMLHttpRequest(); + oReq.addEventListener("load", onJSONLoaded); + var index_path = base_path + '/search_index.json'; + if( 'function' === typeof importScripts ){ + index_path = 'search_index.json'; + } + oReq.open("GET", index_path); + oReq.send(); +} + +function search (query) { + if (!allowSearch) { + console.error('Assets for search still loading'); + return; + } + + var resultDocuments = []; + var results = index.search(query); + for (var i=0; i < results.length; i++){ + var result = results[i]; + doc = documents[result.ref]; + doc.summary = doc.text.substring(0, 200); + resultDocuments.push(doc); + } + return resultDocuments; +} + +if( 'function' === typeof importScripts ) { + onmessage = function (e) { + if (e.data.init) { + init(); + } else if (e.data.query) { + postMessage({ results: search(e.data.query) }); + } else { + console.error("Worker - Unrecognized message: " + e); + } + }; +} diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/livereload/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/livereload/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1057c9caaa3a488cf4f46a8eb7f8d25c19266d26 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/livereload/__init__.py @@ -0,0 +1,364 @@ +from __future__ import annotations + +import functools +import io +import ipaddress +import logging +import mimetypes +import os +import os.path +import pathlib +import posixpath +import re +import socket +import socketserver +import string +import sys +import threading +import time +import traceback +import urllib.parse +import warnings +import wsgiref.simple_server +import wsgiref.util +from typing import Any, BinaryIO, Callable, Iterable + +import watchdog.events +import watchdog.observers.polling + +_SCRIPT_TEMPLATE_STR = """ +var livereload = function(epoch, requestId) { + var req = new XMLHttpRequest(); + req.onloadend = function() { + window.removeEventListener("beforeunload", abort); + if (parseFloat(this.responseText) > epoch) { + location.reload(); + return; + } + var launchNext = livereload.bind(this, epoch, requestId); + if (this.status === 200) { + launchNext(); + } else { + setTimeout(launchNext, 3000); + } + }; + var abort = req.abort.bind(req); + window.addEventListener("beforeunload", abort); + req.open("GET", "/livereload/" + epoch + "/" + requestId); + req.send(); + + console.log('Enabled live reload'); +} +livereload(${epoch}, ${request_id}); +""" +_SCRIPT_TEMPLATE = string.Template(_SCRIPT_TEMPLATE_STR) + + +class _LoggerAdapter(logging.LoggerAdapter): + def process(self, msg: str, kwargs: dict) -> tuple[str, dict]: # type: ignore[override] + return time.strftime("[%H:%M:%S] ") + msg, kwargs + + +log = _LoggerAdapter(logging.getLogger(__name__), {}) + + +class LiveReloadServer(socketserver.ThreadingMixIn, wsgiref.simple_server.WSGIServer): + daemon_threads = True + poll_response_timeout = 60 + + def __init__( + self, + builder: Callable[[], None], + host: str, + port: int, + root: str, + mount_path: str = "/", + polling_interval: float = 0.5, + shutdown_delay: float = 0.25, + ) -> None: + self.builder = builder + self.server_name = host + self.server_port = port + try: + if isinstance(ipaddress.ip_address(host), ipaddress.IPv6Address): + self.address_family = socket.AF_INET6 + except Exception: + pass + self.root = os.path.abspath(root) + self.mount_path = ("/" + mount_path.lstrip("/")).rstrip("/") + "/" + self.url = f"http://{self.server_name}:{self.server_port}{self.mount_path}" + self.build_delay = 0.1 + self.shutdown_delay = shutdown_delay + # To allow custom error pages. + self.error_handler: Callable[[int], bytes | None] = lambda code: None + + super().__init__((host, port), _Handler, bind_and_activate=False) + self.set_app(self.serve_request) + + self._wanted_epoch = _timestamp() # The version of the site that started building. + self._visible_epoch = self._wanted_epoch # Latest fully built version of the site. + self._epoch_cond = threading.Condition() # Must be held when accessing _visible_epoch. + + self._to_rebuild: dict[ + Callable[[], None], bool + ] = {} # Used as an ordered set of functions to call. + self._rebuild_cond = threading.Condition() # Must be held when accessing _to_rebuild. + + self._shutdown = False + self.serve_thread = threading.Thread(target=lambda: self.serve_forever(shutdown_delay)) + self.observer = watchdog.observers.polling.PollingObserver(timeout=polling_interval) + + self._watched_paths: dict[str, int] = {} + self._watch_refs: dict[str, Any] = {} + + def watch( + self, path: str, func: Callable[[], None] | None = None, recursive: bool = True + ) -> None: + """Add the 'path' to watched paths, call the function and reload when any file changes under it.""" + path = os.path.abspath(path) + if func is None or func is self.builder: + funct = self.builder + else: + funct = func + warnings.warn( + "Plugins should not pass the 'func' parameter of watch(). " + "The ability to execute custom callbacks will be removed soon.", + DeprecationWarning, + stacklevel=2, + ) + + if path in self._watched_paths: + self._watched_paths[path] += 1 + return + self._watched_paths[path] = 1 + + def callback(event): + if event.is_directory: + return + log.debug(str(event)) + with self._rebuild_cond: + self._to_rebuild[funct] = True + self._rebuild_cond.notify_all() + + handler = watchdog.events.FileSystemEventHandler() + handler.on_any_event = callback # type: ignore[method-assign] + log.debug(f"Watching '{path}'") + self._watch_refs[path] = self.observer.schedule(handler, path, recursive=recursive) + + def unwatch(self, path: str) -> None: + """Stop watching file changes for path. Raises if there was no corresponding `watch` call.""" + path = os.path.abspath(path) + + self._watched_paths[path] -= 1 + if self._watched_paths[path] <= 0: + self._watched_paths.pop(path) + self.observer.unschedule(self._watch_refs.pop(path)) + + def serve(self): + self.server_bind() + self.server_activate() + + if self._watched_paths: + self.observer.start() + + paths_str = ", ".join(f"'{_try_relativize_path(path)}'" for path in self._watched_paths) + log.info(f"Watching paths for changes: {paths_str}") + + log.info(f"Serving on {self.url}") + self.serve_thread.start() + + self._build_loop() + + def _build_loop(self): + while True: + with self._rebuild_cond: + while not self._rebuild_cond.wait_for( + lambda: self._to_rebuild or self._shutdown, timeout=self.shutdown_delay + ): + # We could have used just one wait instead of a loop + timeout, but we need + # occasional breaks, otherwise on Windows we can't receive KeyboardInterrupt. + pass + if self._shutdown: + break + log.info("Detected file changes") + while self._rebuild_cond.wait(timeout=self.build_delay): + log.debug("Waiting for file changes to stop happening") + + self._wanted_epoch = _timestamp() + funcs = list(self._to_rebuild) + self._to_rebuild.clear() + + try: + for func in funcs: + func() + except Exception as e: + if isinstance(e, SystemExit): + print(e, file=sys.stderr) # noqa: T201 + else: + traceback.print_exc() + log.error( + "An error happened during the rebuild. The server will appear stuck until build errors are resolved." + ) + continue + + with self._epoch_cond: + log.info("Reloading browsers") + self._visible_epoch = self._wanted_epoch + self._epoch_cond.notify_all() + + def shutdown(self, wait=False) -> None: + self.observer.stop() + with self._rebuild_cond: + self._shutdown = True + self._rebuild_cond.notify_all() + + if self.serve_thread.is_alive(): + super().shutdown() + self.server_close() + if wait: + self.serve_thread.join() + self.observer.join() + + def serve_request(self, environ, start_response) -> Iterable[bytes]: + try: + result = self._serve_request(environ, start_response) + except Exception: + code = 500 + msg = "500 Internal Server Error" + log.exception(msg) + else: + if result is not None: + return result + code = 404 + msg = "404 Not Found" + + error_content = None + try: + error_content = self.error_handler(code) + except Exception: + log.exception("Failed to render an error message!") + if error_content is None: + error_content = msg.encode() + + start_response(msg, [("Content-Type", "text/html")]) + return [error_content] + + def _serve_request(self, environ, start_response) -> Iterable[bytes] | None: + # https://bugs.python.org/issue16679 + # https://github.com/bottlepy/bottle/blob/f9b1849db4/bottle.py#L984 + path = environ["PATH_INFO"].encode("latin-1").decode("utf-8", "ignore") + + if path.startswith("/livereload/"): + m = re.fullmatch(r"/livereload/([0-9]+)/[0-9]+", path) + if m: + epoch = int(m[1]) + start_response("200 OK", [("Content-Type", "text/plain")]) + + def condition(): + return self._visible_epoch > epoch + + with self._epoch_cond: + if not condition(): + # Stall the browser, respond as soon as there's something new. + # If there's not, respond anyway after a minute. + self._log_poll_request(environ.get("HTTP_REFERER"), request_id=path) + self._epoch_cond.wait_for(condition, timeout=self.poll_response_timeout) + return [b"%d" % self._visible_epoch] + + if (path + "/").startswith(self.mount_path): + rel_file_path = path[len(self.mount_path) :] + + if path.endswith("/"): + rel_file_path += "index.html" + # Prevent directory traversal - normalize the path. + rel_file_path = posixpath.normpath("/" + rel_file_path).lstrip("/") + file_path = os.path.join(self.root, rel_file_path) + elif path == "/": + start_response("302 Found", [("Location", urllib.parse.quote(self.mount_path))]) + return [] + else: + return None # Not found + + # Wait until the ongoing rebuild (if any) finishes, so we're not serving a half-built site. + with self._epoch_cond: + self._epoch_cond.wait_for(lambda: self._visible_epoch == self._wanted_epoch) + epoch = self._visible_epoch + + try: + file: BinaryIO = open(file_path, "rb") + except OSError: + if not path.endswith("/") and os.path.isfile(os.path.join(file_path, "index.html")): + start_response("302 Found", [("Location", urllib.parse.quote(path) + "/")]) + return [] + return None # Not found + + if self._watched_paths and file_path.endswith(".html"): + with file: + content = file.read() + content = self._inject_js_into_html(content, epoch) + file = io.BytesIO(content) + content_length = len(content) + else: + content_length = os.path.getsize(file_path) + + content_type = self._guess_type(file_path) + start_response( + "200 OK", [("Content-Type", content_type), ("Content-Length", str(content_length))] + ) + return wsgiref.util.FileWrapper(file) + + def _inject_js_into_html(self, content, epoch): + try: + body_end = content.rindex(b"") + except ValueError: + body_end = len(content) + # The page will reload if the livereload poller returns a newer epoch than what it knows. + # The other timestamp becomes just a unique identifier for the initiating page. + script = _SCRIPT_TEMPLATE.substitute(epoch=epoch, request_id=_timestamp()) + return b"%b%b" % ( + content[:body_end], + script.encode(), + content[body_end:], + ) + + @classmethod + @functools.lru_cache() # "Cache" to not repeat the same message for the same browser tab. + def _log_poll_request(cls, url, request_id): + log.info(f"Browser connected: {url}") + + @classmethod + def _guess_type(cls, path): + # MkDocs only ensures a few common types (as seen in livereload_tests.py::test_mime_types). + # Other uncommon types will not be accepted. + if path.endswith((".js", ".JS", ".mjs")): + return "application/javascript" + if path.endswith(".gz"): + return "application/gzip" + + guess, _ = mimetypes.guess_type(path) + if guess: + return guess + return "application/octet-stream" + + +class _Handler(wsgiref.simple_server.WSGIRequestHandler): + def log_request(self, code="-", size="-"): + level = logging.DEBUG if str(code) == "200" else logging.WARNING + log.log(level, f'"{self.requestline}" code {code}') + + def log_message(self, format, *args): + log.debug(format, *args) + + +def _timestamp() -> int: + return round(time.monotonic() * 1000) + + +def _try_relativize_path(path: str) -> str: + """Make the path relative to current directory if it's under that directory.""" + p = pathlib.Path(path) + try: + p = p.relative_to(os.getcwd()) + except ValueError: + pass + return str(p) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/livereload/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/livereload/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e155b67f28be6dbc1720406627a1b515a3728e23 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/livereload/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/structure/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/structure/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c99b6575ec7fc8722d14f33b10ac94462c5de79c --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/structure/__init__.py @@ -0,0 +1,36 @@ +from __future__ import annotations + +import abc +from typing import TYPE_CHECKING, Iterable + +if TYPE_CHECKING: + from mkdocs.structure.nav import Section + + +class StructureItem(metaclass=abc.ABCMeta): + """An item in MkDocs structure - see concrete subclasses Section, Page or Link.""" + + @abc.abstractmethod + def __init__(self): + ... + + parent: Section | None = None + """The immediate parent of the item in the site navigation. `None` if it's at the top level.""" + + @property + def is_top_level(self) -> bool: + return self.parent is None + + title: str | None + is_section: bool = False + is_page: bool = False + is_link: bool = False + + @property + def ancestors(self) -> Iterable[StructureItem]: + if self.parent is None: + return [] + return [self.parent, *self.parent.ancestors] + + def _indent_print(self, depth: int = 0) -> str: + return (' ' * depth) + repr(self) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/structure/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/structure/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..943282bfdcc29e66db6190ded934b9b1f943899a Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/structure/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/structure/__pycache__/files.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/structure/__pycache__/files.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e9137044b56bc022648c4620fd55e02047803772 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/structure/__pycache__/files.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/structure/__pycache__/nav.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/structure/__pycache__/nav.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d23ce54a0849dea2979d747b6cdb962287bcbbb2 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/structure/__pycache__/nav.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/structure/__pycache__/pages.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/structure/__pycache__/pages.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..154649fbd2564d2d7fc174d312db76d8808d7432 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/structure/__pycache__/pages.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/structure/__pycache__/toc.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/structure/__pycache__/toc.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ab0ae917871be91da85acacb9602519e69079519 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/structure/__pycache__/toc.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/structure/files.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/structure/files.py new file mode 100644 index 0000000000000000000000000000000000000000..a918cb12edc79ae72275f942c986e1dabf221c9c --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/structure/files.py @@ -0,0 +1,406 @@ +from __future__ import annotations + +import enum +import fnmatch +import logging +import os +import posixpath +import shutil +import warnings +from pathlib import PurePath +from typing import TYPE_CHECKING, Callable, Iterable, Iterator, Sequence +from urllib.parse import quote as urlquote + +import pathspec +import pathspec.gitignore +import pathspec.util + +from mkdocs import utils + +if TYPE_CHECKING: + import jinja2.environment + + from mkdocs.config.defaults import MkDocsConfig + from mkdocs.structure.pages import Page + + +log = logging.getLogger(__name__) + + +class InclusionLevel(enum.Enum): + EXCLUDED = -2 + """The file is excluded from the final site, but will still be populated during `mkdocs serve`.""" + NOT_IN_NAV = -1 + """The file is part of the site, but doesn't produce nav warnings.""" + UNDEFINED = 0 + """Still needs to be computed based on the config. If the config doesn't kick in, acts the same as `included`.""" + INCLUDED = 1 + """The file is part of the site. Documentation pages that are omitted from the nav will produce warnings.""" + + def all(self): + return True + + def is_included(self): + return self.value > self.EXCLUDED.value + + def is_excluded(self): + return self.value <= self.EXCLUDED.value + + def is_in_nav(self): + return self.value > self.NOT_IN_NAV.value + + def is_not_in_nav(self): + return self.value <= self.NOT_IN_NAV.value + + +class Files: + """A collection of [File][mkdocs.structure.files.File] objects.""" + + def __init__(self, files: list[File]) -> None: + self._files = files + self._src_uris: dict[str, File] | None = None + + def __iter__(self) -> Iterator[File]: + """Iterate over the files within.""" + return iter(self._files) + + def __len__(self) -> int: + """The number of files within.""" + return len(self._files) + + def __contains__(self, path: str) -> bool: + """Whether the file with this `src_uri` is in the collection.""" + return PurePath(path).as_posix() in self.src_uris + + @property + def src_paths(self) -> dict[str, File]: + """Soft-deprecated, prefer `src_uris`.""" + return {file.src_path: file for file in self._files} + + @property + def src_uris(self) -> dict[str, File]: + """A mapping containing every file, with the keys being their + [`src_uri`][mkdocs.structure.files.File.src_uri].""" + if self._src_uris is None: + self._src_uris = {file.src_uri: file for file in self._files} + return self._src_uris + + def get_file_from_path(self, path: str) -> File | None: + """Return a File instance with File.src_uri equal to path.""" + return self.src_uris.get(PurePath(path).as_posix()) + + def append(self, file: File) -> None: + """Append file to Files collection.""" + self._src_uris = None + self._files.append(file) + + def remove(self, file: File) -> None: + """Remove file from Files collection.""" + self._src_uris = None + self._files.remove(file) + + def copy_static_files( + self, + dirty: bool = False, + *, + inclusion: Callable[[InclusionLevel], bool] = InclusionLevel.is_included, + ) -> None: + """Copy static files from source to destination.""" + for file in self: + if not file.is_documentation_page() and inclusion(file.inclusion): + file.copy_file(dirty) + + def documentation_pages( + self, *, inclusion: Callable[[InclusionLevel], bool] = InclusionLevel.is_included + ) -> Sequence[File]: + """Return iterable of all Markdown page file objects.""" + return [file for file in self if file.is_documentation_page() and inclusion(file.inclusion)] + + def static_pages(self) -> Sequence[File]: + """Return iterable of all static page file objects.""" + return [file for file in self if file.is_static_page()] + + def media_files(self) -> Sequence[File]: + """Return iterable of all file objects which are not documentation or static pages.""" + return [file for file in self if file.is_media_file()] + + def javascript_files(self) -> Sequence[File]: + """Return iterable of all javascript file objects.""" + return [file for file in self if file.is_javascript()] + + def css_files(self) -> Sequence[File]: + """Return iterable of all CSS file objects.""" + return [file for file in self if file.is_css()] + + def add_files_from_theme(self, env: jinja2.Environment, config: MkDocsConfig) -> None: + """Retrieve static files from Jinja environment and add to collection.""" + + def filter(name): + # '.*' filters dot files/dirs at root level whereas '*/.*' filters nested levels + patterns = ['.*', '*/.*', '*.py', '*.pyc', '*.html', '*readme*', 'mkdocs_theme.yml'] + # Exclude translation files + patterns.append("locales/*") + patterns.extend(f'*{x}' for x in utils.markdown_extensions) + patterns.extend(config.theme.static_templates) + for pattern in patterns: + if fnmatch.fnmatch(name.lower(), pattern): + return False + return True + + for path in env.list_templates(filter_func=filter): + # Theme files do not override docs_dir files + path = PurePath(path).as_posix() + if path not in self.src_uris: + for dir in config.theme.dirs: + # Find the first theme dir which contains path + if os.path.isfile(os.path.join(dir, path)): + self.append(File(path, dir, config.site_dir, config.use_directory_urls)) + break + + +class File: + """ + A MkDocs File object. + + Points to the source and destination locations of a file. + + The `path` argument must be a path that exists relative to `src_dir`. + + The `src_dir` and `dest_dir` must be absolute paths on the local file system. + + The `use_directory_urls` argument controls how destination paths are generated. If `False`, a Markdown file is + mapped to an HTML file of the same name (the file extension is changed to `.html`). If True, a Markdown file is + mapped to an HTML index file (`index.html`) nested in a directory using the "name" of the file in `path`. The + `use_directory_urls` argument has no effect on non-Markdown files. + + File objects have the following properties, which are Unicode strings: + """ + + src_uri: str + """The pure path (always '/'-separated) of the source file relative to the source directory.""" + + abs_src_path: str + """The absolute concrete path of the source file. Will use backslashes on Windows.""" + + dest_uri: str + """The pure path (always '/'-separated) of the destination file relative to the destination directory.""" + + abs_dest_path: str + """The absolute concrete path of the destination file. Will use backslashes on Windows.""" + + url: str + """The URI of the destination file relative to the destination directory as a string.""" + + inclusion: InclusionLevel = InclusionLevel.UNDEFINED + """Whether the file will be excluded from the built site.""" + + @property + def src_path(self) -> str: + """Same as `src_uri` (and synchronized with it) but will use backslashes on Windows. Discouraged.""" + return os.path.normpath(self.src_uri) + + @src_path.setter + def src_path(self, value): + self.src_uri = PurePath(value).as_posix() + + @property + def dest_path(self) -> str: + """Same as `dest_uri` (and synchronized with it) but will use backslashes on Windows. Discouraged.""" + return os.path.normpath(self.dest_uri) + + @dest_path.setter + def dest_path(self, value): + self.dest_uri = PurePath(value).as_posix() + + page: Page | None + + def __init__( + self, + path: str, + src_dir: str, + dest_dir: str, + use_directory_urls: bool, + *, + dest_uri: str | None = None, + inclusion: InclusionLevel = InclusionLevel.UNDEFINED, + ) -> None: + self.page = None + self.src_path = path + self.name = self._get_stem() + if dest_uri is None: + dest_uri = self._get_dest_path(use_directory_urls) + self.dest_uri = dest_uri + self.url = self._get_url(use_directory_urls) + self.abs_src_path = os.path.normpath(os.path.join(src_dir, self.src_uri)) + self.abs_dest_path = os.path.normpath(os.path.join(dest_dir, self.dest_uri)) + self.inclusion = inclusion + + def __eq__(self, other) -> bool: + return ( + isinstance(other, self.__class__) + and self.src_uri == other.src_uri + and self.abs_src_path == other.abs_src_path + and self.url == other.url + ) + + def __repr__(self): + return ( + f"File(src_uri='{self.src_uri}', dest_uri='{self.dest_uri}'," + f" name='{self.name}', url='{self.url}')" + ) + + def _get_stem(self) -> str: + """Return the name of the file without its extension.""" + filename = posixpath.basename(self.src_uri) + stem, ext = posixpath.splitext(filename) + return 'index' if stem == 'README' else stem + + def _get_dest_path(self, use_directory_urls: bool) -> str: + """Return destination path based on source path.""" + if self.is_documentation_page(): + parent, filename = posixpath.split(self.src_uri) + if not use_directory_urls or self.name == 'index': + # index.md or README.md => index.html + # foo.md => foo.html + return posixpath.join(parent, self.name + '.html') + else: + # foo.md => foo/index.html + return posixpath.join(parent, self.name, 'index.html') + return self.src_uri + + def _get_url(self, use_directory_urls: bool) -> str: + """Return url based in destination path.""" + url = self.dest_uri + dirname, filename = posixpath.split(url) + if use_directory_urls and filename == 'index.html': + url = (dirname or '.') + '/' + return urlquote(url) + + def url_relative_to(self, other: File | str) -> str: + """Return url for file relative to other file.""" + return utils.get_relative_url(self.url, other.url if isinstance(other, File) else other) + + def copy_file(self, dirty: bool = False) -> None: + """Copy source file to destination, ensuring parent directories exist.""" + if dirty and not self.is_modified(): + log.debug(f"Skip copying unmodified file: '{self.src_uri}'") + else: + log.debug(f"Copying media file: '{self.src_uri}'") + try: + utils.copy_file(self.abs_src_path, self.abs_dest_path) + except shutil.SameFileError: + pass # Let plugins write directly into site_dir. + + def is_modified(self) -> bool: + if os.path.isfile(self.abs_dest_path): + return os.path.getmtime(self.abs_dest_path) < os.path.getmtime(self.abs_src_path) + return True + + def is_documentation_page(self) -> bool: + """Return True if file is a Markdown page.""" + return utils.is_markdown_file(self.src_uri) + + def is_static_page(self) -> bool: + """Return True if file is a static page (HTML, XML, JSON).""" + return self.src_uri.endswith(('.html', '.htm', '.xml', '.json')) + + def is_media_file(self) -> bool: + """Return True if file is not a documentation or static page.""" + return not (self.is_documentation_page() or self.is_static_page()) + + def is_javascript(self) -> bool: + """Return True if file is a JavaScript file.""" + return self.src_uri.endswith(('.js', '.javascript', '.mjs')) + + def is_css(self) -> bool: + """Return True if file is a CSS file.""" + return self.src_uri.endswith('.css') + + +_default_exclude = pathspec.gitignore.GitIgnoreSpec.from_lines(['.*', '/templates/']) + + +def _set_exclusions(files: Iterable[File], config: MkDocsConfig) -> None: + """Re-calculate which files are excluded, based on the patterns in the config.""" + exclude: pathspec.gitignore.GitIgnoreSpec | None = config.get('exclude_docs') + exclude = _default_exclude + exclude if exclude else _default_exclude + nav_exclude: pathspec.gitignore.GitIgnoreSpec | None = config.get('not_in_nav') + + for file in files: + if file.inclusion == InclusionLevel.UNDEFINED: + if exclude.match_file(file.src_uri): + file.inclusion = InclusionLevel.EXCLUDED + elif nav_exclude and nav_exclude.match_file(file.src_uri): + file.inclusion = InclusionLevel.NOT_IN_NAV + else: + file.inclusion = InclusionLevel.INCLUDED + + +def get_files(config: MkDocsConfig) -> Files: + """Walk the `docs_dir` and return a Files collection.""" + files: list[File] = [] + conflicting_files: list[tuple[File, File]] = [] + for source_dir, dirnames, filenames in os.walk(config['docs_dir'], followlinks=True): + relative_dir = os.path.relpath(source_dir, config['docs_dir']) + dirnames.sort() + filenames.sort(key=_file_sort_key) + + files_by_dest: dict[str, File] = {} + for filename in filenames: + file = File( + os.path.join(relative_dir, filename), + config['docs_dir'], + config['site_dir'], + config['use_directory_urls'], + ) + # Skip README.md if an index file also exists in dir (part 1) + prev_file = files_by_dest.setdefault(file.dest_uri, file) + if prev_file is not file: + conflicting_files.append((prev_file, file)) + files.append(file) + prev_file = file + + _set_exclusions(files, config) + # Skip README.md if an index file also exists in dir (part 2) + for a, b in conflicting_files: + if b.inclusion.is_included(): + if a.inclusion.is_included(): + log.warning( + f"Excluding '{a.src_uri}' from the site because it conflicts with '{b.src_uri}'." + ) + try: + files.remove(a) + except ValueError: + pass # Catching this to avoid errors if attempting to remove the same file twice. + else: + try: + files.remove(b) + except ValueError: + pass + + return Files(files) + + +def _file_sort_key(f: str): + """Always sort `index` or `README` as first filename in list.""" + return (os.path.splitext(f)[0] not in ('index', 'README'), f) + + +def _sort_files(filenames: Iterable[str]) -> list[str]: + return sorted(filenames, key=_file_sort_key) + + +def _filter_paths(basename: str, path: str, is_dir: bool, exclude: Iterable[str]) -> bool: + warnings.warn( + "_filter_paths is not used since MkDocs 1.5 and will be removed soon.", DeprecationWarning + ) + for item in exclude: + # Items ending in '/' apply only to directories. + if item.endswith('/') and not is_dir: + continue + # Items starting with '/' apply to the whole path. + # In any other cases just the basename is used. + match = path if item.startswith('/') else basename + if fnmatch.fnmatch(match, item.strip('/')): + return True + return False diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/structure/nav.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/structure/nav.py new file mode 100644 index 0000000000000000000000000000000000000000..018794eb1aa675baf3c726a0bc1e05a307cf6489 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/structure/nav.py @@ -0,0 +1,249 @@ +from __future__ import annotations + +import logging +import warnings +from typing import TYPE_CHECKING, Iterator, TypeVar +from urllib.parse import urlsplit + +from mkdocs.structure import StructureItem +from mkdocs.structure.pages import Page +from mkdocs.utils import nest_paths + +if TYPE_CHECKING: + from mkdocs.config.defaults import MkDocsConfig + from mkdocs.structure.files import Files + + +log = logging.getLogger(__name__) + + +class Navigation: + def __init__(self, items: list, pages: list[Page]) -> None: + self.items = items # Nested List with full navigation of Sections, Pages, and Links. + self.pages = pages # Flat List of subset of Pages in nav, in order. + + self.homepage = None + for page in pages: + if page.is_homepage: + self.homepage = page + break + + homepage: Page | None + """The [page][mkdocs.structure.pages.Page] object for the homepage of the site.""" + + pages: list[Page] + """A flat list of all [page][mkdocs.structure.pages.Page] objects contained in the navigation.""" + + def __str__(self) -> str: + return '\n'.join(item._indent_print() for item in self) + + def __iter__(self) -> Iterator: + return iter(self.items) + + def __len__(self) -> int: + return len(self.items) + + +class Section(StructureItem): + def __init__(self, title: str, children: list[StructureItem]) -> None: + self.title = title + self.children = children + + self.active = False + + def __repr__(self): + name = self.__class__.__name__ + return f"{name}(title={self.title!r})" + + title: str + """The title of the section.""" + + children: list[StructureItem] + """An iterable of all child navigation objects. Children may include nested sections, pages and links.""" + + @property + def active(self) -> bool: + """ + When `True`, indicates that a child page of this section is the current page and + can be used to highlight the section as the currently viewed section. Defaults + to `False`. + """ + return self.__active + + @active.setter + def active(self, value: bool): + """Set active status of section and ancestors.""" + self.__active = bool(value) + if self.parent is not None: + self.parent.active = bool(value) + + is_section: bool = True + """Indicates that the navigation object is a "section" object. Always `True` for section objects.""" + + is_page: bool = False + """Indicates that the navigation object is a "page" object. Always `False` for section objects.""" + + is_link: bool = False + """Indicates that the navigation object is a "link" object. Always `False` for section objects.""" + + def _indent_print(self, depth: int = 0) -> str: + ret = [super()._indent_print(depth)] + for item in self.children: + ret.append(item._indent_print(depth + 1)) + return '\n'.join(ret) + + +class Link(StructureItem): + def __init__(self, title: str, url: str): + self.title = title + self.url = url + + def __repr__(self): + name = self.__class__.__name__ + title = f"{self.title!r}" if self.title is not None else '[blank]' + return f"{name}(title={title}, url={self.url!r})" + + title: str + """The title of the link. This would generally be used as the label of the link.""" + + url: str + """The URL that the link points to. The URL should always be an absolute URLs and + should not need to have `base_url` prepended.""" + + children: None = None + """Links do not contain children and the attribute is always `None`.""" + + active: bool = False + """External links cannot be "active" and the attribute is always `False`.""" + + is_section: bool = False + """Indicates that the navigation object is a "section" object. Always `False` for link objects.""" + + is_page: bool = False + """Indicates that the navigation object is a "page" object. Always `False` for link objects.""" + + is_link: bool = True + """Indicates that the navigation object is a "link" object. Always `True` for link objects.""" + + +def get_navigation(files: Files, config: MkDocsConfig) -> Navigation: + """Build site navigation from config and files.""" + documentation_pages = files.documentation_pages() + nav_config = config['nav'] or nest_paths(f.src_uri for f in documentation_pages) + items = _data_to_navigation(nav_config, files, config) + if not isinstance(items, list): + items = [items] + + # Get only the pages from the navigation, ignoring any sections and links. + pages = _get_by_type(items, Page) + + # Include next, previous and parent links. + _add_previous_and_next_links(pages) + _add_parent_links(items) + + missing_from_config = [] + for file in documentation_pages: + if file.page is None: + # Any documentation files not found in the nav should still have an associated page, so we + # create them here. The Page object will automatically be assigned to `file.page` during + # its creation (and this is the only way in which these page objects are accessible). + Page(None, file, config) + if file.inclusion.is_in_nav(): + missing_from_config.append(file.src_path) + if missing_from_config: + log.log( + config.validation.nav.omitted_files, + 'The following pages exist in the docs directory, but are not ' + 'included in the "nav" configuration:\n - ' + '\n - '.join(missing_from_config), + ) + + links = _get_by_type(items, Link) + for link in links: + scheme, netloc, path, query, fragment = urlsplit(link.url) + if scheme or netloc: + log.debug(f"An external link to '{link.url}' is included in the 'nav' configuration.") + elif link.url.startswith('/'): + log.log( + config.validation.nav.absolute_links, + f"An absolute path to '{link.url}' is included in the 'nav' " + "configuration, which presumably points to an external resource.", + ) + else: + log.log( + config.validation.nav.not_found, + f"A relative path to '{link.url}' is included in the 'nav' " + "configuration, which is not found in the documentation files.", + ) + return Navigation(items, pages) + + +def _data_to_navigation(data, files: Files, config: MkDocsConfig): + if isinstance(data, dict): + return [ + _data_to_navigation((key, value), files, config) + if isinstance(value, str) + else Section(title=key, children=_data_to_navigation(value, files, config)) + for key, value in data.items() + ] + elif isinstance(data, list): + return [ + _data_to_navigation(item, files, config)[0] + if isinstance(item, dict) and len(item) == 1 + else _data_to_navigation(item, files, config) + for item in data + ] + title, path = data if isinstance(data, tuple) else (None, data) + file = files.get_file_from_path(path) + if file: + if file.inclusion.is_excluded(): + log.log( + min(logging.INFO, config.validation.nav.not_found), + f"A reference to '{file.src_path}' is included in the 'nav' " + "configuration, but this file is excluded from the built site.", + ) + page = file.page + if page is not None: + if isinstance(page, Page): + if type(page) is not Page: # Strict subclass + return page + warnings.warn( + "A plugin has set File.page to an instance of Page and it got overwritten. " + "The behavior of this will change in MkDocs 1.6.", + DeprecationWarning, + ) + else: + warnings.warn( # type: ignore[unreachable] + "A plugin has set File.page to a type other than Page. " + "This will be an error in MkDocs 1.6.", + DeprecationWarning, + ) + return Page(title, file, config) + return Link(title, path) + + +T = TypeVar('T') + + +def _get_by_type(nav, t: type[T]) -> list[T]: + ret = [] + for item in nav: + if isinstance(item, t): + ret.append(item) + if item.children: + ret.extend(_get_by_type(item.children, t)) + return ret + + +def _add_parent_links(nav) -> None: + for item in nav: + if item.is_section: + for child in item.children: + child.parent = item + _add_parent_links(item.children) + + +def _add_previous_and_next_links(pages: list[Page]) -> None: + bookended = [None, *pages, None] + zipped = zip(bookended[:-2], pages, bookended[2:]) + for page0, page1, page2 in zipped: + page1.previous_page, page1.next_page = page0, page2 diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/structure/pages.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/structure/pages.py new file mode 100644 index 0000000000000000000000000000000000000000..e51ca2ba3a9c84ec6e5e4b2b70b9392c7a2b01e5 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/structure/pages.py @@ -0,0 +1,458 @@ +from __future__ import annotations + +import copy +import logging +import posixpath +import warnings +from typing import TYPE_CHECKING, Any, Callable, Iterator, MutableMapping, Sequence +from urllib.parse import unquote as urlunquote +from urllib.parse import urljoin, urlsplit, urlunsplit + +import markdown +import markdown.postprocessors +import markdown.treeprocessors +from markdown.util import AMP_SUBSTITUTE + +from mkdocs import utils +from mkdocs.structure import StructureItem +from mkdocs.structure.toc import get_toc +from mkdocs.utils import _removesuffix, get_build_date, get_markdown_title, meta, weak_property + +if TYPE_CHECKING: + from xml.etree import ElementTree as etree + + from mkdocs.config.defaults import MkDocsConfig + from mkdocs.structure.files import File, Files + from mkdocs.structure.toc import TableOfContents + + +log = logging.getLogger(__name__) + + +class Page(StructureItem): + def __init__(self, title: str | None, file: File, config: MkDocsConfig) -> None: + file.page = self + self.file = file + if title is not None: + self.title = title + + # Navigation attributes + self.children = None + self.previous_page = None + self.next_page = None + self.active = False + + self.update_date = get_build_date() + + self._set_canonical_url(config.get('site_url', None)) + self._set_edit_url( + config.get('repo_url', None), config.get('edit_uri'), config.get('edit_uri_template') + ) + + # Placeholders to be filled in later in the build process. + self.markdown = None + self._title_from_render: str | None = None + self.content = None + self.toc = [] # type: ignore + self.meta = {} + + def __eq__(self, other) -> bool: + return ( + isinstance(other, self.__class__) + and self.title == other.title + and self.file == other.file + ) + + def __repr__(self): + name = self.__class__.__name__ + title = f"{self.title!r}" if self.title is not None else '[blank]' + url = self.abs_url or self.file.url + return f"{name}(title={title}, url={url!r})" + + markdown: str | None + """The original Markdown content from the file.""" + + content: str | None + """The rendered Markdown as HTML, this is the contents of the documentation.""" + + toc: TableOfContents + """An iterable object representing the Table of contents for a page. Each item in + the `toc` is an [`AnchorLink`][mkdocs.structure.toc.AnchorLink].""" + + meta: MutableMapping[str, Any] + """A mapping of the metadata included at the top of the markdown page.""" + + @property + def url(self) -> str: + """The URL of the page relative to the MkDocs `site_dir`.""" + url = self.file.url + if url in ('.', './'): + return '' + return url + + file: File + """The documentation [`File`][mkdocs.structure.files.File] that the page is being rendered from.""" + + abs_url: str | None + """The absolute URL of the page from the server root as determined by the value + assigned to the [site_url][] configuration setting. The value includes any + subdirectory included in the `site_url`, but not the domain. [base_url][] should + not be used with this variable.""" + + canonical_url: str | None + """The full, canonical URL to the current page as determined by the value assigned + to the [site_url][] configuration setting. The value includes the domain and any + subdirectory included in the `site_url`. [base_url][] should not be used with this + variable.""" + + @property + def active(self) -> bool: + """When `True`, indicates that this page is the currently viewed page. Defaults to `False`.""" + return self.__active + + @active.setter + def active(self, value: bool): + """Set active status of page and ancestors.""" + self.__active = bool(value) + if self.parent is not None: + self.parent.active = bool(value) + + @property + def is_index(self) -> bool: + return self.file.name == 'index' + + edit_url: str | None + """The full URL to the source page in the source repository. Typically used to + provide a link to edit the source page. [base_url][] should not be used with this + variable.""" + + @property + def is_homepage(self) -> bool: + """Evaluates to `True` for the homepage of the site and `False` for all other pages.""" + return self.is_top_level and self.is_index and self.file.url in ('.', './', 'index.html') + + previous_page: Page | None + """The [page][mkdocs.structure.pages.Page] object for the previous page or `None`. + The value will be `None` if the current page is the first item in the site navigation + or if the current page is not included in the navigation at all.""" + + next_page: Page | None + """The [page][mkdocs.structure.pages.Page] object for the next page or `None`. + The value will be `None` if the current page is the last item in the site navigation + or if the current page is not included in the navigation at all.""" + + children: None = None + """Pages do not contain children and the attribute is always `None`.""" + + is_section: bool = False + """Indicates that the navigation object is a "section" object. Always `False` for page objects.""" + + is_page: bool = True + """Indicates that the navigation object is a "page" object. Always `True` for page objects.""" + + is_link: bool = False + """Indicates that the navigation object is a "link" object. Always `False` for page objects.""" + + def _set_canonical_url(self, base: str | None) -> None: + if base: + if not base.endswith('/'): + base += '/' + self.canonical_url = canonical_url = urljoin(base, self.url) + self.abs_url = urlsplit(canonical_url).path + else: + self.canonical_url = None + self.abs_url = None + + def _set_edit_url( + self, + repo_url: str | None, + edit_uri: str | None = None, + edit_uri_template: str | None = None, + ) -> None: + if edit_uri or edit_uri_template: + src_uri = self.file.src_uri + if edit_uri_template: + noext = posixpath.splitext(src_uri)[0] + edit_uri = edit_uri_template.format(path=src_uri, path_noext=noext) + else: + assert edit_uri is not None and edit_uri.endswith('/') + edit_uri += src_uri + if repo_url: + # Ensure urljoin behavior is correct + if not edit_uri.startswith(('?', '#')) and not repo_url.endswith('/'): + repo_url += '/' + else: + try: + parsed_url = urlsplit(edit_uri) + if not parsed_url.scheme or not parsed_url.netloc: + log.warning( + f"edit_uri: {edit_uri!r} is not a valid URL, it should include the http:// (scheme)" + ) + except ValueError as e: + log.warning(f"edit_uri: {edit_uri!r} is not a valid URL: {e}") + + self.edit_url = urljoin(repo_url or '', edit_uri) + else: + self.edit_url = None + + def read_source(self, config: MkDocsConfig) -> None: + source = config.plugins.on_page_read_source(page=self, config=config) + if source is None: + try: + with open(self.file.abs_src_path, encoding='utf-8-sig', errors='strict') as f: + source = f.read() + except OSError: + log.error(f'File not found: {self.file.src_path}') + raise + except ValueError: + log.error(f'Encoding error reading file: {self.file.src_path}') + raise + + self.markdown, self.meta = meta.get_data(source) + + def _set_title(self) -> None: + warnings.warn( + "_set_title is no longer used in MkDocs and will be removed soon.", DeprecationWarning + ) + + @weak_property + def title(self) -> str | None: # type: ignore[override] + """ + Returns the title for the current page. + + Before calling `read_source()`, this value is empty. It can also be updated by `render()`. + + Check these in order and use the first that returns a valid title: + - value provided on init (passed in from config) + - value of metadata 'title' + - content of the first H1 in Markdown content + - convert filename to title + """ + if self.markdown is None: + return None + + if 'title' in self.meta: + return self.meta['title'] + + if self._title_from_render: + return self._title_from_render + elif self.content is None: # Preserve legacy behavior only for edge cases in plugins. + title_from_md = get_markdown_title(self.markdown) + if title_from_md is not None: + return title_from_md + + if self.is_homepage: + return 'Home' + + title = self.file.name.replace('-', ' ').replace('_', ' ') + # Capitalize if the filename was all lowercase, otherwise leave it as-is. + if title.lower() == title: + title = title.capitalize() + return title + + def render(self, config: MkDocsConfig, files: Files) -> None: + """ + Convert the Markdown source file to HTML as per the config. + """ + if self.markdown is None: + raise RuntimeError("`markdown` field hasn't been set (via `read_source`)") + + md = markdown.Markdown( + extensions=config['markdown_extensions'], + extension_configs=config['mdx_configs'] or {}, + ) + + relative_path_ext = _RelativePathTreeprocessor(self.file, files, config) + relative_path_ext._register(md) + + extract_title_ext = _ExtractTitleTreeprocessor() + extract_title_ext._register(md) + + self.content = md.convert(self.markdown) + self.toc = get_toc(getattr(md, 'toc_tokens', [])) + self._title_from_render = extract_title_ext.title + + +class _RelativePathTreeprocessor(markdown.treeprocessors.Treeprocessor): + def __init__(self, file: File, files: Files, config: MkDocsConfig) -> None: + self.file = file + self.files = files + self.config = config + + def run(self, root: etree.Element) -> etree.Element: + """ + Update urls on anchors and images to make them relative + + Iterates through the full document tree looking for specific + tags and then makes them relative based on the site navigation + """ + for element in root.iter(): + if element.tag == 'a': + key = 'href' + elif element.tag == 'img': + key = 'src' + else: + continue + + url = element.get(key) + assert url is not None + new_url = self.path_to_url(url) + element.set(key, new_url) + + return root + + @classmethod + def _target_uri(cls, src_path: str, dest_path: str): + return posixpath.normpath( + posixpath.join(posixpath.dirname(src_path), dest_path).lstrip('/') + ) + + @classmethod + def _possible_target_uris( + cls, file: File, path: str, use_directory_urls: bool + ) -> Iterator[str]: + """First yields the resolved file uri for the link, then proceeds to yield guesses for possible mistakes.""" + target_uri = cls._target_uri(file.src_uri, path) + yield target_uri + + if posixpath.normpath(path) == '.': + # Explicitly link to current file. + yield file.src_uri + return + tried = {target_uri} + + prefixes = [target_uri, cls._target_uri(file.url, path)] + if prefixes[0] == prefixes[1]: + prefixes.pop() + + suffixes: list[Callable[[str], str]] = [] + if use_directory_urls: + suffixes.append(lambda p: p) + if not posixpath.splitext(target_uri)[-1]: + suffixes.append(lambda p: posixpath.join(p, 'index.md')) + suffixes.append(lambda p: posixpath.join(p, 'README.md')) + if ( + not target_uri.endswith('.') + and not path.endswith('.md') + and (use_directory_urls or not path.endswith('/')) + ): + suffixes.append(lambda p: _removesuffix(p, '.html') + '.md') + + for pref in prefixes: + for suf in suffixes: + guess = posixpath.normpath(suf(pref)) + if guess not in tried and not guess.startswith('../'): + yield guess + tried.add(guess) + + def path_to_url(self, url: str) -> str: + scheme, netloc, path, query, fragment = urlsplit(url) + + warning_level, warning = 0, '' + + # Ignore URLs unless they are a relative link to a source file. + if scheme or netloc: # External link. + return url + elif url.startswith(('/', '\\')): # Absolute link. + warning_level = self.config.validation.links.absolute_links + warning = f"Doc file '{self.file.src_uri}' contains an absolute link '{url}', it was left as is." + elif AMP_SUBSTITUTE in url: # AMP_SUBSTITUTE is used internally by Markdown only for email. + return url + elif not path: # Self-link containing only query or fragment. + return url + + path = urlunquote(path) + # Determine the filepath of the target. + possible_target_uris = self._possible_target_uris( + self.file, path, self.config.use_directory_urls + ) + + if warning: + # For absolute path (already has a warning), the primary lookup path should be preserved as a tip option. + target_uri = url + target_file = None + else: + # Validate that the target exists in files collection. + target_uri = next(possible_target_uris) + target_file = self.files.get_file_from_path(target_uri) + + if target_file is None and not warning: + # Primary lookup path had no match, definitely produce a warning, just choose which one. + if not posixpath.splitext(path)[-1]: + # No '.' in the last part of a path indicates path does not point to a file. + warning_level = self.config.validation.links.unrecognized_links + warning = ( + f"Doc file '{self.file.src_uri}' contains an unrecognized relative link '{url}', " + f"it was left as is." + ) + else: + target = f" '{target_uri}'" if target_uri != url else "" + warning_level = self.config.validation.links.not_found + warning = ( + f"Doc file '{self.file.src_uri}' contains a relative link '{url}', " + f"but the target{target} is not found among documentation files." + ) + + if warning: + # There was no match, so try to guess what other file could've been intended. + if warning_level > logging.DEBUG: + suggest_url = '' + for path in possible_target_uris: + if self.files.get_file_from_path(path) is not None: + if fragment and path == self.file.src_uri: + path = '' + else: + path = utils.get_relative_url(path, self.file.src_uri) + suggest_url = urlunsplit(('', '', path, query, fragment)) + break + else: + if '@' in url and '.' in url and '/' not in url: + suggest_url = f'mailto:{url}' + if suggest_url: + warning += f" Did you mean '{suggest_url}'?" + log.log(warning_level, warning) + return url + + assert target_uri is not None + assert target_file is not None + if target_file.inclusion.is_excluded(): + warning_level = min(logging.INFO, self.config.validation.links.not_found) + warning = ( + f"Doc file '{self.file.src_uri}' contains a link to " + f"'{target_uri}' which is excluded from the built site." + ) + log.log(warning_level, warning) + path = utils.get_relative_url(target_file.url, self.file.url) + return urlunsplit(('', '', path, query, fragment)) + + def _register(self, md: markdown.Markdown) -> None: + md.treeprocessors.register(self, "relpath", 0) + + +class _ExtractTitleTreeprocessor(markdown.treeprocessors.Treeprocessor): + title: str | None = None + postprocessors: Sequence[markdown.postprocessors.Postprocessor] = () + + def run(self, root: etree.Element) -> etree.Element: + for el in root: + if el.tag == 'h1': + # Drop anchorlink from the element, if present. + if len(el) > 0 and el[-1].tag == 'a' and not (el[-1].tail or '').strip(): + el = copy.copy(el) + del el[-1] + # Extract the text only, recursively. + title = ''.join(el.itertext()) + # Unescape per Markdown implementation details. + for pp in self.postprocessors: + title = pp.run(title) + self.title = title + break + return root + + def _register(self, md: markdown.Markdown) -> None: + self.postprocessors = tuple(md.postprocessors) + md.treeprocessors.register( + self, + "mkdocs_extract_title", + priority=-1, # After the end. + ) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/structure/toc.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/structure/toc.py new file mode 100644 index 0000000000000000000000000000000000000000..d52a57d01bdc235d935225a5f39020ca59bd645e --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/structure/toc.py @@ -0,0 +1,90 @@ +""" +Deals with generating the per-page table of contents. + +For the sake of simplicity we use the Python-Markdown `toc` extension to +generate a list of dicts for each toc item, and then store it as AnchorLinks to +maintain compatibility with older versions of MkDocs. +""" +from __future__ import annotations + +import sys +from typing import Iterable, Iterator + +if sys.version_info >= (3, 8): + from typing import TypedDict +else: + from typing_extensions import TypedDict + + +class _TocToken(TypedDict): + level: int + id: str + name: str + children: list[_TocToken] + + +def get_toc(toc_tokens: list[_TocToken]) -> TableOfContents: + toc = [_parse_toc_token(i) for i in toc_tokens] + # For the table of contents, always mark the first element as active + if len(toc): + toc[0].active = True # type: ignore[attr-defined] + return TableOfContents(toc) + + +class AnchorLink: + """ + A single entry in the table of contents. + """ + + def __init__(self, title: str, id: str, level: int) -> None: + self.title, self.id, self.level = title, id, level + self.children = [] + + title: str + """The text of the item.""" + + @property + def url(self) -> str: + """The hash fragment of a URL pointing to the item.""" + return '#' + self.id + + level: int + """The zero-based level of the item.""" + + children: list[AnchorLink] + """An iterable of any child items.""" + + def __str__(self) -> str: + return self.indent_print() + + def indent_print(self, depth: int = 0) -> str: + indent = ' ' * depth + ret = f'{indent}{self.title} - {self.url}\n' + for item in self.children: + ret += item.indent_print(depth + 1) + return ret + + +class TableOfContents(Iterable[AnchorLink]): + """ + Represents the table of contents for a given page. + """ + + def __init__(self, items: list[AnchorLink]) -> None: + self.items = items + + def __iter__(self) -> Iterator[AnchorLink]: + return iter(self.items) + + def __len__(self) -> int: + return len(self.items) + + def __str__(self) -> str: + return ''.join(str(item) for item in self) + + +def _parse_toc_token(token: _TocToken) -> AnchorLink: + anchor = AnchorLink(token['name'], token['id'], token['level']) + for i in token['children']: + anchor.children.append(_parse_toc_token(i)) + return anchor diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/templates/sitemap.xml b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/templates/sitemap.xml new file mode 100644 index 0000000000000000000000000000000000000000..e60c7d01292e195e3d2929c9a3f72965685f7aeb --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/templates/sitemap.xml @@ -0,0 +1,12 @@ + + +{%- for file in pages -%} + {% if not file.page.is_link and (file.page.abs_url or file.page.canonical_url) %} + + {% if file.page.canonical_url %}{{ file.page.canonical_url|e }}{% else %}{{ file.page.abs_url|e }}{% endif %} + {% if file.page.update_date %}{{file.page.update_date}}{% endif %} + daily + + {%- endif -%} +{% endfor %} + diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e0248786db7a34ff2608aeeea701de703faed458 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/__init__.py @@ -0,0 +1,16 @@ +import logging +import unittest.util + +unittest.util._MAX_LENGTH = 100000 + + +class DisallowLogsHandler(logging.Handler): + def __init__(self, level=logging.WARNING): + super().__init__(level=level) + self.formatter = logging.Formatter("%(levelname)s:%(name)s:%(message)s") + + def emit(self, record): + raise AssertionError(f'Unexpected log: {self.format(record)!r}') + + +logging.lastResort = DisallowLogsHandler() # type: ignore diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..710645415300c714da0d91d781dacc3bc684e6e5 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/__pycache__/base.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/__pycache__/base.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..38e287e45d78010241ee7e3305b41da100d95ca4 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/__pycache__/base.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/__pycache__/build_tests.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/__pycache__/build_tests.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c7a3c2fb8b50715327d0c317a70d1bc1d2e6517c Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/__pycache__/build_tests.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/__pycache__/cli_tests.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/__pycache__/cli_tests.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b47998e5a751491c1e67d36f1690f7fe70ee3c8 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/__pycache__/cli_tests.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/__pycache__/get_deps_tests.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/__pycache__/get_deps_tests.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c0fe46535548de79ffc6f7e6d28fb20c4adc693 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/__pycache__/get_deps_tests.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/__pycache__/gh_deploy_tests.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/__pycache__/gh_deploy_tests.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..69b23014b332c250627715e96d1d650f0be03520 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/__pycache__/gh_deploy_tests.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/__pycache__/integration.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/__pycache__/integration.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aea71f786b1733370f1f966e40fbb453c895beac Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/__pycache__/integration.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/__pycache__/livereload_tests.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/__pycache__/livereload_tests.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..70a06869d9a7bd5fce072c28297445fa2306e2cd Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/__pycache__/livereload_tests.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/__pycache__/localization_tests.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/__pycache__/localization_tests.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..adf9b929c38f0f6b004ecf915df475604e045477 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/__pycache__/localization_tests.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/__pycache__/new_tests.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/__pycache__/new_tests.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..755c28b3fd5796e034afff710b3719381d32dfa0 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/__pycache__/new_tests.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/__pycache__/plugin_tests.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/__pycache__/plugin_tests.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3925d06e72283fed9b1ae21f19d5dd325c8b6b8e Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/__pycache__/plugin_tests.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/__pycache__/search_tests.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/__pycache__/search_tests.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1d35b192ef7a7aec47c34ecc151a304146de2b73 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/__pycache__/search_tests.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/__pycache__/theme_tests.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/__pycache__/theme_tests.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0c150e8a96455cb7458a8116e75a186fc7c1363d Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/__pycache__/theme_tests.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/base.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/base.py new file mode 100644 index 0000000000000000000000000000000000000000..c480eaa26e2a76a5e1d6ff9c666fb7c4fa1428f1 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/base.py @@ -0,0 +1,129 @@ +from __future__ import annotations + +import contextlib +import os +import textwrap +from functools import wraps +from tempfile import TemporaryDirectory + +import markdown + +from mkdocs import utils +from mkdocs.config.defaults import MkDocsConfig + + +def dedent(text): + return textwrap.dedent(text).strip() + + +def get_markdown_toc(markdown_source): + """Return TOC generated by Markdown parser from Markdown source text.""" + md = markdown.Markdown(extensions=['toc']) + md.convert(markdown_source) + return md.toc_tokens + + +def load_config(config_file_path: str | None = None, **cfg) -> MkDocsConfig: + """Helper to build a simple config for testing.""" + path_base = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'integration', 'minimal') + if 'site_name' not in cfg: + cfg['site_name'] = 'Example' + if 'docs_dir' not in cfg: + # Point to an actual dir to avoid a 'does not exist' error on validation. + cfg['docs_dir'] = os.path.join(path_base, 'docs') + if 'plugins' not in cfg: + cfg['plugins'] = [] + conf = MkDocsConfig(config_file_path=config_file_path or os.path.join(path_base, 'mkdocs.yml')) + conf.load_dict(cfg) + + errors_warnings = conf.validate() + assert errors_warnings == ([], []), errors_warnings + return conf + + +def tempdir(files=None, **kw): + """ + A decorator for building a temporary directory with prepopulated files. + + The temporary directory and files are created just before the wrapped function is called and are destroyed + immediately after the wrapped function returns. + + The `files` keyword should be a dict of file paths as keys and strings of file content as values. + If `files` is a list, then each item is assumed to be a path of an empty file. All other + keywords are passed to `tempfile.TemporaryDirectory` to create the parent directory. + + In the following example, two files are created in the temporary directory and then are destroyed when + the function exits: + + @tempdir(files={ + 'foo.txt': 'foo content', + 'bar.txt': 'bar content' + }) + def example(self, tdir): + assert os.path.isfile(os.path.join(tdir, 'foo.txt')) + pth = os.path.join(tdir, 'bar.txt') + assert os.path.isfile(pth) + with open(pth, 'r', encoding='utf-8') as f: + assert f.read() == 'bar content' + """ + files = {f: '' for f in files} if isinstance(files, (list, tuple)) else files or {} + + kw['prefix'] = 'mkdocs_test-' + kw.get('prefix', '') + + def decorator(fn): + @wraps(fn) + def wrapper(self, *args): + with TemporaryDirectory(**kw) as td: + for path, content in files.items(): + pth = os.path.join(td, path) + utils.write_file(content.encode(encoding='utf-8'), pth) + return fn(self, td, *args) + + return wrapper + + return decorator + + +@contextlib.contextmanager +def change_dir(path): + old_cwd = os.getcwd() + os.chdir(path) + try: + yield + finally: + os.chdir(old_cwd) + + +class PathAssertionMixin: + """ + Assertion methods for testing paths. + + Each method accepts one or more strings, which are first joined using os.path.join. + """ + + def assertPathsEqual(self, a, b, msg=None): + self.assertEqual(a.replace(os.sep, '/'), b.replace(os.sep, '/')) + + def assertPathExists(self, *parts): + path = os.path.join(*parts) + if not os.path.exists(path): + msg = self._formatMessage(None, f"The path '{path}' does not exist") + raise self.failureException(msg) + + def assertPathNotExists(self, *parts): + path = os.path.join(*parts) + if os.path.exists(path): + msg = self._formatMessage(None, f"The path '{path}' does exist") + raise self.failureException(msg) + + def assertPathIsFile(self, *parts): + path = os.path.join(*parts) + if not os.path.isfile(path): + msg = self._formatMessage(None, f"The path '{path}' is not a file that exists") + raise self.failureException(msg) + + def assertPathIsDir(self, *parts): + path = os.path.join(*parts) + if not os.path.isdir(path): + msg = self._formatMessage(None, f"The path '{path}' is not a directory that exists") + raise self.failureException(msg) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/build_tests.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/build_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..ff62a8285f6c1e5a0e775c9700385e3bdb87b68c --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/build_tests.py @@ -0,0 +1,825 @@ +#!/usr/bin/env python +from __future__ import annotations + +import contextlib +import io +import os.path +import re +import textwrap +import unittest +from pathlib import Path +from typing import TYPE_CHECKING +from unittest import mock + +import markdown.preprocessors + +from mkdocs.commands import build +from mkdocs.config import base +from mkdocs.exceptions import PluginError +from mkdocs.livereload import LiveReloadServer +from mkdocs.structure.files import File, Files +from mkdocs.structure.nav import get_navigation +from mkdocs.structure.pages import Page +from mkdocs.tests.base import PathAssertionMixin, load_config, tempdir +from mkdocs.utils import meta + +if TYPE_CHECKING: + from mkdocs.config.defaults import MkDocsConfig + + +def build_page(title, path, config, md_src=''): + """Helper which returns a Page object.""" + + files = Files([File(path, config.docs_dir, config.site_dir, config.use_directory_urls)]) + page = Page(title, list(files)[0], config) + # Fake page.read_source() + page.markdown, page.meta = meta.get_data(md_src) + return page, files + + +def testing_server(root, builder=lambda: None, mount_path="/"): + with mock.patch("socket.socket"): + return LiveReloadServer( + builder, host="localhost", port=123, root=root, mount_path=mount_path + ) + + +class BuildTests(PathAssertionMixin, unittest.TestCase): + def _get_env_with_null_translations(self, config): + env = config.theme.get_env() + env.add_extension('jinja2.ext.i18n') + env.install_null_translations() + return env + + # Test build.get_context + + def test_context_base_url_homepage(self): + nav_cfg = [ + {'Home': 'index.md'}, + ] + cfg = load_config(nav=nav_cfg, use_directory_urls=False) + fs = [File('index.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls)] + files = Files(fs) + nav = get_navigation(files, cfg) + context = build.get_context(nav, files, cfg, nav.pages[0]) + self.assertEqual(context['base_url'], '.') + + def test_context_base_url_homepage_use_directory_urls(self): + nav_cfg = [ + {'Home': 'index.md'}, + ] + cfg = load_config(nav=nav_cfg) + fs = [File('index.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls)] + files = Files(fs) + nav = get_navigation(files, cfg) + context = build.get_context(nav, files, cfg, nav.pages[0]) + self.assertEqual(context['base_url'], '.') + + def test_context_base_url_nested_page(self): + nav_cfg = [ + {'Home': 'index.md'}, + {'Nested': 'foo/bar.md'}, + ] + cfg = load_config(nav=nav_cfg, use_directory_urls=False) + fs = [ + File('index.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls), + File('foo/bar.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls), + ] + files = Files(fs) + nav = get_navigation(files, cfg) + context = build.get_context(nav, files, cfg, nav.pages[1]) + self.assertEqual(context['base_url'], '..') + + def test_context_base_url_nested_page_use_directory_urls(self): + nav_cfg = [ + {'Home': 'index.md'}, + {'Nested': 'foo/bar.md'}, + ] + cfg = load_config(nav=nav_cfg) + fs = [ + File('index.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls), + File('foo/bar.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls), + ] + files = Files(fs) + nav = get_navigation(files, cfg) + context = build.get_context(nav, files, cfg, nav.pages[1]) + self.assertEqual(context['base_url'], '../..') + + def test_context_base_url_relative_no_page(self): + cfg = load_config(use_directory_urls=False) + context = build.get_context(mock.Mock(), mock.Mock(), cfg, base_url='..') + self.assertEqual(context['base_url'], '..') + + def test_context_base_url_relative_no_page_use_directory_urls(self): + cfg = load_config() + context = build.get_context(mock.Mock(), mock.Mock(), cfg, base_url='..') + self.assertEqual(context['base_url'], '..') + + def test_context_base_url_absolute_no_page(self): + cfg = load_config(use_directory_urls=False) + context = build.get_context(mock.Mock(), mock.Mock(), cfg, base_url='/') + self.assertEqual(context['base_url'], '/') + + def test_context_base_url__absolute_no_page_use_directory_urls(self): + cfg = load_config() + context = build.get_context(mock.Mock(), mock.Mock(), cfg, base_url='/') + self.assertEqual(context['base_url'], '/') + + def test_context_base_url_absolute_nested_no_page(self): + cfg = load_config(use_directory_urls=False) + context = build.get_context(mock.Mock(), mock.Mock(), cfg, base_url='/foo/') + self.assertEqual(context['base_url'], '/foo/') + + def test_context_base_url__absolute_nested_no_page_use_directory_urls(self): + cfg = load_config() + context = build.get_context(mock.Mock(), mock.Mock(), cfg, base_url='/foo/') + self.assertEqual(context['base_url'], '/foo/') + + def test_context_extra_css_js_from_homepage(self): + nav_cfg = [ + {'Home': 'index.md'}, + ] + cfg = load_config( + nav=nav_cfg, + extra_css=['style.css'], + extra_javascript=['script.js'], + use_directory_urls=False, + ) + fs = [File('index.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls)] + files = Files(fs) + nav = get_navigation(files, cfg) + context = build.get_context(nav, files, cfg, nav.pages[0]) + self.assertEqual(context['extra_css'], ['style.css']) + self.assertEqual(context['extra_javascript'], ['script.js']) + + def test_context_extra_css_js_from_nested_page(self): + nav_cfg = [ + {'Home': 'index.md'}, + {'Nested': 'foo/bar.md'}, + ] + cfg = load_config( + nav=nav_cfg, + extra_css=['style.css'], + extra_javascript=['script.js'], + use_directory_urls=False, + ) + fs = [ + File('index.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls), + File('foo/bar.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls), + ] + files = Files(fs) + nav = get_navigation(files, cfg) + context = build.get_context(nav, files, cfg, nav.pages[1]) + self.assertEqual(context['extra_css'], ['../style.css']) + self.assertEqual(context['extra_javascript'], ['../script.js']) + + def test_context_extra_css_js_from_nested_page_use_directory_urls(self): + nav_cfg = [ + {'Home': 'index.md'}, + {'Nested': 'foo/bar.md'}, + ] + cfg = load_config( + nav=nav_cfg, + extra_css=['style.css'], + extra_javascript=['script.js'], + ) + fs = [ + File('index.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls), + File('foo/bar.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls), + ] + files = Files(fs) + nav = get_navigation(files, cfg) + context = build.get_context(nav, files, cfg, nav.pages[1]) + self.assertEqual(context['extra_css'], ['../../style.css']) + self.assertEqual(context['extra_javascript'], ['../../script.js']) + + # TODO: This shouldn't pass on Linux + # @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows") + def test_context_extra_css_path_warning(self): + nav_cfg = [ + {'Home': 'index.md'}, + ] + cfg = load_config( + nav=nav_cfg, + extra_css=['assets\\style.css'], + use_directory_urls=False, + ) + fs = [File('index.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls)] + files = Files(fs) + nav = get_navigation(files, cfg) + with self.assertLogs('mkdocs') as cm: + context = build.get_context(nav, files, cfg, nav.pages[0]) + self.assertEqual(context['extra_css'], ['assets/style.css']) + self.assertEqual( + '\n'.join(cm.output), + "WARNING:mkdocs.utils:Path 'assets\\style.css' uses OS-specific separator '\\'. " + "That will be unsupported in a future release. Please change it to '/'.", + ) + + def test_context_extra_css_js_no_page(self): + cfg = load_config(extra_css=['style.css'], extra_javascript=['script.js']) + context = build.get_context(mock.Mock(), mock.Mock(), cfg, base_url='..') + self.assertEqual(context['extra_css'], ['../style.css']) + self.assertEqual(context['extra_javascript'], ['../script.js']) + + def test_extra_context(self): + cfg = load_config(extra={'a': 1}) + context = build.get_context(mock.Mock(), mock.Mock(), cfg) + self.assertEqual(context['config']['extra']['a'], 1) + + # Test build._build_theme_template + + @mock.patch('mkdocs.utils.write_file') + @mock.patch('mkdocs.commands.build._build_template', return_value='some content') + def test_build_theme_template(self, mock_build_template, mock_write_file): + cfg = load_config() + env = cfg.theme.get_env() + build._build_theme_template('main.html', env, mock.Mock(), cfg, mock.Mock()) + mock_write_file.assert_called_once() + mock_build_template.assert_called_once() + + @mock.patch('mkdocs.utils.write_file') + @mock.patch('mkdocs.commands.build._build_template', return_value='some content') + @mock.patch('gzip.GzipFile') + @tempdir() + def test_build_sitemap_template( + self, site_dir, mock_gzip_gzipfile, mock_build_template, mock_write_file + ): + cfg = load_config(site_dir=site_dir) + env = cfg.theme.get_env() + build._build_theme_template('sitemap.xml', env, mock.Mock(), cfg, mock.Mock()) + mock_write_file.assert_called_once() + mock_build_template.assert_called_once() + mock_gzip_gzipfile.assert_called_once() + + @mock.patch('mkdocs.utils.write_file') + @mock.patch('mkdocs.commands.build._build_template', return_value='') + def test_skip_missing_theme_template(self, mock_build_template, mock_write_file): + cfg = load_config() + env = cfg.theme.get_env() + with self.assertLogs('mkdocs') as cm: + build._build_theme_template('missing.html', env, mock.Mock(), cfg, mock.Mock()) + self.assertEqual( + '\n'.join(cm.output), + "WARNING:mkdocs.commands.build:Template skipped: 'missing.html' not found in theme directories.", + ) + mock_write_file.assert_not_called() + mock_build_template.assert_not_called() + + @mock.patch('mkdocs.utils.write_file') + @mock.patch('mkdocs.commands.build._build_template', return_value='') + def test_skip_theme_template_empty_output(self, mock_build_template, mock_write_file): + cfg = load_config() + env = cfg.theme.get_env() + with self.assertLogs('mkdocs') as cm: + build._build_theme_template('main.html', env, mock.Mock(), cfg, mock.Mock()) + self.assertEqual( + '\n'.join(cm.output), + "INFO:mkdocs.commands.build:Template skipped: 'main.html' generated empty output.", + ) + mock_write_file.assert_not_called() + mock_build_template.assert_called_once() + + # Test build._build_extra_template + + @tempdir() + @mock.patch('mkdocs.commands.build.open', mock.mock_open(read_data='template content')) + def test_build_extra_template(self, site_dir): + cfg = load_config(site_dir=site_dir) + fs = [File('foo.html', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls)] + files = Files(fs) + build._build_extra_template('foo.html', files, cfg, mock.Mock()) + + @mock.patch('mkdocs.commands.build.open', mock.mock_open(read_data='template content')) + def test_skip_missing_extra_template(self): + cfg = load_config() + fs = [File('foo.html', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls)] + files = Files(fs) + with self.assertLogs('mkdocs') as cm: + build._build_extra_template('missing.html', files, cfg, mock.Mock()) + self.assertEqual( + '\n'.join(cm.output), + "WARNING:mkdocs.commands.build:Template skipped: 'missing.html' not found in docs_dir.", + ) + + @mock.patch('mkdocs.commands.build.open', side_effect=OSError('Error message.')) + def test_skip_ioerror_extra_template(self, mock_open): + cfg = load_config() + fs = [File('foo.html', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls)] + files = Files(fs) + with self.assertLogs('mkdocs') as cm: + build._build_extra_template('foo.html', files, cfg, mock.Mock()) + self.assertEqual( + '\n'.join(cm.output), + "WARNING:mkdocs.commands.build:Error reading template 'foo.html': Error message.", + ) + + @mock.patch('mkdocs.commands.build.open', mock.mock_open(read_data='')) + def test_skip_extra_template_empty_output(self): + cfg = load_config() + fs = [File('foo.html', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls)] + files = Files(fs) + with self.assertLogs('mkdocs') as cm: + build._build_extra_template('foo.html', files, cfg, mock.Mock()) + self.assertEqual( + '\n'.join(cm.output), + "INFO:mkdocs.commands.build:Template skipped: 'foo.html' generated empty output.", + ) + + # Test build._populate_page + + @tempdir(files={'index.md': 'page content'}) + def test_populate_page(self, docs_dir): + cfg = load_config(docs_dir=docs_dir) + file = File('index.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls) + page = Page('Foo', file, cfg) + build._populate_page(page, cfg, Files([file])) + self.assertEqual(page.content, '

page content

') + + @tempdir(files={'testing.html': '

page content

'}) + def test_populate_page_dirty_modified(self, site_dir): + cfg = load_config(site_dir=site_dir) + file = File('testing.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls) + page = Page('Foo', file, cfg) + build._populate_page(page, cfg, Files([file]), dirty=True) + self.assertTrue(page.markdown.startswith('# Welcome to MkDocs')) + self.assertTrue( + page.content.startswith('

Welcome to MkDocs

') + ) + + @tempdir(files={'index.md': 'page content'}) + @tempdir(files={'index.html': '

page content

'}) + def test_populate_page_dirty_not_modified(self, site_dir, docs_dir): + cfg = load_config(docs_dir=docs_dir, site_dir=site_dir) + file = File('index.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls) + page = Page('Foo', file, cfg) + build._populate_page(page, cfg, Files([file]), dirty=True) + # Content is empty as file read was skipped + self.assertEqual(page.markdown, None) + self.assertEqual(page.content, None) + + @tempdir(files={'index.md': 'new page content'}) + @mock.patch('mkdocs.structure.pages.open', side_effect=OSError('Error message.')) + def test_populate_page_read_error(self, docs_dir, mock_open): + cfg = load_config(docs_dir=docs_dir) + file = File('missing.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls) + page = Page('Foo', file, cfg) + with self.assertLogs('mkdocs') as cm: + with self.assertRaises(OSError): + build._populate_page(page, cfg, Files([file])) + self.assertEqual( + cm.output, + [ + 'ERROR:mkdocs.structure.pages:File not found: missing.md', + "ERROR:mkdocs.commands.build:Error reading page 'missing.md': Error message.", + ], + ) + mock_open.assert_called_once() + + @tempdir(files={'index.md': 'page content'}) + def test_populate_page_read_plugin_error(self, docs_dir): + def on_page_markdown(*args, **kwargs): + raise PluginError('Error message.') + + cfg = load_config(docs_dir=docs_dir) + cfg.plugins.events['page_markdown'].append(on_page_markdown) + + file = File('index.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls) + page = Page('Foo', file, cfg) + with self.assertLogs('mkdocs') as cm: + with self.assertRaises(PluginError): + build._populate_page(page, cfg, Files([file])) + self.assertEqual( + '\n'.join(cm.output), + "ERROR:mkdocs.commands.build:Error reading page 'index.md':", + ) + + # Test build._build_page + + @tempdir() + def test_build_page(self, site_dir): + cfg = load_config(site_dir=site_dir, nav=['index.md']) + fs = [File('index.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls)] + files = Files(fs) + nav = get_navigation(files, cfg) + page = files.documentation_pages()[0].page + # Fake populate page + page.title = 'Title' + page.markdown = 'page content' + page.content = '

page content

' + build._build_page(page, cfg, files, nav, self._get_env_with_null_translations(cfg)) + self.assertPathIsFile(site_dir, 'index.html') + + @tempdir() + @mock.patch('jinja2.environment.Template.render', return_value='') + def test_build_page_empty(self, site_dir, render_mock): + cfg = load_config(site_dir=site_dir, nav=['index.md']) + fs = [File('index.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls)] + files = Files(fs) + nav = get_navigation(files, cfg) + with self.assertLogs('mkdocs') as cm: + build._build_page( + files.documentation_pages()[0].page, cfg, files, nav, cfg.theme.get_env() + ) + self.assertEqual( + '\n'.join(cm.output), + "INFO:mkdocs.commands.build:Page skipped: 'index.md'. Generated empty output.", + ) + self.assertPathNotExists(site_dir, 'index.html') + render_mock.assert_called_once() + + @tempdir(files={'index.md': 'page content'}) + @tempdir(files={'index.html': '

page content

'}) + @mock.patch('mkdocs.utils.write_file') + def test_build_page_dirty_modified(self, site_dir, docs_dir, mock_write_file): + cfg = load_config(docs_dir=docs_dir, site_dir=site_dir, nav=['index.md']) + fs = [File('index.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls)] + files = Files(fs) + nav = get_navigation(files, cfg) + page = files.documentation_pages()[0].page + # Fake populate page + page.title = 'Title' + page.markdown = 'new page content' + page.content = '

new page content

' + build._build_page( + page, cfg, files, nav, self._get_env_with_null_translations(cfg), dirty=True + ) + mock_write_file.assert_not_called() + + @tempdir(files={'testing.html': '

page content

'}) + @mock.patch('mkdocs.utils.write_file') + def test_build_page_dirty_not_modified(self, site_dir, mock_write_file): + cfg = load_config(site_dir=site_dir, nav=['testing.md']) + fs = [File('testing.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls)] + files = Files(fs) + nav = get_navigation(files, cfg) + page = files.documentation_pages()[0].page + # Fake populate page + page.title = 'Title' + page.markdown = 'page content' + page.content = '

page content

' + build._build_page( + page, cfg, files, nav, self._get_env_with_null_translations(cfg), dirty=True + ) + mock_write_file.assert_called_once() + + @tempdir() + def test_build_page_custom_template(self, site_dir): + cfg = load_config(site_dir=site_dir, nav=['index.md']) + fs = [File('index.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls)] + files = Files(fs) + nav = get_navigation(files, cfg) + page = files.documentation_pages()[0].page + # Fake populate page + page.title = 'Title' + page.meta = {'template': '404.html'} + page.markdown = 'page content' + page.content = '

page content

' + build._build_page(page, cfg, files, nav, self._get_env_with_null_translations(cfg)) + self.assertPathIsFile(site_dir, 'index.html') + + @tempdir() + @mock.patch('mkdocs.utils.write_file', side_effect=OSError('Error message.')) + def test_build_page_error(self, site_dir, mock_write_file): + cfg = load_config(site_dir=site_dir, nav=['index.md']) + fs = [File('index.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls)] + files = Files(fs) + nav = get_navigation(files, cfg) + page = files.documentation_pages()[0].page + # Fake populate page + page.title = 'Title' + page.markdown = 'page content' + page.content = '

page content

' + with self.assertLogs('mkdocs') as cm: + with self.assertRaises(OSError): + build._build_page(page, cfg, files, nav, self._get_env_with_null_translations(cfg)) + self.assertEqual( + '\n'.join(cm.output), + "ERROR:mkdocs.commands.build:Error building page 'index.md': Error message.", + ) + mock_write_file.assert_called_once() + + @tempdir() + def test_build_page_plugin_error(self, site_dir): + def on_page_context(*args, **kwargs): + raise PluginError('Error message.') + + cfg = load_config(site_dir=site_dir, nav=['index.md']) + cfg.plugins.events['page_context'].append(on_page_context) + fs = [File('index.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls)] + files = Files(fs) + nav = get_navigation(files, cfg) + page = files.documentation_pages()[0].page + # Fake populate page + page.title = 'Title' + page.markdown = 'page content' + page.content = '

page content

' + with self.assertLogs('mkdocs') as cm: + with self.assertRaises(PluginError): + build._build_page(page, cfg, files, nav, cfg.theme.get_env()) + self.assertEqual( + '\n'.join(cm.output), + "ERROR:mkdocs.commands.build:Error building page 'index.md':", + ) + + # Test build.build + + @tempdir( + files={ + 'index.md': 'page content', + 'empty.md': '', + 'img.jpg': '', + 'static.html': 'content', + '.hidden': 'content', + '.git/hidden': 'content', + } + ) + @tempdir() + def test_copying_media(self, site_dir, docs_dir): + cfg = load_config(docs_dir=docs_dir, site_dir=site_dir) + build.build(cfg) + + # Verify that only non-empty md file (converted to html), static HTML file and image are copied. + self.assertPathIsFile(site_dir, 'index.html') + self.assertPathIsFile(site_dir, 'img.jpg') + self.assertPathIsFile(site_dir, 'static.html') + self.assertPathNotExists(site_dir, 'empty.md') + self.assertPathNotExists(site_dir, '.hidden') + self.assertPathNotExists(site_dir, '.git/hidden') + + @tempdir(files={'index.md': 'page content'}) + @tempdir() + def test_copy_theme_files(self, site_dir, docs_dir): + cfg = load_config(docs_dir=docs_dir, site_dir=site_dir) + build.build(cfg) + + # Verify only theme media are copied, not templates, Python or localization files. + self.assertPathIsFile(site_dir, 'index.html') + self.assertPathIsFile(site_dir, '404.html') + self.assertPathIsDir(site_dir, 'js') + self.assertPathIsDir(site_dir, 'css') + self.assertPathIsDir(site_dir, 'img') + self.assertPathIsDir(site_dir, 'fonts') + self.assertPathNotExists(site_dir, '__init__.py') + self.assertPathNotExists(site_dir, '__init__.pyc') + self.assertPathNotExists(site_dir, 'base.html') + self.assertPathNotExists(site_dir, 'content.html') + self.assertPathNotExists(site_dir, 'main.html') + self.assertPathNotExists(site_dir, 'locales') + + @contextlib.contextmanager + def _assert_build_logs(self, expected): + with self.assertLogs('mkdocs') as cm: + yield + msgs = [f'{r.levelname}:{r.message}' for r in cm.records] + if msgs and msgs[0].startswith('INFO:Cleaning site directory'): + del msgs[0] + if msgs and msgs[0].startswith('INFO:Building documentation to directory'): + del msgs[0] + if msgs and msgs[-1].startswith('INFO:Documentation built'): + del msgs[-1] + self.assertEqual('\n'.join(msgs), textwrap.dedent(expected).strip('\n')) + + @tempdir( + files={ + 'test/foo.md': 'page1 content, [bar](bar.md)', + 'test/bar.md': 'page2 content, [baz](baz.md)', + 'test/baz.md': 'page3 content, [foo](foo.md)', + '.zoo.md': 'page4 content', + } + ) + @tempdir() + def test_exclude_pages_with_invalid_links(self, site_dir, docs_dir): + cfg = load_config( + docs_dir=docs_dir, + site_dir=site_dir, + use_directory_urls=False, + exclude_docs='ba*.md', + ) + + with self.subTest(live_server=None): + expected_logs = ''' + INFO:Doc file 'test/foo.md' contains a link to 'test/bar.md' which is excluded from the built site. + ''' + with self._assert_build_logs(expected_logs): + build.build(cfg) + self.assertPathIsFile(site_dir, 'test', 'foo.html') + self.assertPathNotExists(site_dir, 'test', 'baz.html') + self.assertPathNotExists(site_dir, '.zoo.html') + + server = testing_server(site_dir, mount_path='/documentation/') + with self.subTest(live_server=server): + expected_logs = ''' + INFO:Doc file 'test/bar.md' contains a link to 'test/baz.md' which is excluded from the built site. + INFO:Doc file 'test/foo.md' contains a link to 'test/bar.md' which is excluded from the built site. + INFO:The following pages are being built only for the preview but will be excluded from `mkdocs build` per `exclude_docs`: + - http://localhost:123/documentation/.zoo.html + - http://localhost:123/documentation/test/bar.html + - http://localhost:123/documentation/test/baz.html + ''' + with self._assert_build_logs(expected_logs): + build.build(cfg, live_server=server) + + foo_path = Path(site_dir, 'test', 'foo.html') + self.assertTrue(foo_path.is_file()) + self.assertNotIn('DRAFT', foo_path.read_text()) + + baz_path = Path(site_dir, 'test', 'baz.html') + self.assertPathIsFile(baz_path) + self.assertIn('DRAFT', baz_path.read_text()) + + self.assertPathIsFile(site_dir, '.zoo.html') + + @tempdir( + files={ + 'foo/README.md': 'page1 content', + 'foo/index.md': 'page2 content', + } + ) + @tempdir() + def test_conflicting_readme_and_index(self, site_dir, docs_dir): + cfg = load_config(docs_dir=docs_dir, site_dir=site_dir, use_directory_urls=False) + + for server in None, testing_server(site_dir): + with self.subTest(live_server=server): + expected_logs = ''' + WARNING:Excluding 'foo/README.md' from the site because it conflicts with 'foo/index.md'. + ''' + with self._assert_build_logs(expected_logs): + build.build(cfg, live_server=server) + + index_path = Path(site_dir, 'foo', 'index.html') + self.assertPathIsFile(index_path) + self.assertRegex(index_path.read_text(), r'page2 content') + + @tempdir( + files={ + 'foo/README.md': 'page1 content', + 'foo/index.md': 'page2 content', + } + ) + @tempdir() + def test_exclude_readme_and_index(self, site_dir, docs_dir): + cfg = load_config( + docs_dir=docs_dir, site_dir=site_dir, use_directory_urls=False, exclude_docs='index.md' + ) + + for server in None, testing_server(site_dir): + with self.subTest(live_server=server): + with self._assert_build_logs(''): + build.build(cfg, live_server=server) + + index_path = Path(site_dir, 'foo', 'index.html') + self.assertPathIsFile(index_path) + self.assertRegex(index_path.read_text(), r'page1 content') + + @tempdir( + files={ + 'foo.md': 'page1 content', + 'bar.md': 'page2 content', + } + ) + @tempdir() + @tempdir() + def test_plugins_adding_files_and_interacting(self, tmp_dir, site_dir, docs_dir): + def on_files_1(files: Files, config: MkDocsConfig) -> Files: + # Plugin 1 generates a file. + Path(tmp_dir, 'SUMMARY.md').write_text('foo.md\nbar.md\n') + files.append(File('SUMMARY.md', tmp_dir, config.site_dir, config.use_directory_urls)) + return files + + def on_files_2(files: Files, config: MkDocsConfig) -> None: + # Plugin 2 reads that file and uses it to configure the nav. + f = files.get_file_from_path('SUMMARY.md') + assert f is not None + config.nav = Path(f.abs_src_path).read_text().splitlines() + + for server in None, testing_server(site_dir): + for exclude in 'full', 'nav', None: + with self.subTest(live_server=server, exclude=exclude): + cfg = load_config( + docs_dir=docs_dir, + site_dir=site_dir, + use_directory_urls=False, + exclude_docs='SUMMARY.md' if exclude == 'full' else '', + not_in_nav='SUMMARY.md' if exclude == 'nav' else '', + ) + cfg.plugins.events['files'] += [on_files_1, on_files_2] + + expected_logs = '' + if exclude is None: + expected_logs = ''' + INFO:The following pages exist in the docs directory, but are not included in the "nav" configuration: + - SUMMARY.md + ''' + if exclude == 'full' and server: + expected_logs = ''' + INFO:The following pages are being built only for the preview but will be excluded from `mkdocs build` per `exclude_docs`: + - http://localhost:123/SUMMARY.html + ''' + with self._assert_build_logs(expected_logs): + build.build(cfg, live_server=server) + + foo_path = Path(site_dir, 'foo.html') + self.assertPathIsFile(foo_path) + self.assertRegex( + foo_path.read_text(), + r'href="foo.html"[\s\S]+href="bar.html"', # Nav order is respected + ) + + summary_path = Path(site_dir, 'SUMMARY.html') + if exclude == 'full' and not server: + self.assertPathNotExists(summary_path) + else: + self.assertPathExists(summary_path) + + @tempdir( + files={ + 'README.md': 'CONFIG_README\n', + 'docs/foo.md': 'ROOT_FOO\n', + 'docs/test/bar.md': 'TEST_BAR\n', + 'docs/main/foo.md': 'MAIN_FOO\n', + 'docs/main/main.md': ( + '--8<-- "README.md"\n\n' + '--8<-- "foo.md"\n\n' + '--8<-- "test/bar.md"\n\n' + '--8<-- "../foo.md"\n\n' + ), + } + ) + def test_markdown_extension_with_relative(self, config_dir): + for base_path, expected in { + '!relative': ''' +

(Failed to read 'README.md')

+

MAIN_FOO

+

(Failed to read 'test/bar.md')

+

ROOT_FOO

''', + '!relative $docs_dir': ''' +

(Failed to read 'README.md')

+

ROOT_FOO

+

TEST_BAR

+

(Failed to read '../foo.md')

''', + '!relative $config_dir/docs': ''' +

(Failed to read 'README.md')

+

ROOT_FOO

+

TEST_BAR

+

(Failed to read '../foo.md')

''', + '!relative $config_dir': ''' +

CONFIG_README

+

(Failed to read 'foo.md')

+

(Failed to read 'test/bar.md')

+

(Failed to read '../foo.md')

''', + }.items(): + with self.subTest(base_path=base_path): + cfg = f''' + site_name: test + use_directory_urls: false + markdown_extensions: + - mkdocs.tests.build_tests: + base_path: {base_path} + ''' + config = base.load_config( + io.StringIO(cfg), config_file_path=os.path.join(config_dir, 'mkdocs.yml') + ) + + with self._assert_build_logs(''): + build.build(config) + main_path = Path(config_dir, 'site', 'main', 'main.html') + self.assertTrue(main_path.is_file()) + self.assertIn(textwrap.dedent(expected), main_path.read_text()) + + # Test build.site_directory_contains_stale_files + + @tempdir(files=['index.html']) + def test_site_dir_contains_stale_files(self, site_dir): + self.assertTrue(build.site_directory_contains_stale_files(site_dir)) + + @tempdir() + def test_not_site_dir_contains_stale_files(self, site_dir): + self.assertFalse(build.site_directory_contains_stale_files(site_dir)) + + +class _TestPreprocessor(markdown.preprocessors.Preprocessor): + def __init__(self, base_path: str) -> None: + self.base_path = base_path + + def run(self, lines: list[str]) -> list[str]: + for i, line in enumerate(lines): + m = re.search(r'^--8<-- "(.+)"$', line) + if m: + try: + lines[i] = Path(self.base_path, m[1]).read_text() + except OSError: + lines[i] = f"(Failed to read {m[1]!r})\n" + return lines + + +class _TestExtension(markdown.extensions.Extension): + def __init__(self, base_path: str) -> None: + self.base_path = base_path + + def extendMarkdown(self, md: markdown.Markdown) -> None: + md.preprocessors.register(_TestPreprocessor(self.base_path), "mkdocs_test", priority=32) + + +makeExtension = _TestExtension diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/cli_tests.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/cli_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..6ce03db1099807d768d52a2022db5d185d70b385 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/cli_tests.py @@ -0,0 +1,636 @@ +#!/usr/bin/env python + +import io +import logging +import unittest +from unittest import mock + +from click.testing import CliRunner + +from mkdocs import __main__ as cli + + +class CLITests(unittest.TestCase): + def setUp(self): + self.runner = CliRunner() + + @mock.patch('mkdocs.commands.serve.serve', autospec=True) + def test_serve_default(self, mock_serve): + result = self.runner.invoke(cli.cli, ["serve"], catch_exceptions=False) + + self.assertEqual(result.exit_code, 0) + mock_serve.assert_called_once_with( + dev_addr=None, + livereload=True, + build_type=None, + config_file=None, + strict=None, + theme=None, + use_directory_urls=None, + watch_theme=False, + watch=(), + ) + + @mock.patch('mkdocs.commands.serve.serve', autospec=True) + def test_serve_config_file(self, mock_serve): + result = self.runner.invoke( + cli.cli, ["serve", "--config-file", "mkdocs.yml"], catch_exceptions=False + ) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_serve.call_count, 1) + args, kwargs = mock_serve.call_args + self.assertTrue('config_file' in kwargs) + self.assertIsInstance(kwargs['config_file'], io.BufferedReader) + self.assertEqual(kwargs['config_file'].name, 'mkdocs.yml') + + @mock.patch('mkdocs.commands.serve.serve', autospec=True) + def test_serve_dev_addr(self, mock_serve): + result = self.runner.invoke( + cli.cli, ["serve", '--dev-addr', '0.0.0.0:80'], catch_exceptions=False + ) + + self.assertEqual(result.exit_code, 0) + mock_serve.assert_called_once_with( + dev_addr='0.0.0.0:80', + livereload=True, + build_type=None, + config_file=None, + strict=None, + theme=None, + use_directory_urls=None, + watch_theme=False, + watch=(), + ) + + @mock.patch('mkdocs.commands.serve.serve', autospec=True) + def test_serve_strict(self, mock_serve): + result = self.runner.invoke(cli.cli, ["serve", '--strict'], catch_exceptions=False) + + self.assertEqual(result.exit_code, 0) + mock_serve.assert_called_once_with( + dev_addr=None, + livereload=True, + build_type=None, + config_file=None, + strict=True, + theme=None, + use_directory_urls=None, + watch_theme=False, + watch=(), + ) + + @mock.patch('mkdocs.commands.serve.serve', autospec=True) + def test_serve_theme(self, mock_serve): + result = self.runner.invoke( + cli.cli, ["serve", '--theme', 'readthedocs'], catch_exceptions=False + ) + + self.assertEqual(result.exit_code, 0) + mock_serve.assert_called_once_with( + dev_addr=None, + livereload=True, + build_type=None, + config_file=None, + strict=None, + theme='readthedocs', + use_directory_urls=None, + watch_theme=False, + watch=(), + ) + + @mock.patch('mkdocs.commands.serve.serve', autospec=True) + def test_serve_use_directory_urls(self, mock_serve): + result = self.runner.invoke( + cli.cli, ["serve", '--use-directory-urls'], catch_exceptions=False + ) + + self.assertEqual(result.exit_code, 0) + mock_serve.assert_called_once_with( + dev_addr=None, + livereload=True, + build_type=None, + config_file=None, + strict=None, + theme=None, + use_directory_urls=True, + watch_theme=False, + watch=(), + ) + + @mock.patch('mkdocs.commands.serve.serve', autospec=True) + def test_serve_no_directory_urls(self, mock_serve): + result = self.runner.invoke( + cli.cli, ["serve", '--no-directory-urls'], catch_exceptions=False + ) + + self.assertEqual(result.exit_code, 0) + mock_serve.assert_called_once_with( + dev_addr=None, + livereload=True, + build_type=None, + config_file=None, + strict=None, + theme=None, + use_directory_urls=False, + watch_theme=False, + watch=(), + ) + + @mock.patch('mkdocs.commands.serve.serve', autospec=True) + def test_serve_livereload(self, mock_serve): + result = self.runner.invoke(cli.cli, ["serve", '--livereload'], catch_exceptions=False) + + self.assertEqual(result.exit_code, 0) + mock_serve.assert_called_once_with( + dev_addr=None, + livereload=True, + build_type=None, + config_file=None, + strict=None, + theme=None, + use_directory_urls=None, + watch_theme=False, + watch=(), + ) + + @mock.patch('mkdocs.commands.serve.serve', autospec=True) + def test_serve_no_livereload(self, mock_serve): + result = self.runner.invoke(cli.cli, ["serve", '--no-livereload'], catch_exceptions=False) + + self.assertEqual(result.exit_code, 0) + mock_serve.assert_called_once_with( + dev_addr=None, + livereload=False, + build_type=None, + config_file=None, + strict=None, + theme=None, + use_directory_urls=None, + watch_theme=False, + watch=(), + ) + + @mock.patch('mkdocs.commands.serve.serve', autospec=True) + def test_serve_dirtyreload(self, mock_serve): + result = self.runner.invoke(cli.cli, ["serve", '--dirty'], catch_exceptions=False) + + self.assertEqual(result.exit_code, 0) + mock_serve.assert_called_once_with( + dev_addr=None, + livereload=True, + build_type='dirty', + config_file=None, + strict=None, + theme=None, + use_directory_urls=None, + watch_theme=False, + watch=(), + ) + + @mock.patch('mkdocs.commands.serve.serve', autospec=True) + def test_serve_watch_theme(self, mock_serve): + result = self.runner.invoke(cli.cli, ["serve", '--watch-theme'], catch_exceptions=False) + + self.assertEqual(result.exit_code, 0) + mock_serve.assert_called_once_with( + dev_addr=None, + livereload=True, + build_type=None, + config_file=None, + strict=None, + theme=None, + use_directory_urls=None, + watch_theme=True, + watch=(), + ) + + @mock.patch('mkdocs.config.load_config', autospec=True) + @mock.patch('mkdocs.commands.build.build', autospec=True) + def test_build_defaults(self, mock_build, mock_load_config): + result = self.runner.invoke(cli.cli, ['build'], catch_exceptions=False) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_build.call_count, 1) + args, kwargs = mock_build.call_args + self.assertTrue('dirty' in kwargs) + self.assertFalse(kwargs['dirty']) + mock_load_config.assert_called_once_with( + config_file=None, + strict=None, + theme=None, + use_directory_urls=None, + site_dir=None, + ) + handler = logging._handlers.get('MkDocsStreamHandler') + self.assertEqual(handler.level, logging.INFO) + + @mock.patch('mkdocs.config.load_config', autospec=True) + @mock.patch('mkdocs.commands.build.build', autospec=True) + def test_build_clean(self, mock_build, mock_load_config): + result = self.runner.invoke(cli.cli, ['build', '--clean'], catch_exceptions=False) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_build.call_count, 1) + args, kwargs = mock_build.call_args + self.assertTrue('dirty' in kwargs) + self.assertFalse(kwargs['dirty']) + + @mock.patch('mkdocs.config.load_config', autospec=True) + @mock.patch('mkdocs.commands.build.build', autospec=True) + def test_build_dirty(self, mock_build, mock_load_config): + result = self.runner.invoke(cli.cli, ['build', '--dirty'], catch_exceptions=False) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_build.call_count, 1) + args, kwargs = mock_build.call_args + self.assertTrue('dirty' in kwargs) + self.assertTrue(kwargs['dirty']) + + @mock.patch('mkdocs.config.load_config', autospec=True) + @mock.patch('mkdocs.commands.build.build', autospec=True) + def test_build_config_file(self, mock_build, mock_load_config): + result = self.runner.invoke( + cli.cli, ['build', '--config-file', 'mkdocs.yml'], catch_exceptions=False + ) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_build.call_count, 1) + self.assertEqual(mock_load_config.call_count, 1) + args, kwargs = mock_load_config.call_args + self.assertTrue('config_file' in kwargs) + self.assertIsInstance(kwargs['config_file'], io.BufferedReader) + self.assertEqual(kwargs['config_file'].name, 'mkdocs.yml') + + @mock.patch('mkdocs.config.load_config', autospec=True) + @mock.patch('mkdocs.commands.build.build', autospec=True) + def test_build_strict(self, mock_build, mock_load_config): + result = self.runner.invoke(cli.cli, ['build', '--strict'], catch_exceptions=False) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_build.call_count, 1) + mock_load_config.assert_called_once_with( + config_file=None, + strict=True, + theme=None, + use_directory_urls=None, + site_dir=None, + ) + + @mock.patch('mkdocs.config.load_config', autospec=True) + @mock.patch('mkdocs.commands.build.build', autospec=True) + def test_build_theme(self, mock_build, mock_load_config): + result = self.runner.invoke( + cli.cli, ['build', '--theme', 'readthedocs'], catch_exceptions=False + ) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_build.call_count, 1) + mock_load_config.assert_called_once_with( + config_file=None, + strict=None, + theme='readthedocs', + use_directory_urls=None, + site_dir=None, + ) + + @mock.patch('mkdocs.config.load_config', autospec=True) + @mock.patch('mkdocs.commands.build.build', autospec=True) + def test_build_use_directory_urls(self, mock_build, mock_load_config): + result = self.runner.invoke( + cli.cli, ['build', '--use-directory-urls'], catch_exceptions=False + ) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_build.call_count, 1) + mock_load_config.assert_called_once_with( + config_file=None, + strict=None, + theme=None, + use_directory_urls=True, + site_dir=None, + ) + + @mock.patch('mkdocs.config.load_config', autospec=True) + @mock.patch('mkdocs.commands.build.build', autospec=True) + def test_build_no_directory_urls(self, mock_build, mock_load_config): + result = self.runner.invoke( + cli.cli, ['build', '--no-directory-urls'], catch_exceptions=False + ) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_build.call_count, 1) + mock_load_config.assert_called_once_with( + config_file=None, + strict=None, + theme=None, + use_directory_urls=False, + site_dir=None, + ) + + @mock.patch('mkdocs.config.load_config', autospec=True) + @mock.patch('mkdocs.commands.build.build', autospec=True) + def test_build_site_dir(self, mock_build, mock_load_config): + result = self.runner.invoke( + cli.cli, ['build', '--site-dir', 'custom'], catch_exceptions=False + ) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_build.call_count, 1) + mock_load_config.assert_called_once_with( + config_file=None, + strict=None, + theme=None, + use_directory_urls=None, + site_dir='custom', + ) + + @mock.patch('mkdocs.config.load_config', autospec=True) + @mock.patch('mkdocs.commands.build.build', autospec=True) + def test_build_verbose(self, mock_build, mock_load_config): + result = self.runner.invoke(cli.cli, ['build', '--verbose'], catch_exceptions=False) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_build.call_count, 1) + handler = logging._handlers.get('MkDocsStreamHandler') + self.assertEqual(handler.level, logging.DEBUG) + + @mock.patch('mkdocs.config.load_config', autospec=True) + @mock.patch('mkdocs.commands.build.build', autospec=True) + def test_build_quiet(self, mock_build, mock_load_config): + result = self.runner.invoke(cli.cli, ['build', '--quiet'], catch_exceptions=False) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_build.call_count, 1) + handler = logging._handlers.get('MkDocsStreamHandler') + self.assertEqual(handler.level, logging.ERROR) + + @mock.patch('mkdocs.commands.new.new', autospec=True) + def test_new(self, mock_new): + result = self.runner.invoke(cli.cli, ["new", "project"], catch_exceptions=False) + + self.assertEqual(result.exit_code, 0) + mock_new.assert_called_once_with('project') + + @mock.patch('mkdocs.config.load_config', autospec=True) + @mock.patch('mkdocs.commands.build.build', autospec=True) + @mock.patch('mkdocs.commands.gh_deploy.gh_deploy', autospec=True) + def test_gh_deploy_defaults(self, mock_gh_deploy, mock_build, mock_load_config): + result = self.runner.invoke(cli.cli, ['gh-deploy'], catch_exceptions=False) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_gh_deploy.call_count, 1) + g_args, g_kwargs = mock_gh_deploy.call_args + self.assertTrue('message' in g_kwargs) + self.assertEqual(g_kwargs['message'], None) + self.assertTrue('force' in g_kwargs) + self.assertEqual(g_kwargs['force'], False) + self.assertTrue('ignore_version' in g_kwargs) + self.assertEqual(g_kwargs['ignore_version'], False) + self.assertEqual(mock_build.call_count, 1) + b_args, b_kwargs = mock_build.call_args + self.assertTrue('dirty' in b_kwargs) + self.assertFalse(b_kwargs['dirty']) + mock_load_config.assert_called_once_with( + remote_branch=None, + remote_name=None, + config_file=None, + strict=None, + theme=None, + use_directory_urls=None, + site_dir=None, + ) + + @mock.patch('mkdocs.config.load_config', autospec=True) + @mock.patch('mkdocs.commands.build.build', autospec=True) + @mock.patch('mkdocs.commands.gh_deploy.gh_deploy', autospec=True) + def test_gh_deploy_clean(self, mock_gh_deploy, mock_build, mock_load_config): + result = self.runner.invoke(cli.cli, ['gh-deploy', '--clean'], catch_exceptions=False) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_gh_deploy.call_count, 1) + self.assertEqual(mock_build.call_count, 1) + args, kwargs = mock_build.call_args + self.assertTrue('dirty' in kwargs) + self.assertFalse(kwargs['dirty']) + + @mock.patch('mkdocs.config.load_config', autospec=True) + @mock.patch('mkdocs.commands.build.build', autospec=True) + @mock.patch('mkdocs.commands.gh_deploy.gh_deploy', autospec=True) + def test_gh_deploy_dirty(self, mock_gh_deploy, mock_build, mock_load_config): + result = self.runner.invoke(cli.cli, ['gh-deploy', '--dirty'], catch_exceptions=False) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_gh_deploy.call_count, 1) + self.assertEqual(mock_build.call_count, 1) + args, kwargs = mock_build.call_args + self.assertTrue('dirty' in kwargs) + self.assertTrue(kwargs['dirty']) + + @mock.patch('mkdocs.config.load_config', autospec=True) + @mock.patch('mkdocs.commands.build.build', autospec=True) + @mock.patch('mkdocs.commands.gh_deploy.gh_deploy', autospec=True) + def test_gh_deploy_config_file(self, mock_gh_deploy, mock_build, mock_load_config): + result = self.runner.invoke( + cli.cli, ['gh-deploy', '--config-file', 'mkdocs.yml'], catch_exceptions=False + ) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_gh_deploy.call_count, 1) + self.assertEqual(mock_build.call_count, 1) + self.assertEqual(mock_load_config.call_count, 1) + args, kwargs = mock_load_config.call_args + self.assertTrue('config_file' in kwargs) + self.assertIsInstance(kwargs['config_file'], io.BufferedReader) + self.assertEqual(kwargs['config_file'].name, 'mkdocs.yml') + + @mock.patch('mkdocs.config.load_config', autospec=True) + @mock.patch('mkdocs.commands.build.build', autospec=True) + @mock.patch('mkdocs.commands.gh_deploy.gh_deploy', autospec=True) + def test_gh_deploy_message(self, mock_gh_deploy, mock_build, mock_load_config): + result = self.runner.invoke( + cli.cli, ['gh-deploy', '--message', 'A commit message'], catch_exceptions=False + ) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_gh_deploy.call_count, 1) + g_args, g_kwargs = mock_gh_deploy.call_args + self.assertTrue('message' in g_kwargs) + self.assertEqual(g_kwargs['message'], 'A commit message') + self.assertEqual(mock_build.call_count, 1) + self.assertEqual(mock_load_config.call_count, 1) + + @mock.patch('mkdocs.config.load_config', autospec=True) + @mock.patch('mkdocs.commands.build.build', autospec=True) + @mock.patch('mkdocs.commands.gh_deploy.gh_deploy', autospec=True) + def test_gh_deploy_remote_branch(self, mock_gh_deploy, mock_build, mock_load_config): + result = self.runner.invoke( + cli.cli, ['gh-deploy', '--remote-branch', 'foo'], catch_exceptions=False + ) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_gh_deploy.call_count, 1) + self.assertEqual(mock_build.call_count, 1) + mock_load_config.assert_called_once_with( + remote_branch='foo', + remote_name=None, + config_file=None, + strict=None, + theme=None, + use_directory_urls=None, + site_dir=None, + ) + + @mock.patch('mkdocs.config.load_config', autospec=True) + @mock.patch('mkdocs.commands.build.build', autospec=True) + @mock.patch('mkdocs.commands.gh_deploy.gh_deploy', autospec=True) + def test_gh_deploy_remote_name(self, mock_gh_deploy, mock_build, mock_load_config): + result = self.runner.invoke( + cli.cli, ['gh-deploy', '--remote-name', 'foo'], catch_exceptions=False + ) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_gh_deploy.call_count, 1) + self.assertEqual(mock_build.call_count, 1) + mock_load_config.assert_called_once_with( + remote_branch=None, + remote_name='foo', + config_file=None, + strict=None, + theme=None, + use_directory_urls=None, + site_dir=None, + ) + + @mock.patch('mkdocs.config.load_config', autospec=True) + @mock.patch('mkdocs.commands.build.build', autospec=True) + @mock.patch('mkdocs.commands.gh_deploy.gh_deploy', autospec=True) + def test_gh_deploy_force(self, mock_gh_deploy, mock_build, mock_load_config): + result = self.runner.invoke(cli.cli, ['gh-deploy', '--force'], catch_exceptions=False) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_gh_deploy.call_count, 1) + g_args, g_kwargs = mock_gh_deploy.call_args + self.assertTrue('force' in g_kwargs) + self.assertEqual(g_kwargs['force'], True) + self.assertEqual(mock_build.call_count, 1) + self.assertEqual(mock_load_config.call_count, 1) + + @mock.patch('mkdocs.config.load_config', autospec=True) + @mock.patch('mkdocs.commands.build.build', autospec=True) + @mock.patch('mkdocs.commands.gh_deploy.gh_deploy', autospec=True) + def test_gh_deploy_ignore_version(self, mock_gh_deploy, mock_build, mock_load_config): + result = self.runner.invoke( + cli.cli, ['gh-deploy', '--ignore-version'], catch_exceptions=False + ) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_gh_deploy.call_count, 1) + g_args, g_kwargs = mock_gh_deploy.call_args + self.assertTrue('ignore_version' in g_kwargs) + self.assertEqual(g_kwargs['ignore_version'], True) + self.assertEqual(mock_build.call_count, 1) + self.assertEqual(mock_load_config.call_count, 1) + + @mock.patch('mkdocs.config.load_config', autospec=True) + @mock.patch('mkdocs.commands.build.build', autospec=True) + @mock.patch('mkdocs.commands.gh_deploy.gh_deploy', autospec=True) + def test_gh_deploy_strict(self, mock_gh_deploy, mock_build, mock_load_config): + result = self.runner.invoke(cli.cli, ['gh-deploy', '--strict'], catch_exceptions=False) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_gh_deploy.call_count, 1) + self.assertEqual(mock_build.call_count, 1) + mock_load_config.assert_called_once_with( + remote_branch=None, + remote_name=None, + config_file=None, + strict=True, + theme=None, + use_directory_urls=None, + site_dir=None, + ) + + @mock.patch('mkdocs.config.load_config', autospec=True) + @mock.patch('mkdocs.commands.build.build', autospec=True) + @mock.patch('mkdocs.commands.gh_deploy.gh_deploy', autospec=True) + def test_gh_deploy_theme(self, mock_gh_deploy, mock_build, mock_load_config): + result = self.runner.invoke( + cli.cli, ['gh-deploy', '--theme', 'readthedocs'], catch_exceptions=False + ) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_gh_deploy.call_count, 1) + self.assertEqual(mock_build.call_count, 1) + mock_load_config.assert_called_once_with( + remote_branch=None, + remote_name=None, + config_file=None, + strict=None, + theme='readthedocs', + use_directory_urls=None, + site_dir=None, + ) + + @mock.patch('mkdocs.config.load_config', autospec=True) + @mock.patch('mkdocs.commands.build.build', autospec=True) + @mock.patch('mkdocs.commands.gh_deploy.gh_deploy', autospec=True) + def test_gh_deploy_use_directory_urls(self, mock_gh_deploy, mock_build, mock_load_config): + result = self.runner.invoke( + cli.cli, ['gh-deploy', '--use-directory-urls'], catch_exceptions=False + ) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_gh_deploy.call_count, 1) + self.assertEqual(mock_build.call_count, 1) + mock_load_config.assert_called_once_with( + remote_branch=None, + remote_name=None, + config_file=None, + strict=None, + theme=None, + use_directory_urls=True, + site_dir=None, + ) + + @mock.patch('mkdocs.config.load_config', autospec=True) + @mock.patch('mkdocs.commands.build.build', autospec=True) + @mock.patch('mkdocs.commands.gh_deploy.gh_deploy', autospec=True) + def test_gh_deploy_no_directory_urls(self, mock_gh_deploy, mock_build, mock_load_config): + result = self.runner.invoke( + cli.cli, ['gh-deploy', '--no-directory-urls'], catch_exceptions=False + ) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_gh_deploy.call_count, 1) + self.assertEqual(mock_build.call_count, 1) + mock_load_config.assert_called_once_with( + remote_branch=None, + remote_name=None, + config_file=None, + strict=None, + theme=None, + use_directory_urls=False, + site_dir=None, + ) + + @mock.patch('mkdocs.config.load_config', autospec=True) + @mock.patch('mkdocs.commands.build.build', autospec=True) + @mock.patch('mkdocs.commands.gh_deploy.gh_deploy', autospec=True) + def test_gh_deploy_site_dir(self, mock_gh_deploy, mock_build, mock_load_config): + result = self.runner.invoke( + cli.cli, ['gh-deploy', '--site-dir', 'custom'], catch_exceptions=False + ) + + self.assertEqual(result.exit_code, 0) + self.assertEqual(mock_gh_deploy.call_count, 1) + self.assertEqual(mock_build.call_count, 1) + mock_load_config.assert_called_once_with( + remote_branch=None, + remote_name=None, + config_file=None, + strict=None, + theme=None, + use_directory_urls=None, + site_dir='custom', + ) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/config/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/config/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/config/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/config/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1f279dccac676b8f5f76fd292730e430d1478853 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/config/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/config/__pycache__/base_tests.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/config/__pycache__/base_tests.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de0543739279e55a7af24ecc784e07ae7a2c47c7 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/config/__pycache__/base_tests.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/config/__pycache__/config_options_legacy_tests.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/config/__pycache__/config_options_legacy_tests.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..18e3f607b54db1373140da50b445e7481beb2d42 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/config/__pycache__/config_options_legacy_tests.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f08ec7e2dd44233c259a71d812a0f8975b15916bea5d7e82867c266d79c9551f +size 103677 diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/config/__pycache__/config_options_tests.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/config/__pycache__/config_options_tests.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1996a1afa75c1195d593fcbba6e43ecc090d2a4e --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/config/__pycache__/config_options_tests.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cff20afb76356db3e9e32de3df76d7609b2b5cedda7d4661c85959e57627ac85 +size 153971 diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/config/__pycache__/config_tests.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/config/__pycache__/config_tests.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c5a4724d62fa76ddd0d1bda0176516b8bcde352a Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/config/__pycache__/config_tests.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/config/base_tests.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/config/base_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..2590b718581d42e6c86ed5a33f4ab7f197c62390 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/config/base_tests.py @@ -0,0 +1,284 @@ +import os +import unittest + +from mkdocs import exceptions +from mkdocs.config import base +from mkdocs.config import config_options as c +from mkdocs.config import defaults +from mkdocs.config.base import ValidationError +from mkdocs.tests.base import change_dir, tempdir + + +class ConfigBaseTests(unittest.TestCase): + def test_unrecognised_keys(self): + conf = defaults.MkDocsConfig() + conf.load_dict( + { + 'not_a_valid_config_option': "test", + } + ) + + failed, warnings = conf.validate() + + self.assertEqual( + warnings, + [ + ( + 'not_a_valid_config_option', + 'Unrecognised configuration name: not_a_valid_config_option', + ) + ], + ) + + def test_missing_required(self): + conf = defaults.MkDocsConfig() + + errors, warnings = conf.validate() + + self.assertEqual( + errors, [('site_name', ValidationError('Required configuration not provided.'))] + ) + self.assertEqual(warnings, []) + + @tempdir() + def test_load_from_file(self, temp_dir): + """ + Users can explicitly set the config file using the '--config' option. + Allows users to specify a config other than the default `mkdocs.yml`. + """ + with open(os.path.join(temp_dir, 'mkdocs.yml'), 'w') as config_file: + config_file.write("site_name: MkDocs Test\n") + os.mkdir(os.path.join(temp_dir, 'docs')) + + cfg = base.load_config(config_file=config_file.name) + self.assertTrue(isinstance(cfg, defaults.MkDocsConfig)) + self.assertEqual(cfg.site_name, 'MkDocs Test') + + @tempdir() + def test_load_default_file(self, temp_dir): + """ + test that `mkdocs.yml` will be loaded when '--config' is not set. + """ + with open(os.path.join(temp_dir, 'mkdocs.yml'), 'w') as config_file: + config_file.write("site_name: MkDocs Test\n") + os.mkdir(os.path.join(temp_dir, 'docs')) + with change_dir(temp_dir): + cfg = base.load_config(config_file=None) + self.assertTrue(isinstance(cfg, defaults.MkDocsConfig)) + self.assertEqual(cfg.site_name, 'MkDocs Test') + + @tempdir + def test_load_default_file_with_yaml(self, temp_dir): + """ + test that `mkdocs.yml` will be loaded when '--config' is not set. + """ + with open(os.path.join(temp_dir, 'mkdocs.yaml'), 'w') as config_file: + config_file.write("site_name: MkDocs Test\n") + os.mkdir(os.path.join(temp_dir, 'docs')) + with change_dir(temp_dir): + cfg = base.load_config(config_file=None) + self.assertTrue(isinstance(cfg, defaults.MkDocsConfig)) + self.assertEqual(cfg.site_name, 'MkDocs Test') + + @tempdir() + def test_load_default_file_prefer_yml(self, temp_dir): + """ + test that `mkdocs.yml` will be loaded when '--config' is not set. + """ + with open(os.path.join(temp_dir, 'mkdocs.yml'), 'w') as config_file1: + config_file1.write("site_name: MkDocs Test1\n") + with open(os.path.join(temp_dir, 'mkdocs.yaml'), 'w') as config_file2: + config_file2.write("site_name: MkDocs Test2\n") + + os.mkdir(os.path.join(temp_dir, 'docs')) + with change_dir(temp_dir): + cfg = base.load_config(config_file=None) + self.assertTrue(isinstance(cfg, defaults.MkDocsConfig)) + self.assertEqual(cfg.site_name, 'MkDocs Test1') + + def test_load_from_missing_file(self): + with self.assertRaisesRegex( + exceptions.ConfigurationError, "Config file 'missing_file.yml' does not exist." + ): + base.load_config(config_file='missing_file.yml') + + @tempdir() + def test_load_from_open_file(self, temp_path): + """ + `load_config` can accept an open file descriptor. + """ + config_fname = os.path.join(temp_path, 'mkdocs.yml') + config_file = open(config_fname, 'w+') + config_file.write("site_name: MkDocs Test\n") + config_file.flush() + os.mkdir(os.path.join(temp_path, 'docs')) + + cfg = base.load_config(config_file=config_file) + self.assertTrue(isinstance(cfg, defaults.MkDocsConfig)) + self.assertEqual(cfg.site_name, 'MkDocs Test') + # load_config will always close the file + self.assertTrue(config_file.closed) + + @tempdir() + def test_load_from_closed_file(self, temp_dir): + """ + The `serve` command with auto-reload may pass in a closed file descriptor. + Ensure `load_config` reloads the closed file. + """ + with open(os.path.join(temp_dir, 'mkdocs.yml'), 'w') as config_file: + config_file.write("site_name: MkDocs Test\n") + os.mkdir(os.path.join(temp_dir, 'docs')) + + cfg = base.load_config(config_file=config_file) + self.assertTrue(isinstance(cfg, defaults.MkDocsConfig)) + self.assertEqual(cfg.site_name, 'MkDocs Test') + + @tempdir + def test_load_missing_required(self, temp_dir): + """ + `site_name` is a required setting. + """ + with open(os.path.join(temp_dir, 'mkdocs.yml'), 'w') as config_file: + config_file.write("site_dir: output\nsite_url: https://www.mkdocs.org\n") + os.mkdir(os.path.join(temp_dir, 'docs')) + + with self.assertLogs('mkdocs') as cm: + with self.assertRaises(exceptions.Abort): + base.load_config(config_file=config_file.name) + self.assertEqual( + '\n'.join(cm.output), + "ERROR:mkdocs.config:Config value 'site_name': Required configuration not provided.", + ) + + def test_pre_validation_error(self): + class InvalidConfigOption(c.BaseConfigOption): + def pre_validation(self, config, key_name): + raise ValidationError('pre_validation error') + + conf = base.Config(schema=(('invalid_option', InvalidConfigOption()),)) + + errors, warnings = conf.validate() + + self.assertEqual(errors, [('invalid_option', ValidationError('pre_validation error'))]) + self.assertEqual(warnings, []) + + def test_run_validation_error(self): + class InvalidConfigOption(c.BaseConfigOption): + def run_validation(self, value): + raise ValidationError('run_validation error') + + conf = base.Config(schema=(('invalid_option', InvalidConfigOption()),)) + + errors, warnings = conf.validate() + + self.assertEqual(errors, [('invalid_option', ValidationError('run_validation error'))]) + self.assertEqual(warnings, []) + + def test_post_validation_error(self): + class InvalidConfigOption(c.BaseConfigOption): + def post_validation(self, config, key_name): + raise ValidationError('post_validation error') + + conf = base.Config(schema=(('invalid_option', InvalidConfigOption()),)) + + errors, warnings = conf.validate() + + self.assertEqual(errors, [('invalid_option', ValidationError('post_validation error'))]) + self.assertEqual(warnings, []) + + def test_pre_and_run_validation_errors(self): + """A pre_validation error does not stop run_validation from running.""" + + class InvalidConfigOption(c.BaseConfigOption): + def pre_validation(self, config, key_name): + raise ValidationError('pre_validation error') + + def run_validation(self, value): + raise ValidationError('run_validation error') + + conf = base.Config(schema=(('invalid_option', InvalidConfigOption()),)) + + errors, warnings = conf.validate() + + self.assertEqual( + errors, + [ + ('invalid_option', ValidationError('pre_validation error')), + ('invalid_option', ValidationError('run_validation error')), + ], + ) + self.assertEqual(warnings, []) + + def test_run_and_post_validation_errors(self): + """A run_validation error stops post_validation from running.""" + + class InvalidConfigOption(c.BaseConfigOption): + def run_validation(self, value): + raise ValidationError('run_validation error') + + def post_validation(self, config, key_name): + raise ValidationError('post_validation error') + + conf = base.Config(schema=(('invalid_option', InvalidConfigOption()),)) + + errors, warnings = conf.validate() + + self.assertEqual(errors, [('invalid_option', ValidationError('run_validation error'))]) + self.assertEqual(warnings, []) + + def test_validation_warnings(self): + class InvalidConfigOption(c.BaseConfigOption): + def pre_validation(self, config, key_name): + self.warnings.append('pre_validation warning') + + def run_validation(self, value): + self.warnings.append('run_validation warning') + + def post_validation(self, config, key_name): + self.warnings.append('post_validation warning') + + conf = base.Config(schema=(('invalid_option', InvalidConfigOption()),)) + + errors, warnings = conf.validate() + + self.assertEqual(errors, []) + self.assertEqual( + warnings, + [ + ('invalid_option', 'pre_validation warning'), + ('invalid_option', 'run_validation warning'), + ('invalid_option', 'post_validation warning'), + ], + ) + + @tempdir() + def test_load_from_file_with_relative_paths(self, config_dir): + """ + When explicitly setting a config file, paths should be relative to the + config file, not the working directory. + """ + config_fname = os.path.join(config_dir, 'mkdocs.yml') + with open(config_fname, 'w') as config_file: + config_file.write("docs_dir: src\nsite_name: MkDocs Test\n") + docs_dir = os.path.join(config_dir, 'src') + os.mkdir(docs_dir) + + cfg = base.load_config(config_file=config_file) + self.assertTrue(isinstance(cfg, defaults.MkDocsConfig)) + self.assertEqual(cfg.site_name, 'MkDocs Test') + self.assertEqual(cfg.docs_dir, docs_dir) + self.assertEqual(cfg.config_file_path, config_fname) + self.assertIsInstance(cfg.config_file_path, str) + + def test_get_schema(self): + class FooConfig: + z = c.URL() + aa = c.Type(int) + + self.assertEqual( + base.get_schema(FooConfig), + ( + ('z', FooConfig.z), + ('aa', FooConfig.aa), + ), + ) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/config/config_options_legacy_tests.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/config/config_options_legacy_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..0f76bf6320c90d107e789f658c5b5dde693de922 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/config/config_options_legacy_tests.py @@ -0,0 +1,1657 @@ +from __future__ import annotations + +import contextlib +import copy +import io +import os +import re +import sys +import textwrap +import unittest +from typing import Any +from unittest.mock import patch + +import mkdocs +from mkdocs.config import base +from mkdocs.config import config_options as c +from mkdocs.tests.base import tempdir +from mkdocs.utils import write_file, yaml_load + + +class UnexpectedError(Exception): + pass + + +class TestCase(unittest.TestCase): + @contextlib.contextmanager + def expect_error(self, **kwargs): + [(key, msg)] = kwargs.items() + with self.assertRaises(UnexpectedError) as cm: + yield + if isinstance(msg, re.Pattern): + self.assertRegex(str(cm.exception), f'^{key}="{msg.pattern}"$') + else: + self.assertEqual(f'{key}="{msg}"', str(cm.exception)) + + def get_config( + self, + schema: type, + cfg: dict[str, Any], + warnings: dict[str, str] = {}, + config_file_path=None, + ): + config = base.LegacyConfig(base.get_schema(schema), config_file_path=config_file_path) + config.load_dict(cfg) + actual_errors, actual_warnings = config.validate() + if actual_errors: + raise UnexpectedError(', '.join(f'{key}="{msg}"' for key, msg in actual_errors)) + self.assertEqual(warnings, dict(actual_warnings)) + return config + + +class OptionallyRequiredTest(TestCase): + def test_empty(self): + class Schema: + option = c.OptionallyRequired() + + conf = self.get_config(Schema, {'option': None}) + self.assertEqual(conf['option'], None) + + self.assertEqual(Schema.option.required, False) + + def test_required(self): + class Schema: + option = c.OptionallyRequired(required=True) + + with self.expect_error(option="Required configuration not provided."): + self.get_config(Schema, {'option': None}) + + self.assertEqual(Schema.option.required, True) + + def test_required_no_default(self): + class Schema: + option = c.OptionallyRequired(required=True) + + conf = self.get_config(Schema, {'option': 2}) + self.assertEqual(conf['option'], 2) + + def test_default(self): + class Schema: + option = c.OptionallyRequired(default=1) + + conf = self.get_config(Schema, {'option': None}) + self.assertEqual(conf['option'], 1) + + def test_replace_default(self): + class Schema: + option = c.OptionallyRequired(default=1) + + conf = self.get_config(Schema, {'option': 2}) + self.assertEqual(conf['option'], 2) + + +class TypeTest(TestCase): + def test_single_type(self): + class Schema: + option = c.Type(str) + + conf = self.get_config(Schema, {'option': "Testing"}) + self.assertEqual(conf['option'], "Testing") + + def test_multiple_types(self): + class Schema: + option = c.Type((list, tuple)) + + conf = self.get_config(Schema, {'option': [1, 2, 3]}) + self.assertEqual(conf['option'], [1, 2, 3]) + + conf = self.get_config(Schema, {'option': (1, 2, 3)}) + self.assertEqual(conf['option'], (1, 2, 3)) + + with self.expect_error( + option="Expected type: (, ) but received: " + ): + self.get_config(Schema, {'option': {'a': 1}}) + + def test_length(self): + class Schema: + option = c.Type(str, length=7) + + conf = self.get_config(Schema, {'option': "Testing"}) + self.assertEqual(conf['option'], "Testing") + + with self.expect_error( + option="Expected type: with length 7 but received: 'Testing Long' with length 12" + ): + self.get_config(Schema, {'option': "Testing Long"}) + + +class ChoiceTest(TestCase): + def test_required(self): + class Schema: + option = c.Choice(('python', 'node'), required=True) + + conf = self.get_config(Schema, {'option': 'python'}) + self.assertEqual(conf['option'], 'python') + + def test_optional(self): + class Schema: + option = c.Choice(('python', 'node')) + + conf = self.get_config(Schema, {'option': 'python'}) + self.assertEqual(conf['option'], 'python') + + conf = self.get_config(Schema, {}) + self.assertEqual(conf['option'], None) + + conf = self.get_config(Schema, {'option': None}) + self.assertEqual(conf['option'], None) + + def test_default(self): + class Schema: + option = c.Choice(('a', 'b', 'c'), default='b') + + conf = self.get_config(Schema, {}) + self.assertEqual(conf['option'], 'b') + + conf = self.get_config(Schema, {'option': None}) + self.assertEqual(conf['option'], 'b') + + with self.expect_error(option="Expected one of: ('a', 'b', 'c') but received: 'go'"): + self.get_config(Schema, {'option': 'go'}) + + def test_invalid_default(self): + with self.assertRaises(ValueError): + c.Choice(('a', 'b'), default='c') + with self.assertRaises(ValueError): + c.Choice(('a', 'b'), default='c', required=True) + + def test_invalid_choice(self): + class Schema: + option = c.Choice(('python', 'node')) + + with self.expect_error(option="Expected one of: ('python', 'node') but received: 'go'"): + self.get_config(Schema, {'option': 'go'}) + + def test_invalid_choices(self): + with self.assertRaises(ValueError): + c.Choice('') + with self.assertRaises(ValueError): + c.Choice([]) + with self.assertRaises(ValueError): + c.Choice(5) + + +class DeprecatedTest(TestCase): + def test_deprecated_option_simple(self): + class Schema: + d = c.Deprecated() + + self.get_config( + Schema, + {'d': 'value'}, + warnings=dict( + d="The configuration option 'd' has been deprecated and will be removed in a " + "future release." + ), + ) + + def test_deprecated_option_message(self): + class Schema: + d = c.Deprecated(message='custom message for {} key') + + self.get_config(Schema, {'d': 'value'}, warnings={'d': 'custom message for d key'}) + + def test_deprecated_option_with_type(self): + class Schema: + d = c.Deprecated(option_type=c.Type(str)) + + self.get_config( + Schema, + {'d': 'value'}, + warnings=dict( + d="The configuration option 'd' has been deprecated and will be removed in a " + "future release." + ), + ) + + def test_deprecated_option_with_invalid_type(self): + class Schema: + d = c.Deprecated(option_type=c.Type(list)) + + with self.expect_error(d="Expected type: but received: "): + self.get_config( + Schema, + {'d': 'value'}, + warnings=dict( + d="The configuration option 'd' has been deprecated and will be removed in a " + "future release." + ), + ) + + def test_removed_option(self): + class Schema: + d = c.Deprecated(removed=True, moved_to='foo') + + with self.expect_error( + d="The configuration option 'd' was removed from MkDocs. Use 'foo' instead.", + ): + self.get_config(Schema, {'d': 'value'}) + + def test_deprecated_option_with_type_undefined(self): + class Schema: + option = c.Deprecated(option_type=c.Type(str)) + + self.get_config(Schema, {'option': None}) + + def test_deprecated_option_move(self): + class Schema: + new = c.Type(str) + old = c.Deprecated(moved_to='new') + + conf = self.get_config( + Schema, + {'old': 'value'}, + warnings=dict( + old="The configuration option 'old' has been deprecated and will be removed in a " + "future release. Use 'new' instead." + ), + ) + self.assertEqual(conf, {'new': 'value', 'old': None}) + + def test_deprecated_option_move_complex(self): + class Schema: + foo = c.Type(dict) + old = c.Deprecated(moved_to='foo.bar') + + conf = self.get_config( + Schema, + {'old': 'value'}, + warnings=dict( + old="The configuration option 'old' has been deprecated and will be removed in a " + "future release. Use 'foo.bar' instead." + ), + ) + self.assertEqual(conf, {'foo': {'bar': 'value'}, 'old': None}) + + def test_deprecated_option_move_existing(self): + class Schema: + foo = c.Type(dict) + old = c.Deprecated(moved_to='foo.bar') + + conf = self.get_config( + Schema, + {'old': 'value', 'foo': {'existing': 'existing'}}, + warnings=dict( + old="The configuration option 'old' has been deprecated and will be removed in a " + "future release. Use 'foo.bar' instead." + ), + ) + self.assertEqual(conf, {'foo': {'existing': 'existing', 'bar': 'value'}, 'old': None}) + + def test_deprecated_option_move_invalid(self): + class Schema: + foo = c.Type(dict) + old = c.Deprecated(moved_to='foo.bar') + + with self.expect_error(foo="Expected type: but received: "): + self.get_config( + Schema, + {'old': 'value', 'foo': 'wrong type'}, + warnings=dict( + old="The configuration option 'old' has been deprecated and will be removed in a " + "future release. Use 'foo.bar' instead." + ), + ) + + +class IpAddressTest(TestCase): + class Schema: + option = c.IpAddress() + + def test_valid_address(self): + addr = '127.0.0.1:8000' + + conf = self.get_config(self.Schema, {'option': addr}) + self.assertEqual(str(conf['option']), addr) + self.assertEqual(conf['option'].host, '127.0.0.1') + self.assertEqual(conf['option'].port, 8000) + + def test_valid_IPv6_address(self): + addr = '::1:8000' + + conf = self.get_config(self.Schema, {'option': addr}) + self.assertEqual(str(conf['option']), addr) + self.assertEqual(conf['option'].host, '::1') + self.assertEqual(conf['option'].port, 8000) + + def test_valid_full_IPv6_address(self): + addr = '[2001:db8:85a3::8a2e:370:7334]:123' + + conf = self.get_config(self.Schema, {'option': addr}) + self.assertEqual(conf['option'].host, '2001:db8:85a3::8a2e:370:7334') + self.assertEqual(conf['option'].port, 123) + + def test_named_address(self): + addr = 'localhost:8000' + + conf = self.get_config(self.Schema, {'option': addr}) + self.assertEqual(str(conf['option']), addr) + self.assertEqual(conf['option'].host, 'localhost') + self.assertEqual(conf['option'].port, 8000) + + def test_default_address(self): + addr = '127.0.0.1:8000' + + class Schema: + option = c.IpAddress(default=addr) + + conf = self.get_config(Schema, {'option': None}) + self.assertEqual(str(conf['option']), addr) + self.assertEqual(conf['option'].host, '127.0.0.1') + self.assertEqual(conf['option'].port, 8000) + + @unittest.skipIf( + sys.version_info < (3, 9, 5), + "Leading zeros allowed in IP addresses before Python3.9.5", + ) + def test_invalid_leading_zeros(self): + with self.expect_error( + option="'127.000.000.001' does not appear to be an IPv4 or IPv6 address" + ): + self.get_config(self.Schema, {'option': '127.000.000.001:8000'}) + + def test_invalid_address_range(self): + with self.expect_error(option="'277.0.0.1' does not appear to be an IPv4 or IPv6 address"): + self.get_config(self.Schema, {'option': '277.0.0.1:8000'}) + + def test_invalid_address_format(self): + with self.expect_error(option="Must be a string of format 'IP:PORT'"): + self.get_config(self.Schema, {'option': '127.0.0.18000'}) + + def test_invalid_address_type(self): + with self.expect_error(option="Must be a string of format 'IP:PORT'"): + self.get_config(self.Schema, {'option': 123}) + + def test_invalid_address_port(self): + with self.expect_error(option="'foo' is not a valid port"): + self.get_config(self.Schema, {'option': '127.0.0.1:foo'}) + + def test_invalid_address_missing_port(self): + with self.expect_error(option="Must be a string of format 'IP:PORT'"): + self.get_config(self.Schema, {'option': '127.0.0.1'}) + + def test_unsupported_address(self): + class Schema: + dev_addr = c.IpAddress() + + self.get_config( + Schema, + {'dev_addr': '0.0.0.0:8000'}, + warnings=dict( + dev_addr="The use of the IP address '0.0.0.0' suggests a production " + "environment or the use of a proxy to connect to the MkDocs " + "server. However, the MkDocs' server is intended for local " + "development purposes only. Please use a third party " + "production-ready server instead." + ), + ) + + def test_unsupported_IPv6_address(self): + class Schema: + dev_addr = c.IpAddress() + + self.get_config( + Schema, + {'dev_addr': ':::8000'}, + warnings=dict( + dev_addr="The use of the IP address '::' suggests a production environment " + "or the use of a proxy to connect to the MkDocs server. However, " + "the MkDocs' server is intended for local development purposes " + "only. Please use a third party production-ready server instead." + ), + ) + + +class URLTest(TestCase): + def test_valid_url(self): + class Schema: + option = c.URL() + + conf = self.get_config(Schema, {'option': "https://mkdocs.org"}) + self.assertEqual(conf['option'], "https://mkdocs.org") + + conf = self.get_config(Schema, {'option': ""}) + self.assertEqual(conf['option'], "") + + def test_valid_url_is_dir(self): + class Schema: + option = c.URL(is_dir=True) + + conf = self.get_config(Schema, {'option': "http://mkdocs.org/"}) + self.assertEqual(conf['option'], "http://mkdocs.org/") + + conf = self.get_config(Schema, {'option': "https://mkdocs.org"}) + self.assertEqual(conf['option'], "https://mkdocs.org/") + + def test_optional(self): + class Schema: + option = c.URL(is_dir=True) + + conf = self.get_config(Schema, {'option': ''}) + self.assertEqual(conf['option'], '') + + conf = self.get_config(Schema, {'option': None}) + self.assertEqual(conf['option'], None) + + def test_invalid_url(self): + class Schema: + option = c.URL(required=True) + + with self.expect_error(option="Required configuration not provided."): + self.get_config(Schema, {'option': None}) + + for url in "www.mkdocs.org", "//mkdocs.org/test", "http:/mkdocs.org/", "/hello/": + with self.subTest(url=url): + with self.expect_error( + option="The URL isn't valid, it should include the http:// (scheme)" + ): + self.get_config(Schema, {'option': url}) + + def test_invalid_type(self): + class Schema: + option = c.URL() + + with self.expect_error(option="Expected a string, got "): + self.get_config(Schema, {'option': 1}) + + +class EditURITest(TestCase): + class Schema: + repo_url = c.URL() + repo_name = c.RepoName('repo_url') + edit_uri_template = c.EditURITemplate('edit_uri') + edit_uri = c.EditURI('repo_url') + + def test_repo_name_github(self): + conf = self.get_config( + self.Schema, + {'repo_url': "https://github.com/mkdocs/mkdocs"}, + ) + self.assertEqual(conf['repo_name'], "GitHub") + + def test_repo_name_bitbucket(self): + conf = self.get_config( + self.Schema, + {'repo_url': "https://bitbucket.org/gutworth/six/"}, + ) + self.assertEqual(conf['repo_name'], "Bitbucket") + + def test_repo_name_gitlab(self): + conf = self.get_config( + self.Schema, + {'repo_url': "https://gitlab.com/gitlab-org/gitlab-ce/"}, + ) + self.assertEqual(conf['repo_name'], "GitLab") + + def test_repo_name_custom(self): + conf = self.get_config( + self.Schema, + {'repo_url': "https://launchpad.net/python-tuskarclient"}, + ) + self.assertEqual(conf['repo_name'], "Launchpad") + + def test_edit_uri_github(self): + conf = self.get_config( + self.Schema, + {'repo_url': "https://github.com/mkdocs/mkdocs"}, + ) + self.assertEqual(conf['edit_uri'], 'edit/master/docs/') + self.assertEqual(conf['repo_url'], "https://github.com/mkdocs/mkdocs") + + def test_edit_uri_bitbucket(self): + conf = self.get_config( + self.Schema, + {'repo_url': "https://bitbucket.org/gutworth/six/"}, + ) + self.assertEqual(conf['edit_uri'], 'src/default/docs/') + self.assertEqual(conf['repo_url'], "https://bitbucket.org/gutworth/six/") + + def test_edit_uri_gitlab(self): + conf = self.get_config( + self.Schema, + {'repo_url': "https://gitlab.com/gitlab-org/gitlab-ce/"}, + ) + self.assertEqual(conf['edit_uri'], 'edit/master/docs/') + + def test_edit_uri_custom(self): + conf = self.get_config( + self.Schema, + {'repo_url': "https://launchpad.net/python-tuskarclient"}, + ) + self.assertEqual(conf['edit_uri'], None) + self.assertEqual(conf['repo_url'], "https://launchpad.net/python-tuskarclient") + + def test_repo_name_custom_and_empty_edit_uri(self): + conf = self.get_config( + self.Schema, + {'repo_url': "https://github.com/mkdocs/mkdocs", 'repo_name': 'mkdocs'}, + ) + self.assertEqual(conf['edit_uri'], 'edit/master/docs/') + + def test_edit_uri_template_ok(self): + conf = self.get_config( + self.Schema, + { + 'repo_url': "https://github.com/mkdocs/mkdocs", + 'edit_uri_template': 'edit/foo/docs/{path}', + }, + ) + self.assertEqual(conf['edit_uri_template'], 'edit/foo/docs/{path}') + + def test_edit_uri_template_errors(self): + with self.expect_error( + edit_uri_template=re.compile(r'.*[{}].*') # Complains about unclosed '{' or missing '}' + ): + self.get_config( + self.Schema, + { + 'repo_url': "https://github.com/mkdocs/mkdocs", + 'edit_uri_template': 'edit/master/{path', + }, + ) + + with self.expect_error(edit_uri_template=re.compile(r'.*\bz\b.*')): + self.get_config( + self.Schema, + { + 'repo_url': "https://github.com/mkdocs/mkdocs", + 'edit_uri_template': 'edit/master/{path!z}', + }, + ) + + with self.expect_error(edit_uri_template="Unknown template substitute: 'foo'"): + self.get_config( + self.Schema, + { + 'repo_url': "https://github.com/mkdocs/mkdocs", + 'edit_uri_template': 'edit/master/{foo}', + }, + ) + + def test_edit_uri_template_warning(self): + conf = self.get_config( + self.Schema, + { + 'repo_url': "https://github.com/mkdocs/mkdocs", + 'edit_uri': 'edit', + 'edit_uri_template': 'edit/master/{path}', + }, + warnings=dict( + edit_uri_template="The option 'edit_uri' has no effect when 'edit_uri_template' is set." + ), + ) + self.assertEqual(conf['edit_uri_template'], 'edit/master/{path}') + + +class ListOfItemsTest(TestCase): + def test_int_type(self): + class Schema: + option = c.ListOfItems(c.Type(int)) + + conf = self.get_config(Schema, {'option': [1, 2, 3]}) + self.assertEqual(conf['option'], [1, 2, 3]) + + with self.expect_error( + option="Expected type: but received: " + ): + conf = self.get_config(Schema, {'option': [1, None, 3]}) + + def test_combined_float_type(self): + class Schema: + option = c.ListOfItems(c.Type((int, float))) + + conf = self.get_config(Schema, {'option': [1.4, 2, 3]}) + self.assertEqual(conf['option'], [1.4, 2, 3]) + + with self.expect_error( + option="Expected type: (, ) but received: " + ): + self.get_config(Schema, {'option': ['a']}) + + def test_list_default(self): + class Schema: + option = c.ListOfItems(c.Type(int), default=[]) + + conf = self.get_config(Schema, {}) + self.assertEqual(conf['option'], []) + + conf = self.get_config(Schema, {'option': None}) + self.assertEqual(conf['option'], []) + + def test_none_without_default(self): + class Schema: + option = c.ListOfItems(c.Type(str)) + + with self.expect_error(option="Required configuration not provided."): + conf = self.get_config(Schema, {}) + + with self.expect_error(option="Required configuration not provided."): + conf = self.get_config(Schema, {'option': None}) + + conf = self.get_config(Schema, {'option': ['foo']}) + self.assertEqual(conf['option'], ['foo']) + + def test_string_not_a_list_of_strings(self): + class Schema: + option = c.ListOfItems(c.Type(str)) + + with self.expect_error(option="Expected a list of items, but a was given."): + self.get_config(Schema, {'option': 'foo'}) + + def test_post_validation_error(self): + class Schema: + option = c.ListOfItems(c.IpAddress()) + + with self.expect_error(option="'asdf' is not a valid port"): + self.get_config(Schema, {'option': ["localhost:8000", "1.2.3.4:asdf"]}) + + +class FilesystemObjectTest(TestCase): + def test_valid_dir(self): + for cls in c.Dir, c.FilesystemObject: + with self.subTest(cls): + d = os.path.dirname(__file__) + + class Schema: + option = cls(exists=True) + + conf = self.get_config(Schema, {'option': d}) + self.assertEqual(conf['option'], d) + + def test_valid_file(self): + for cls in c.File, c.FilesystemObject: + with self.subTest(cls): + f = __file__ + + class Schema: + option = cls(exists=True) + + conf = self.get_config(Schema, {'option': f}) + self.assertEqual(conf['option'], f) + + def test_missing_without_exists(self): + for cls in c.Dir, c.File, c.FilesystemObject: + with self.subTest(cls): + d = os.path.join("not", "a", "real", "path", "I", "hope") + + class Schema: + option = cls() + + conf = self.get_config(Schema, {'option': d}) + self.assertEqual(conf['option'], os.path.abspath(d)) + + def test_missing_but_required(self): + for cls in c.Dir, c.File, c.FilesystemObject: + with self.subTest(cls): + d = os.path.join("not", "a", "real", "path", "I", "hope") + + class Schema: + option = cls(exists=True) + + with self.expect_error(option=re.compile(r"The path '.+' isn't an existing .+")): + self.get_config(Schema, {'option': d}) + + def test_not_a_dir(self): + d = __file__ + + class Schema: + option = c.Dir(exists=True) + + with self.expect_error(option=re.compile(r"The path '.+' isn't an existing directory.")): + self.get_config(Schema, {'option': d}) + + def test_not_a_file(self): + d = os.path.dirname(__file__) + + class Schema: + option = c.File(exists=True) + + with self.expect_error(option=re.compile(r"The path '.+' isn't an existing file.")): + self.get_config(Schema, {'option': d}) + + def test_incorrect_type_error(self): + for cls in c.Dir, c.File, c.FilesystemObject: + with self.subTest(cls): + + class Schema: + option = cls() + + with self.expect_error( + option="Expected type: but received: " + ): + self.get_config(Schema, {'option': 1}) + with self.expect_error( + option="Expected type: but received: " + ): + self.get_config(Schema, {'option': []}) + + def test_with_unicode(self): + for cls in c.Dir, c.File, c.FilesystemObject: + with self.subTest(cls): + + class Schema: + dir = cls() + + conf = self.get_config(Schema, {'dir': 'юникод'}) + self.assertIsInstance(conf['dir'], str) + + def test_dir_bytes(self): + class Schema: + dir = c.Dir() + + with self.expect_error(dir="Expected type: but received: "): + self.get_config(Schema, {'dir': b'foo'}) + + def test_config_dir_prepended(self): + for cls in c.Dir, c.File, c.FilesystemObject: + with self.subTest(cls): + base_path = os.path.dirname(os.path.abspath(__file__)) + + class Schema: + dir = cls() + + conf = self.get_config( + Schema, + {'dir': 'foo'}, + config_file_path=os.path.join(base_path, 'mkdocs.yml'), + ) + self.assertEqual(conf['dir'], os.path.join(base_path, 'foo')) + + def test_site_dir_is_config_dir_fails(self): + class Schema: + dir = c.DocsDir() + + with self.expect_error( + dir="The 'dir' should not be the parent directory of the config file. " + "Use a child directory instead so that the 'dir' is a sibling of the config file." + ): + self.get_config( + Schema, + {'dir': '.'}, + config_file_path=os.path.join(os.path.abspath('.'), 'mkdocs.yml'), + ) + + +class ListOfPathsTest(TestCase): + def test_valid_path(self): + paths = [os.path.dirname(__file__)] + + class Schema: + option = c.ListOfPaths() + + self.get_config(Schema, {'option': paths}) + + def test_missing_path(self): + paths = [os.path.join("does", "not", "exist", "i", "hope")] + + class Schema: + option = c.ListOfPaths() + + with self.expect_error( + option=f"The path '{paths[0]}' isn't an existing file or directory." + ): + self.get_config(Schema, {'option': paths}) + + def test_non_path(self): + paths = [os.path.dirname(__file__), None] + + class Schema: + option = c.ListOfPaths() + + with self.expect_error( + option="Expected type: but received: " + ): + self.get_config(Schema, {'option': paths}) + + def test_empty_list(self): + class Schema: + option = c.ListOfPaths() + + conf = self.get_config(Schema, {'option': []}) + self.assertEqual(conf['option'], []) + + def test_non_list(self): + paths = os.path.dirname(__file__) + + class Schema: + option = c.ListOfPaths() + + with self.expect_error(option="Expected a list of items, but a was given."): + self.get_config(Schema, {'option': paths}) + + def test_file(self): + paths = [__file__] + + class Schema: + option = c.ListOfPaths() + + self.get_config(Schema, {'option': paths}) + + @tempdir() + def test_paths_localized_to_config(self, base_path): + with open(os.path.join(base_path, 'foo'), 'w') as f: + f.write('hi') + + class Schema: + watch = c.ListOfPaths() + + conf = self.get_config( + Schema, + {'watch': ['foo']}, + config_file_path=os.path.join(base_path, 'mkdocs.yml'), + ) + + self.assertEqual(conf['watch'], [os.path.join(base_path, 'foo')]) + + +class SiteDirTest(TestCase): + class Schema: + site_dir = c.SiteDir() + docs_dir = c.Dir() + + def test_doc_dir_in_site_dir(self): + j = os.path.join + # The parent dir is not the same on every system, so use the actual dir name + parent_dir = mkdocs.__file__.split(os.sep)[-3] + + test_configs = ( + {'docs_dir': j('site', 'docs'), 'site_dir': 'site'}, + {'docs_dir': 'docs', 'site_dir': '.'}, + {'docs_dir': '.', 'site_dir': '.'}, + {'docs_dir': 'docs', 'site_dir': ''}, + {'docs_dir': '', 'site_dir': ''}, + {'docs_dir': j('..', parent_dir, 'docs'), 'site_dir': 'docs'}, + {'docs_dir': 'docs', 'site_dir': '/'}, + ) + + for test_config in test_configs: + with self.subTest(test_config): + with self.expect_error( + site_dir=re.compile(r"The 'docs_dir' should not be within the 'site_dir'.*") + ): + self.get_config(self.Schema, test_config) + + def test_site_dir_in_docs_dir(self): + j = os.path.join + + test_configs = ( + {'docs_dir': 'docs', 'site_dir': j('docs', 'site')}, + {'docs_dir': '.', 'site_dir': 'site'}, + {'docs_dir': '', 'site_dir': 'site'}, + {'docs_dir': '/', 'site_dir': 'site'}, + ) + + for test_config in test_configs: + with self.subTest(test_config): + with self.expect_error( + site_dir=re.compile(r"The 'site_dir' should not be within the 'docs_dir'.*") + ): + self.get_config(self.Schema, test_config) + + def test_common_prefix(self): + """Legitimate settings with common prefixes should not fail validation.""" + + test_configs = ( + {'docs_dir': 'docs', 'site_dir': 'docs-site'}, + {'docs_dir': 'site-docs', 'site_dir': 'site'}, + ) + + for test_config in test_configs: + with self.subTest(test_config): + self.get_config(self.Schema, test_config) + + +class ThemeTest(TestCase): + def test_theme_as_string(self): + class Schema: + option = c.Theme() + + conf = self.get_config(Schema, {'option': "mkdocs"}) + self.assertEqual(conf['option'].name, 'mkdocs') + + def test_uninstalled_theme_as_string(self): + class Schema: + option = c.Theme() + + with self.expect_error( + option=re.compile( + r"Unrecognised theme name: 'mkdocs2'. The available installed themes are: .+" + ) + ): + self.get_config(Schema, {'option': "mkdocs2"}) + + def test_theme_default(self): + class Schema: + option = c.Theme(default='mkdocs') + + conf = self.get_config(Schema, {'option': None}) + self.assertEqual(conf['option'].name, 'mkdocs') + + def test_theme_as_simple_config(self): + config = { + 'name': 'mkdocs', + } + + class Schema: + option = c.Theme() + + conf = self.get_config(Schema, {'option': config}) + self.assertEqual(conf['option'].name, 'mkdocs') + + @tempdir() + def test_theme_as_complex_config(self, custom_dir): + config = { + 'name': 'mkdocs', + 'custom_dir': custom_dir, + 'static_templates': ['sitemap.html'], + 'show_sidebar': False, + } + + class Schema: + option = c.Theme() + + conf = self.get_config(Schema, {'option': config}) + self.assertEqual(conf['option'].name, 'mkdocs') + self.assertIn(custom_dir, conf['option'].dirs) + self.assertEqual( + conf['option'].static_templates, + {'404.html', 'sitemap.xml', 'sitemap.html'}, + ) + self.assertEqual(conf['option']['show_sidebar'], False) + + def test_theme_name_is_none(self): + config = { + 'name': None, + } + + class Schema: + option = c.Theme() + + with self.expect_error(option="At least one of 'name' or 'custom_dir' must be defined."): + self.get_config(Schema, {'option': config}) + + def test_theme_config_missing_name(self): + config = { + 'custom_dir': 'custom', + } + + class Schema: + option = c.Theme() + + with self.expect_error(option="No theme name set."): + self.get_config(Schema, {'option': config}) + + def test_uninstalled_theme_as_config(self): + config = { + 'name': 'mkdocs2', + } + + class Schema: + option = c.Theme() + + with self.expect_error( + option=re.compile( + r"Unrecognised theme name: 'mkdocs2'. The available installed themes are: .+" + ) + ): + self.get_config(Schema, {'option': config}) + + def test_theme_invalid_type(self): + config = ['mkdocs2'] + + class Schema: + option = c.Theme() + + with self.expect_error( + option="Invalid type . Expected a string or key/value pairs." + ): + self.get_config(Schema, {'option': config}) + + def test_post_validation_none_theme_name_and_missing_custom_dir(self): + config = { + 'theme': { + 'name': None, + }, + } + + class Schema: + theme = c.Theme() + + with self.expect_error(theme="At least one of 'name' or 'custom_dir' must be defined."): + self.get_config(Schema, config) + + @tempdir() + def test_post_validation_inexisting_custom_dir(self, abs_base_path): + path = os.path.join(abs_base_path, 'inexisting_custom_dir') + config = { + 'theme': { + 'name': None, + 'custom_dir': path, + }, + } + + class Schema: + theme = c.Theme() + + with self.expect_error(theme=f"The path set in custom_dir ('{path}') does not exist."): + self.get_config(Schema, config) + + def test_post_validation_locale_none(self): + config = { + 'theme': { + 'name': 'mkdocs', + 'locale': None, + }, + } + + class Schema: + theme = c.Theme() + + with self.expect_error(theme="'locale' must be a string."): + self.get_config(Schema, config) + + def test_post_validation_locale_invalid_type(self): + config = { + 'theme': { + 'name': 'mkdocs', + 'locale': 0, + }, + } + + class Schema: + theme = c.Theme() + + with self.expect_error(theme="'locale' must be a string."): + self.get_config(Schema, config) + + def test_post_validation_locale(self): + config = { + 'theme': { + 'name': 'mkdocs', + 'locale': 'fr', + }, + } + + class Schema: + theme = c.Theme() + + conf = self.get_config(Schema, config) + self.assertEqual(conf['theme']['locale'].language, 'fr') + + +class NavTest(TestCase): + class Schema: + option = c.Nav() + + def test_old_format(self): + with self.expect_error( + option="Expected nav item to be a string or dict, got a list: ['index.md']" + ): + self.get_config(self.Schema, {'option': [['index.md']]}) + + def test_provided_dict(self): + conf = self.get_config(self.Schema, {'option': ['index.md', {"Page": "page.md"}]}) + self.assertEqual(conf['option'], ['index.md', {'Page': 'page.md'}]) + + def test_provided_empty(self): + conf = self.get_config(self.Schema, {'option': []}) + self.assertEqual(conf['option'], None) + + def test_normal_nav(self): + nav_yaml = textwrap.dedent( + '''\ + - Home: index.md + - getting-started.md + - User Guide: + - Overview: user-guide/index.md + - Installation: user-guide/installation.md + ''' + ) + nav = yaml_load(io.StringIO(nav_yaml)) + + conf = self.get_config(self.Schema, {'option': nav}) + self.assertEqual(conf['option'], nav) + + def test_invalid_type_dict(self): + with self.expect_error(option="Expected nav to be a list, got a dict: {}"): + self.get_config(self.Schema, {'option': {}}) + + def test_invalid_type_int(self): + with self.expect_error(option="Expected nav to be a list, got a int: 5"): + self.get_config(self.Schema, {'option': 5}) + + def test_invalid_item_int(self): + with self.expect_error(option="Expected nav item to be a string or dict, got a int: 1"): + self.get_config(self.Schema, {'option': [1]}) + + def test_invalid_item_none(self): + with self.expect_error(option="Expected nav item to be a string or dict, got None"): + self.get_config(self.Schema, {'option': [None]}) + + def test_invalid_children_config_int(self): + with self.expect_error(option="Expected nav to be a list, got a int: 1"): + self.get_config(self.Schema, {'option': [{"foo.md": [{"bar.md": 1}]}]}) + + def test_invalid_children_config_none(self): + with self.expect_error(option="Expected nav to be a list, got None"): + self.get_config(self.Schema, {'option': [{"foo.md": None}]}) + + def test_invalid_children_empty_dict(self): + nav = ['foo', {}] + with self.expect_error(option="Expected nav item to be a dict of size 1, got a dict: {}"): + self.get_config(self.Schema, {'option': nav}) + + def test_invalid_nested_list(self): + nav = [{'aaa': [[{"bbb": "user-guide/index.md"}]]}] + with self.expect_error( + option="Expected nav item to be a string or dict, got a list: [{'bbb': 'user-guide/index.md'}]" + ): + self.get_config(self.Schema, {'option': nav}) + + def test_invalid_children_oversized_dict(self): + nav = [{"aaa": [{"bbb": "user-guide/index.md", "ccc": "user-guide/installation.md"}]}] + with self.expect_error( + option="Expected nav item to be a dict of size 1, got dict with keys ('bbb', 'ccc')" + ): + self.get_config(self.Schema, {'option': nav}) + + def test_warns_for_dict(self): + self.get_config( + self.Schema, + {'option': [{"a": {"b": "c.md", "d": "e.md"}}]}, + warnings=dict(option="Expected nav to be a list, got dict with keys ('b', 'd')"), + ) + + +class PrivateTest(TestCase): + def test_defined(self): + class Schema: + option = c.Private() + + with self.expect_error(option="For internal use only."): + self.get_config(Schema, {'option': 'somevalue'}) + + +class SubConfigTest(TestCase): + def test_subconfig_wrong_type(self): + # Test that an error is raised if subconfig does not receive a dict + class Schema: + option = c.SubConfig() + + for val in "not_a_dict", ("not_a_dict",), ["not_a_dict"]: + with self.subTest(val): + with self.expect_error( + option=re.compile( + r"The configuration is invalid. Expected a key-value mapping " + r"\(dict\) but received: .+" + ) + ): + self.get_config(Schema, {'option': val}) + + def test_subconfig_ignored(self): + """Default behaviour of subconfig: validation is ignored""" + + # Nominal + class Schema1: + option = c.SubConfig(('cc', c.Choice(('foo', 'bar')))) + + conf = self.get_config(Schema1, {'option': {'cc': 'foo'}}) + self.assertEqual(conf, {'option': {'cc': 'foo'}}) + + # Invalid option: No error + class Schema2: + option = c.SubConfig(('cc', c.Choice(('foo', 'bar')))) + + conf = self.get_config(Schema2, {'option': {'cc': True}}) + self.assertEqual(conf, {'option': {'cc': True}}) + + # Missing option: Will be considered optional with default None + class Schema3: + option = c.SubConfig(('cc', c.Choice(('foo', 'bar')))) + + conf = self.get_config(Schema3, {'option': {}}) + self.assertEqual(conf, {'option': {'cc': None}}) + + # Unknown option: No warning + class Schema4: + option = c.SubConfig(('cc', c.Choice(('foo', 'bar')))) + + conf = self.get_config(Schema4, {'option': {'unknown_key_is_ok': 0}}) + self.assertEqual(conf, {'option': {'cc': None, 'unknown_key_is_ok': 0}}) + + def test_subconfig_unknown_option(self): + class Schema: + option = c.SubConfig(validate=True) + + conf = self.get_config( + Schema, + {'option': {'unknown': 0}}, + warnings=dict(option="Sub-option 'unknown': Unrecognised configuration name: unknown"), + ) + self.assertEqual(conf['option'], {"unknown": 0}) + + def test_subconfig_invalid_option(self): + class Schema: + option = c.SubConfig( + ('cc', c.Choice(('foo', 'bar'))), + validate=True, + ) + + with self.expect_error( + option="Sub-option 'cc': Expected one of: ('foo', 'bar') but received: True" + ): + self.get_config(Schema, {'option': {'cc': True}}) + + def test_subconfig_normal(self): + class Schema: + option = c.SubConfig( + ('cc', c.Choice(('foo', 'bar'))), + ) + + conf = self.get_config(Schema, {'option': {'cc': 'foo'}}) + self.assertEqual(conf['option'], {'cc': 'foo'}) + + def test_config_file_path_pass_through(self): + """Necessary to ensure FilesystemObject validates the correct path""" + + passed_config_path = None + + class SubType(c.BaseConfigOption): + def pre_validation(self, config, key_name): + nonlocal passed_config_path + passed_config_path = config.config_file_path + + class Schema: + sub = c.SubConfig(('opt', SubType())) + + config_path = "foo/mkdocs.yaml" + self.get_config(Schema, {"sub": {"opt": "bar"}}, config_file_path=config_path) + self.assertEqual(passed_config_path, config_path) + + +class ConfigItemsTest(TestCase): + def test_subconfig_with_multiple_items(self): + # This had a bug where subsequent items would get merged into the same dict. + class Schema: + the_items = c.ConfigItems( + ("value", c.Type(str)), + ) + + conf = self.get_config( + Schema, + { + 'the_items': [ + {'value': 'a'}, + {'value': 'b'}, + ] + }, + ) + self.assertEqual(conf['the_items'], [{'value': 'a'}, {'value': 'b'}]) + + def test_optional(self): + class Schema: + sub = c.ListOfItems( + c.SubConfig( + ('opt', c.Type(int)), + validate=True, + ), + default=[], + ) + + conf = self.get_config(Schema, {}) + self.assertEqual(conf['sub'], []) + + conf = self.get_config(Schema, {'sub': None}) + self.assertEqual(conf['sub'], []) + + conf = self.get_config(Schema, {'sub': [{'opt': 1}, {}]}) + self.assertEqual(conf['sub'], [{'opt': 1}, {'opt': None}]) + + conf = self.get_config(Schema, {'sub': []}) + + conf = self.get_config(Schema, {'sub': [{'opt': 1}, {'opt': 2}]}) + self.assertEqual(conf['sub'], [{'opt': 1}, {'opt': 2}]) + + def test_required(self): + class Schema: + sub = c.ListOfItems( + c.SubConfig( + ('opt', c.Type(int, required=True)), + validate=True, + ) + ) + + with self.expect_error(sub="Required configuration not provided."): + conf = self.get_config(Schema, {}) + + with self.expect_error(sub="Required configuration not provided."): + conf = self.get_config(Schema, {'sub': None}) + + with self.expect_error( + sub="Sub-option 'opt': Expected type: but received: " + ): + conf = self.get_config(Schema, {'sub': [{'opt': 'asdf'}, {}]}) + + conf = self.get_config(Schema, {'sub': []}) + + conf = self.get_config(Schema, {'sub': [{'opt': 1}, {'opt': 2}]}) + self.assertEqual(conf['sub'], [{'opt': 1}, {'opt': 2}]) + + with self.expect_error( + sub="Sub-option 'opt': Expected type: but received: " + ): + self.get_config(Schema, {'sub': [{'opt': 'z'}, {'opt': 2}]}) + + with self.expect_error( + sub="Sub-option 'opt': Expected type: but received: " + ): + conf = self.get_config(Schema, {'sub': [{'opt': 'z'}, {'opt': 2}]}) + + with self.expect_error( + sub="The configuration is invalid. Expected a key-value mapping " + "(dict) but received: " + ): + conf = self.get_config(Schema, {'sub': [1, 2]}) + + +class MarkdownExtensionsTest(TestCase): + @patch('markdown.Markdown') + def test_simple_list(self, mock_md): + class Schema: + markdown_extensions = c.MarkdownExtensions() + mdx_configs = c.Private() + + config = { + 'markdown_extensions': ['foo', 'bar'], + } + conf = self.get_config(Schema, config) + self.assertEqual(conf['markdown_extensions'], ['foo', 'bar']) + self.assertEqual(conf['mdx_configs'], {}) + + @patch('markdown.Markdown') + def test_list_dicts(self, mock_md): + class Schema: + markdown_extensions = c.MarkdownExtensions() + mdx_configs = c.Private() + + config = { + 'markdown_extensions': [ + {'foo': {'foo_option': 'foo value'}}, + {'bar': {'bar_option': 'bar value'}}, + {'baz': None}, + ] + } + conf = self.get_config(Schema, config) + self.assertEqual(conf['markdown_extensions'], ['foo', 'bar', 'baz']) + self.assertEqual( + conf['mdx_configs'], + { + 'foo': {'foo_option': 'foo value'}, + 'bar': {'bar_option': 'bar value'}, + }, + ) + + @patch('markdown.Markdown') + def test_mixed_list(self, mock_md): + class Schema: + markdown_extensions = c.MarkdownExtensions() + mdx_configs = c.Private() + + config = { + 'markdown_extensions': [ + 'foo', + {'bar': {'bar_option': 'bar value'}}, + ] + } + conf = self.get_config(Schema, config) + self.assertEqual(conf['markdown_extensions'], ['foo', 'bar']) + self.assertEqual( + conf['mdx_configs'], + { + 'bar': {'bar_option': 'bar value'}, + }, + ) + + @patch('markdown.Markdown') + def test_dict_of_dicts(self, mock_md): + class Schema: + markdown_extensions = c.MarkdownExtensions() + mdx_configs = c.Private() + + config = { + 'markdown_extensions': { + 'foo': {'foo_option': 'foo value'}, + 'bar': {'bar_option': 'bar value'}, + 'baz': {}, + } + } + conf = self.get_config(Schema, config) + self.assertEqual(conf['markdown_extensions'], ['foo', 'bar', 'baz']) + self.assertEqual( + conf['mdx_configs'], + { + 'foo': {'foo_option': 'foo value'}, + 'bar': {'bar_option': 'bar value'}, + }, + ) + + @patch('markdown.Markdown') + def test_builtins(self, mock_md): + class Schema: + markdown_extensions = c.MarkdownExtensions(builtins=['meta', 'toc']) + mdx_configs = c.Private() + + config = { + 'markdown_extensions': ['foo', 'bar'], + } + conf = self.get_config(Schema, config) + self.assertEqual(conf['markdown_extensions'], ['meta', 'toc', 'foo', 'bar']) + self.assertEqual(conf['mdx_configs'], {}) + + def test_duplicates(self): + class Schema: + markdown_extensions = c.MarkdownExtensions(builtins=['meta', 'toc']) + mdx_configs = c.Private() + + config = { + 'markdown_extensions': ['meta', 'toc'], + } + conf = self.get_config(Schema, config) + self.assertEqual(conf['markdown_extensions'], ['meta', 'toc']) + self.assertEqual(conf['mdx_configs'], {}) + + def test_builtins_config(self): + class Schema: + markdown_extensions = c.MarkdownExtensions(builtins=['meta', 'toc']) + mdx_configs = c.Private() + + config = { + 'markdown_extensions': [ + {'toc': {'permalink': True}}, + ], + } + conf = self.get_config(Schema, config) + self.assertEqual(conf['markdown_extensions'], ['meta', 'toc']) + self.assertEqual(conf['mdx_configs'], {'toc': {'permalink': True}}) + + @patch('markdown.Markdown') + def test_configkey(self, mock_md): + class Schema: + markdown_extensions = c.MarkdownExtensions(configkey='bar') + bar = c.Private() + + config = { + 'markdown_extensions': [ + {'foo': {'foo_option': 'foo value'}}, + ] + } + conf = self.get_config(Schema, config) + self.assertEqual(conf['markdown_extensions'], ['foo']) + self.assertEqual( + conf['bar'], + { + 'foo': {'foo_option': 'foo value'}, + }, + ) + + def test_missing_default(self): + class Schema: + markdown_extensions = c.MarkdownExtensions() + mdx_configs = c.Private() + + conf = self.get_config(Schema, {}) + self.assertEqual(conf['markdown_extensions'], []) + self.assertEqual(conf['mdx_configs'], {}) + + def test_none(self): + class Schema: + markdown_extensions = c.MarkdownExtensions(default=[]) + mdx_configs = c.Private() + + config = { + 'markdown_extensions': None, + } + conf = self.get_config(Schema, config) + self.assertEqual(conf['markdown_extensions'], []) + self.assertEqual(conf['mdx_configs'], {}) + + @patch('markdown.Markdown') + def test_not_list(self, mock_md): + class Schema: + option = c.MarkdownExtensions() + + with self.expect_error(option="Invalid Markdown Extensions configuration"): + self.get_config(Schema, {'option': 'not a list'}) + + @patch('markdown.Markdown') + def test_invalid_config_option(self, mock_md): + class Schema: + markdown_extensions = c.MarkdownExtensions() + + config = { + 'markdown_extensions': [ + {'foo': 'not a dict'}, + ], + } + with self.expect_error( + markdown_extensions="Invalid config options for Markdown Extension 'foo'." + ): + self.get_config(Schema, config) + + @patch('markdown.Markdown') + def test_invalid_config_item(self, mock_md): + class Schema: + markdown_extensions = c.MarkdownExtensions() + + config = { + 'markdown_extensions': [ + ['not a dict'], + ], + } + with self.expect_error(markdown_extensions="Invalid Markdown Extensions configuration"): + self.get_config(Schema, config) + + @patch('markdown.Markdown') + def test_invalid_dict_item(self, mock_md): + class Schema: + markdown_extensions = c.MarkdownExtensions() + + config = { + 'markdown_extensions': [ + {'key1': 'value', 'key2': 'too many keys'}, + ], + } + with self.expect_error(markdown_extensions="Invalid Markdown Extensions configuration"): + self.get_config(Schema, config) + + def test_unknown_extension(self): + class Schema: + markdown_extensions = c.MarkdownExtensions() + + config = { + 'markdown_extensions': ['unknown'], + } + with self.expect_error( + markdown_extensions=re.compile(r"Failed to load extension 'unknown'.\n.+") + ): + self.get_config(Schema, config) + + def test_multiple_markdown_config_instances(self): + # This had a bug where an extension config would persist to separate + # config instances that didn't specify extensions. + class Schema: + markdown_extensions = c.MarkdownExtensions() + mdx_configs = c.Private() + + conf = self.get_config( + Schema, + { + 'markdown_extensions': [{'toc': {'permalink': '##'}}], + }, + ) + self.assertEqual(conf['mdx_configs']['toc'], {'permalink': '##'}) + + conf = self.get_config( + Schema, + {}, + ) + self.assertIsNone(conf['mdx_configs'].get('toc')) + + +class HooksTest(TestCase): + class Schema: + plugins = c.Plugins(default=[]) + hooks = c.Hooks('plugins') + + @tempdir() + def test_hooks(self, src_dir): + write_file( + b'def on_page_markdown(markdown, **kwargs): return markdown.replace("f", "z")', + os.path.join(src_dir, 'hooks', 'my_hook.py'), + ) + write_file( + b'foo foo', + os.path.join(src_dir, 'docs', 'index.md'), + ) + conf = self.get_config( + self.Schema, + {'hooks': ['hooks/my_hook.py']}, + config_file_path=os.path.join(src_dir, 'mkdocs.yml'), + ) + self.assertIn('hooks/my_hook.py', conf['plugins']) + hook = conf['plugins']['hooks/my_hook.py'] + self.assertTrue(hasattr(hook, 'on_page_markdown')) + self.assertEqual( + {**conf['plugins'].events, 'page_markdown': [hook.on_page_markdown]}, + conf['plugins'].events, + ) + self.assertEqual(hook.on_page_markdown('foo foo'), 'zoo zoo') + self.assertFalse(hasattr(hook, 'on_nav')) + + +class SchemaTest(TestCase): + def test_copy(self): + copy.deepcopy( + base.LegacyConfig( + (('foo', c.MarkdownExtensions()),), + ), + ) + + copy.deepcopy(self.get_config(IpAddressTest.Schema, {'option': '1.2.3.4:5678'})) + copy.deepcopy(IpAddressTest.Schema) + copy.deepcopy(base.get_schema(IpAddressTest.Schema)) + + copy.deepcopy(self.get_config(EditURITest.Schema, {})) + copy.deepcopy(EditURITest.Schema) + copy.deepcopy(base.get_schema(EditURITest.Schema)) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/config/config_options_tests.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/config/config_options_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..7fd2149c1ff015a2800bd0b9334ea78dae4fb290 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/config/config_options_tests.py @@ -0,0 +1,2374 @@ +from __future__ import annotations + +import contextlib +import copy +import io +import logging +import os +import re +import sys +import textwrap +import unittest +from typing import TYPE_CHECKING, Any, Dict, List, Optional, TypeVar, Union +from unittest.mock import patch + +if TYPE_CHECKING: + from typing_extensions import assert_type +else: + + def assert_type(val, typ): + return None + + +import mkdocs +from mkdocs.config import config_options as c +from mkdocs.config import defaults +from mkdocs.config.base import Config +from mkdocs.plugins import BasePlugin, PluginCollection +from mkdocs.tests.base import tempdir +from mkdocs.theme import Theme +from mkdocs.utils import write_file, yaml_load + +SomeConfig = TypeVar('SomeConfig', bound=Config) + + +class UnexpectedError(Exception): + pass + + +class TestCase(unittest.TestCase): + @contextlib.contextmanager + def expect_error(self, **kwargs): + [(key, msg)] = kwargs.items() + with self.assertRaises(UnexpectedError) as cm: + yield + if isinstance(msg, re.Pattern): + self.assertRegex(str(cm.exception), f'^{key}="{msg.pattern}"$') + else: + self.assertEqual(f'{key}="{msg}"', str(cm.exception)) + + def get_config( + self, + config_class: type[SomeConfig], + cfg: dict[str, Any], + warnings: dict[str, str] = {}, + config_file_path=None, + ) -> SomeConfig: + config = config_class(config_file_path=config_file_path) + config.load_dict(cfg) + actual_errors, actual_warnings = config.validate() + if actual_errors: + raise UnexpectedError(', '.join(f'{key}="{msg}"' for key, msg in actual_errors)) + self.assertEqual(warnings, dict(actual_warnings)) + return config + + +class TypeTest(TestCase): + def test_single_type(self) -> None: + class Schema(Config): + option = c.Type(str) + + conf = self.get_config(Schema, {'option': "Testing"}) + assert_type(conf.option, str) + self.assertEqual(conf.option, "Testing") + + def test_multiple_types(self) -> None: + class Schema(Config): + option = c.Type((list, tuple)) + + conf = self.get_config(Schema, {'option': [1, 2, 3]}) + self.assertEqual(conf.option, [1, 2, 3]) + + conf = self.get_config(Schema, {'option': (1, 2, 3)}) + self.assertEqual(conf.option, (1, 2, 3)) + + with self.expect_error( + option="Expected type: (, ) but received: " + ): + self.get_config(Schema, {'option': {'a': 1}}) + + def test_length(self) -> None: + class Schema(Config): + option = c.Type(str, length=7) + + conf = self.get_config(Schema, {'option': "Testing"}) + assert_type(conf.option, str) + self.assertEqual(conf.option, "Testing") + + with self.expect_error( + option="Expected type: with length 7 but received: 'Testing Long' with length 12" + ): + self.get_config(Schema, {'option': "Testing Long"}) + + def test_optional_with_default(self) -> None: + with self.assertRaisesRegex(ValueError, "doesn't need to be wrapped into Optional"): + c.Optional(c.Type(int, default=5)) + + +class ChoiceTest(TestCase): + def test_required(self) -> None: + class Schema(Config): + option = c.Choice(('python', 'node')) + + conf = self.get_config(Schema, {'option': 'python'}) + assert_type(conf.option, str) + self.assertEqual(conf.option, 'python') + + def test_optional(self) -> None: + class Schema(Config): + option = c.Optional(c.Choice(('python', 'node'))) + + conf = self.get_config(Schema, {'option': 'python'}) + assert_type(conf.option, Optional[str]) + self.assertEqual(conf.option, 'python') + + conf = self.get_config(Schema, {}) + self.assertEqual(conf.option, None) + + conf = self.get_config(Schema, {'option': None}) + self.assertEqual(conf.option, None) + + def test_default(self) -> None: + class Schema(Config): + option = c.Choice(('a', 'b', 'c'), default='b') + + conf = self.get_config(Schema, {}) + assert_type(conf.option, str) + self.assertEqual(conf.option, 'b') + + conf = self.get_config(Schema, {}) + self.assertEqual(conf.option, 'b') + + conf = self.get_config(Schema, {'option': None}) + self.assertEqual(conf.option, 'b') + + with self.expect_error(option="Expected one of: ('a', 'b', 'c') but received: 'go'"): + self.get_config(Schema, {'option': 'go'}) + + def test_invalid_default(self) -> None: + with self.assertRaises(ValueError): + c.Choice(('a', 'b'), default='c') + with self.assertRaises(ValueError): + c.Choice(('a', 'b'), default='c', required=True) + + def test_invalid_choice(self) -> None: + class Schema(Config): + option = c.Choice(('python', 'node')) + + with self.expect_error(option="Expected one of: ('python', 'node') but received: 'go'"): + self.get_config(Schema, {'option': 'go'}) + + def test_invalid_choices(self) -> None: + with self.assertRaises(ValueError): + c.Choice('') + with self.assertRaises(ValueError): + c.Choice([]) + + +class DeprecatedTest(TestCase): + def test_deprecated_option_simple(self) -> None: + class Schema(Config): + d = c.Deprecated() + + self.get_config( + Schema, + {'d': 'value'}, + warnings=dict( + d="The configuration option 'd' has been deprecated and will be removed in a " + "future release." + ), + ) + + def test_deprecated_option_message(self) -> None: + class Schema(Config): + d = c.Deprecated(message='custom message for {} key') + + self.get_config(Schema, {'d': 'value'}, warnings={'d': 'custom message for d key'}) + + def test_deprecated_option_with_type(self) -> None: + class Schema(Config): + d = c.Deprecated(option_type=c.Type(str)) + + self.get_config( + Schema, + {'d': 'value'}, + warnings=dict( + d="The configuration option 'd' has been deprecated and will be removed in a " + "future release." + ), + ) + + def test_deprecated_option_with_invalid_type(self) -> None: + class Schema(Config): + d = c.Deprecated(option_type=c.Type(list)) + + with self.expect_error(d="Expected type: but received: "): + self.get_config( + Schema, + {'d': 'value'}, + warnings=dict( + d="The configuration option 'd' has been deprecated and will be removed in a " + "future release." + ), + ) + + def test_removed_option(self) -> None: + class Schema(Config): + d = c.Deprecated(removed=True, moved_to='foo') + + with self.expect_error( + d="The configuration option 'd' was removed from MkDocs. Use 'foo' instead.", + ): + self.get_config(Schema, {'d': 'value'}) + + def test_deprecated_option_with_type_undefined(self) -> None: + class Schema(Config): + option = c.Deprecated(option_type=c.Type(str)) + + self.get_config(Schema, {'option': None}) + + def test_deprecated_option_move(self) -> None: + class Schema(Config): + new = c.Type(str) + old = c.Deprecated(moved_to='new') + + conf = self.get_config( + Schema, + {'old': 'value'}, + warnings=dict( + old="The configuration option 'old' has been deprecated and will be removed in a " + "future release. Use 'new' instead." + ), + ) + self.assertEqual(conf, {'new': 'value', 'old': None}) + + def test_deprecated_option_move_complex(self) -> None: + class Schema(Config): + foo = c.Type(dict) + old = c.Deprecated(moved_to='foo.bar') + + conf = self.get_config( + Schema, + {'old': 'value'}, + warnings=dict( + old="The configuration option 'old' has been deprecated and will be removed in a " + "future release. Use 'foo.bar' instead." + ), + ) + self.assertEqual(conf, {'foo': {'bar': 'value'}, 'old': None}) + + def test_deprecated_option_move_existing(self) -> None: + class Schema(Config): + foo = c.Type(dict) + old = c.Deprecated(moved_to='foo.bar') + + conf = self.get_config( + Schema, + {'old': 'value', 'foo': {'existing': 'existing'}}, + warnings=dict( + old="The configuration option 'old' has been deprecated and will be removed in a " + "future release. Use 'foo.bar' instead." + ), + ) + self.assertEqual(conf, {'foo': {'existing': 'existing', 'bar': 'value'}, 'old': None}) + + def test_deprecated_option_move_invalid(self) -> None: + class Schema(Config): + foo = c.Type(dict) + old = c.Deprecated(moved_to='foo.bar') + + with self.expect_error(foo="Expected type: but received: "): + self.get_config( + Schema, + {'old': 'value', 'foo': 'wrong type'}, + warnings=dict( + old="The configuration option 'old' has been deprecated and will be removed in a " + "future release. Use 'foo.bar' instead." + ), + ) + + +class IpAddressTest(TestCase): + class Schema(Config): + option = c.IpAddress() + + def test_valid_address(self) -> None: + addr = '127.0.0.1:8000' + + conf = self.get_config(self.Schema, {'option': addr}) + + assert_type(conf.option, c._IpAddressValue) + assert_type(conf.option.host, str) + assert_type(conf.option.port, int) + + self.assertEqual(str(conf.option), addr) + self.assertEqual(conf.option.host, '127.0.0.1') + self.assertEqual(conf.option.port, 8000) + + def test_valid_IPv6_address(self) -> None: + addr = '::1:8000' + + conf = self.get_config(self.Schema, {'option': addr}) + self.assertEqual(str(conf.option), addr) + self.assertEqual(conf.option.host, '::1') + self.assertEqual(conf.option.port, 8000) + + def test_valid_full_IPv6_address(self) -> None: + addr = '[2001:db8:85a3::8a2e:370:7334]:123' + + conf = self.get_config(self.Schema, {'option': addr}) + self.assertEqual(conf.option.host, '2001:db8:85a3::8a2e:370:7334') + self.assertEqual(conf.option.port, 123) + + def test_named_address(self) -> None: + addr = 'localhost:8000' + + conf = self.get_config(self.Schema, {'option': addr}) + self.assertEqual(str(conf.option), addr) + self.assertEqual(conf.option.host, 'localhost') + self.assertEqual(conf.option.port, 8000) + + def test_default_address(self) -> None: + addr = '127.0.0.1:8000' + + class Schema(Config): + option = c.IpAddress(default=addr) + + conf = self.get_config(Schema, {'option': None}) + self.assertEqual(str(conf.option), addr) + self.assertEqual(conf.option.host, '127.0.0.1') + self.assertEqual(conf.option.port, 8000) + + @unittest.skipIf( + sys.version_info < (3, 9, 5), + "Leading zeros allowed in IP addresses before Python3.9.5", + ) + def test_invalid_leading_zeros(self) -> None: + with self.expect_error( + option="'127.000.000.001' does not appear to be an IPv4 or IPv6 address" + ): + self.get_config(self.Schema, {'option': '127.000.000.001:8000'}) + + def test_invalid_address_range(self) -> None: + with self.expect_error(option="'277.0.0.1' does not appear to be an IPv4 or IPv6 address"): + self.get_config(self.Schema, {'option': '277.0.0.1:8000'}) + + def test_invalid_address_format(self) -> None: + with self.expect_error(option="Must be a string of format 'IP:PORT'"): + self.get_config(self.Schema, {'option': '127.0.0.18000'}) + + def test_invalid_address_type(self) -> None: + with self.expect_error(option="Must be a string of format 'IP:PORT'"): + self.get_config(self.Schema, {'option': 123}) + + def test_invalid_address_port(self) -> None: + with self.expect_error(option="'foo' is not a valid port"): + self.get_config(self.Schema, {'option': '127.0.0.1:foo'}) + + def test_invalid_address_missing_port(self) -> None: + with self.expect_error(option="Must be a string of format 'IP:PORT'"): + self.get_config(self.Schema, {'option': '127.0.0.1'}) + + def test_unsupported_address(self) -> None: + class Schema(Config): + dev_addr = c.IpAddress() + + self.get_config( + Schema, + {'dev_addr': '0.0.0.0:8000'}, + warnings=dict( + dev_addr="The use of the IP address '0.0.0.0' suggests a production " + "environment or the use of a proxy to connect to the MkDocs " + "server. However, the MkDocs' server is intended for local " + "development purposes only. Please use a third party " + "production-ready server instead." + ), + ) + + def test_unsupported_IPv6_address(self) -> None: + class Schema(Config): + dev_addr = c.IpAddress() + + self.get_config( + Schema, + {'dev_addr': ':::8000'}, + warnings=dict( + dev_addr="The use of the IP address '::' suggests a production environment " + "or the use of a proxy to connect to the MkDocs server. However, " + "the MkDocs' server is intended for local development purposes " + "only. Please use a third party production-ready server instead." + ), + ) + + +class URLTest(TestCase): + def test_valid_url(self) -> None: + class Schema(Config): + option = c.URL() + + conf = self.get_config(Schema, {'option': "https://mkdocs.org"}) + assert_type(conf.option, str) + self.assertEqual(conf.option, "https://mkdocs.org") + + conf = self.get_config(Schema, {'option': ""}) + self.assertEqual(conf.option, "") + + def test_valid_url_is_dir(self) -> None: + class Schema(Config): + option = c.URL(is_dir=True) + + conf = self.get_config(Schema, {'option': "http://mkdocs.org/"}) + self.assertEqual(conf.option, "http://mkdocs.org/") + + conf = self.get_config(Schema, {'option': "https://mkdocs.org"}) + self.assertEqual(conf.option, "https://mkdocs.org/") + + def test_optional(self): + class Schema(Config): + option = c.Optional(c.URL(is_dir=True)) + + conf = self.get_config(Schema, {'option': ''}) + self.assertEqual(conf.option, '') + + conf = self.get_config(Schema, {'option': None}) + self.assertEqual(conf.option, None) + + def test_invalid_url(self) -> None: + class Schema(Config): + option = c.URL() + + with self.expect_error(option="Required configuration not provided."): + self.get_config(Schema, {'option': None}) + + for url in "www.mkdocs.org", "//mkdocs.org/test", "http:/mkdocs.org/", "/hello/": + with self.subTest(url=url): + with self.expect_error( + option="The URL isn't valid, it should include the http:// (scheme)" + ): + self.get_config(Schema, {'option': url}) + + def test_invalid_type(self) -> None: + class Schema(Config): + option = c.URL() + + with self.expect_error(option="Expected a string, got "): + self.get_config(Schema, {'option': 1}) + + +class EditURITest(TestCase): + class Schema(Config): + repo_url = c.Optional(c.URL()) + repo_name = c.Optional(c.RepoName('repo_url')) + edit_uri_template = c.Optional(c.EditURITemplate('edit_uri')) + edit_uri = c.Optional(c.EditURI('repo_url')) + + def test_repo_name_github(self) -> None: + conf = self.get_config( + self.Schema, + {'repo_url': "https://github.com/mkdocs/mkdocs"}, + ) + assert_type(conf.repo_name, Optional[str]) + self.assertEqual(conf.repo_name, "GitHub") + + def test_repo_name_bitbucket(self) -> None: + conf = self.get_config( + self.Schema, + {'repo_url': "https://bitbucket.org/gutworth/six/"}, + ) + self.assertEqual(conf.repo_name, "Bitbucket") + + def test_repo_name_gitlab(self) -> None: + conf = self.get_config( + self.Schema, + {'repo_url': "https://gitlab.com/gitlab-org/gitlab-ce/"}, + ) + self.assertEqual(conf.repo_name, "GitLab") + + def test_repo_name_custom(self) -> None: + conf = self.get_config( + self.Schema, + {'repo_url': "https://launchpad.net/python-tuskarclient"}, + ) + self.assertEqual(conf.repo_name, "Launchpad") + + def test_edit_uri_github(self) -> None: + conf = self.get_config( + self.Schema, + {'repo_url': "https://github.com/mkdocs/mkdocs"}, + ) + assert_type(conf.edit_uri, Optional[str]) + assert_type(conf.repo_url, Optional[str]) + self.assertEqual(conf.edit_uri, 'edit/master/docs/') + self.assertEqual(conf.repo_url, "https://github.com/mkdocs/mkdocs") + + def test_edit_uri_bitbucket(self) -> None: + conf = self.get_config( + self.Schema, + {'repo_url': "https://bitbucket.org/gutworth/six/"}, + ) + self.assertEqual(conf.edit_uri, 'src/default/docs/') + self.assertEqual(conf.repo_url, "https://bitbucket.org/gutworth/six/") + + def test_edit_uri_gitlab(self) -> None: + conf = self.get_config( + self.Schema, + {'repo_url': "https://gitlab.com/gitlab-org/gitlab-ce/"}, + ) + self.assertEqual(conf.edit_uri, 'edit/master/docs/') + + def test_edit_uri_custom(self) -> None: + conf = self.get_config( + self.Schema, + {'repo_url': "https://launchpad.net/python-tuskarclient"}, + ) + self.assertEqual(conf.edit_uri, None) + self.assertEqual(conf.repo_url, "https://launchpad.net/python-tuskarclient") + + def test_repo_name_custom_and_empty_edit_uri(self) -> None: + conf = self.get_config( + self.Schema, + {'repo_url': "https://github.com/mkdocs/mkdocs", 'repo_name': 'mkdocs'}, + ) + self.assertEqual(conf.edit_uri, 'edit/master/docs/') + + def test_edit_uri_template_ok(self) -> None: + conf = self.get_config( + self.Schema, + { + 'repo_url': "https://github.com/mkdocs/mkdocs", + 'edit_uri_template': 'edit/foo/docs/{path}', + }, + ) + assert_type(conf.edit_uri_template, Optional[str]) + self.assertEqual(conf.edit_uri_template, 'edit/foo/docs/{path}') + + def test_edit_uri_template_errors(self) -> None: + with self.expect_error( + edit_uri_template=re.compile(r'.*[{}].*') # Complains about unclosed '{' or missing '}' + ): + self.get_config( + self.Schema, + { + 'repo_url': "https://github.com/mkdocs/mkdocs", + 'edit_uri_template': 'edit/master/{path', + }, + ) + + with self.expect_error(edit_uri_template=re.compile(r'.*\bz\b.*')): + self.get_config( + self.Schema, + { + 'repo_url': "https://github.com/mkdocs/mkdocs", + 'edit_uri_template': 'edit/master/{path!z}', + }, + ) + + with self.expect_error(edit_uri_template="Unknown template substitute: 'foo'"): + self.get_config( + self.Schema, + { + 'repo_url': "https://github.com/mkdocs/mkdocs", + 'edit_uri_template': 'edit/master/{foo}', + }, + ) + + def test_edit_uri_template_warning(self) -> None: + conf = self.get_config( + self.Schema, + { + 'repo_url': "https://github.com/mkdocs/mkdocs", + 'edit_uri': 'edit', + 'edit_uri_template': 'edit/master/{path}', + }, + warnings=dict( + edit_uri_template="The option 'edit_uri' has no effect when 'edit_uri_template' is set." + ), + ) + self.assertEqual(conf.edit_uri_template, 'edit/master/{path}') + + +class ListOfItemsTest(TestCase): + def test_int_type(self) -> None: + class Schema(Config): + option = c.ListOfItems(c.Type(int)) + + conf = self.get_config(Schema, {'option': [1, 2, 3]}) + assert_type(conf.option, List[int]) + self.assertEqual(conf.option, [1, 2, 3]) + + with self.expect_error( + option="Expected type: but received: " + ): + conf = self.get_config(Schema, {'option': [1, None, 3]}) + + def test_combined_float_type(self) -> None: + class Schema(Config): + option = c.ListOfItems(c.Type((int, float))) + + conf = self.get_config(Schema, {'option': [1.4, 2, 3]}) + self.assertEqual(conf.option, [1.4, 2, 3]) + + with self.expect_error( + option="Expected type: (, ) but received: " + ): + self.get_config(Schema, {'option': ['a']}) + + def test_list_default(self) -> None: + class Schema(Config): + option = c.ListOfItems(c.Type(int), default=[]) + + conf = self.get_config(Schema, {}) + assert_type(conf.option, List[int]) + self.assertEqual(conf.option, []) + + with self.expect_error(option="Required configuration not provided."): + conf = self.get_config(Schema, {'option': None}) + + def test_none_without_default(self) -> None: + class Schema(Config): + option = c.ListOfItems(c.Type(str)) + + with self.expect_error(option="Required configuration not provided."): + conf = self.get_config(Schema, {}) + + with self.expect_error(option="Required configuration not provided."): + conf = self.get_config(Schema, {'option': None}) + + conf = self.get_config(Schema, {'option': ['foo']}) + self.assertEqual(conf.option, ['foo']) + + def test_optional(self) -> None: + class Schema(Config): + option = c.Optional(c.ListOfItems(c.Type(str))) + + conf = self.get_config(Schema, {}) + assert_type(conf.option, Optional[List[str]]) + self.assertEqual(conf.option, None) + + conf = self.get_config(Schema, {'option': None}) + self.assertEqual(conf.option, None) + + conf = self.get_config(Schema, {'option': ['foo']}) + self.assertEqual(conf.option, ['foo']) + + def test_list_of_optional(self) -> None: + class Schema(Config): + option = c.ListOfItems(c.Optional(c.Type(int)), default=[]) + + conf = self.get_config(Schema, {}) + assert_type(conf.option, List[Optional[int]]) + self.assertEqual(conf.option, []) + + conf = self.get_config(Schema, {'option': [4, None]}) + self.assertEqual(conf.option, [4, None]) + + with self.expect_error(option="Expected type: but received: "): + conf = self.get_config(Schema, {'option': ['foo']}) + self.assertEqual(conf.option, ['foo']) + + def test_string_not_a_list_of_strings(self) -> None: + class Schema(Config): + option = c.ListOfItems(c.Type(str)) + + with self.expect_error(option="Expected a list of items, but a was given."): + self.get_config(Schema, {'option': 'foo'}) + + def test_post_validation_error(self) -> None: + class Schema(Config): + option = c.ListOfItems(c.IpAddress()) + + with self.expect_error(option="'asdf' is not a valid port"): + self.get_config(Schema, {'option': ["localhost:8000", "1.2.3.4:asdf"]}) + + def test_warning(self) -> None: + class Schema(Config): + option = c.ListOfItems(c.Deprecated()) + + self.get_config( + Schema, + {'option': ['a']}, + warnings=dict( + option="The configuration option 'option[0]' has been " + "deprecated and will be removed in a future release." + ), + ) + + +class ExtraScriptsTest(TestCase): + def test_js_async(self) -> None: + class Schema(Config): + option = c.ListOfItems(c.ExtraScript(), default=[]) + + conf = self.get_config(Schema, {'option': ['foo.js', {'path': 'bar.js', 'async': True}]}) + assert_type(conf.option, List[Union[c.ExtraScriptValue, str]]) + self.assertEqual(len(conf.option), 2) + self.assertIsInstance(conf.option[1], c.ExtraScriptValue) + self.assertEqual( + conf.option, + [ + 'foo.js', + {'path': 'bar.js', 'type': '', 'defer': False, 'async': True}, + ], + ) + + def test_mjs(self) -> None: + class Schema(Config): + option = c.ListOfItems(c.ExtraScript(), default=[]) + + conf = self.get_config( + Schema, {'option': ['foo.mjs', {'path': 'bar.js', 'type': 'module'}]} + ) + assert_type(conf.option, List[Union[c.ExtraScriptValue, str]]) + self.assertEqual(len(conf.option), 2) + self.assertIsInstance(conf.option[0], c.ExtraScriptValue) + self.assertEqual( + conf.option, + [ + {'path': 'foo.mjs', 'type': 'module', 'defer': False, 'async': False}, + {'path': 'bar.js', 'type': 'module', 'defer': False, 'async': False}, + ], + ) + + def test_wrong_type(self) -> None: + class Schema(Config): + option = c.ListOfItems(c.ExtraScript(), default=[]) + + with self.expect_error( + option="The configuration is invalid. Expected a key-value mapping (dict) but received: " + ): + self.get_config(Schema, {'option': [1]}) + + def test_unknown_key(self) -> None: + class Schema(Config): + option = c.ListOfItems(c.ExtraScript(), default=[]) + + conf = self.get_config( + Schema, + {'option': [{'path': 'foo.js', 'foo': 'bar'}]}, + warnings=dict(option="Sub-option 'foo': Unrecognised configuration name: foo"), + ) + self.assertEqual( + conf.option, + [{'path': 'foo.js', 'type': '', 'defer': False, 'async': False, 'foo': 'bar'}], + ) + + +class DictOfItemsTest(TestCase): + def test_int_type(self) -> None: + class Schema(Config): + option = c.DictOfItems(c.Type(int)) + + conf = self.get_config(Schema, {'option': {"a": 1, "b": 2}}) + assert_type(conf.option, Dict[str, int]) + self.assertEqual(conf.option, {"a": 1, "b": 2}) + + with self.expect_error( + option="Expected type: but received: " + ): + conf = self.get_config(Schema, {'option': {"a": 1, "b": None}}) + + def test_combined_float_type(self) -> None: + class Schema(Config): + option = c.DictOfItems(c.Type((int, float))) + + conf = self.get_config(Schema, {'option': {"a": 1, "b": 2.3}}) + self.assertEqual(conf.option, {"a": 1, "b": 2.3}) + + with self.expect_error( + option="Expected type: (, ) but received: " + ): + self.get_config(Schema, {'option': {"a": 1, "b": "2"}}) + + def test_dict_default(self) -> None: + class Schema(Config): + option = c.DictOfItems(c.Type(int), default={}) + + conf = self.get_config(Schema, {}) + assert_type(conf.option, Dict[str, int]) + self.assertEqual(conf.option, {}) + + with self.expect_error(option="Required configuration not provided."): + conf = self.get_config(Schema, {'option': None}) + + def test_none_without_default(self) -> None: + class Schema(Config): + option = c.DictOfItems(c.Type(str)) + + with self.expect_error(option="Required configuration not provided."): + conf = self.get_config(Schema, {}) + + with self.expect_error(option="Required configuration not provided."): + conf = self.get_config(Schema, {'option': None}) + + conf = self.get_config(Schema, {'option': {"foo": "bar"}}) + self.assertEqual(conf.option, {"foo": "bar"}) + + def test_optional(self) -> None: + class Schema(Config): + option = c.Optional(c.DictOfItems(c.Type(str))) + + conf = self.get_config(Schema, {}) + assert_type(conf.option, Optional[Dict[str, str]]) + self.assertEqual(conf.option, None) + + conf = self.get_config(Schema, {'option': None}) + self.assertEqual(conf.option, None) + + conf = self.get_config(Schema, {'option': {"foo": "bar"}}) + self.assertEqual(conf.option, {"foo": "bar"}) + + def test_dict_of_optional(self) -> None: + class Schema(Config): + option = c.DictOfItems(c.Optional(c.Type(int)), default={}) + + conf = self.get_config(Schema, {}) + assert_type(conf.option, Dict[str, Optional[int]]) + self.assertEqual(conf.option, {}) + + conf = self.get_config(Schema, {'option': {"a": 1, "b": None}}) + self.assertEqual(conf.option, {"a": 1, "b": None}) + + with self.expect_error(option="Expected type: but received: "): + conf = self.get_config(Schema, {'option': {"foo": "bar"}}) + self.assertEqual(conf.option, {"foo": "bar"}) + + def test_string_not_a_dict_of_strings(self) -> None: + class Schema(Config): + option = c.DictOfItems(c.Type(str)) + + with self.expect_error(option="Expected a dict of items, but a was given."): + self.get_config(Schema, {'option': 'foo'}) + + def test_post_validation_error(self) -> None: + class Schema(Config): + option = c.DictOfItems(c.IpAddress()) + + with self.expect_error(option="'asdf' is not a valid port"): + self.get_config( + Schema, {'option': {"ip_foo": "localhost:8000", "ip_bar": "1.2.3.4:asdf"}} + ) + + def test_all_keys_are_strings(self) -> None: + class Schema(Config): + option = c.DictOfItems(c.Type(int)) + + with self.expect_error( + option="Expected type: for keys, but received: (key=2)" + ): + self.get_config(Schema, {'option': {"a": 1, 2: 3}}) + + +class FilesystemObjectTest(TestCase): + def test_valid_dir(self) -> None: + for cls in c.Dir, c.FilesystemObject: + with self.subTest(cls): + d = os.path.dirname(__file__) + + class Schema(Config): + option = cls(exists=True) + + conf = self.get_config(Schema, {'option': d}) + assert_type(conf.option, str) + self.assertEqual(conf.option, d) + + def test_valid_file(self) -> None: + for cls in c.File, c.FilesystemObject: + with self.subTest(cls): + f = __file__ + + class Schema(Config): + option = cls(exists=True) + + conf = self.get_config(Schema, {'option': f}) + assert_type(conf.option, str) + self.assertEqual(conf.option, f) + + def test_missing_without_exists(self) -> None: + for cls in c.Dir, c.File, c.FilesystemObject: + with self.subTest(cls): + d = os.path.join("not", "a", "real", "path", "I", "hope") + + class Schema(Config): + option = cls() + + conf = self.get_config(Schema, {'option': d}) + assert_type(conf.option, str) + self.assertEqual(conf.option, os.path.abspath(d)) + + def test_missing_but_required(self) -> None: + for cls in c.Dir, c.File, c.FilesystemObject: + with self.subTest(cls): + d = os.path.join("not", "a", "real", "path", "I", "hope") + + class Schema(Config): + option = cls(exists=True) + + with self.expect_error(option=re.compile(r"The path '.+' isn't an existing .+")): + self.get_config(Schema, {'option': d}) + + def test_not_a_dir(self) -> None: + d = __file__ + + class Schema(Config): + option = c.Dir(exists=True) + + with self.expect_error(option=re.compile(r"The path '.+' isn't an existing directory.")): + self.get_config(Schema, {'option': d}) + + def test_not_a_file(self) -> None: + d = os.path.dirname(__file__) + + class Schema(Config): + option = c.File(exists=True) + + with self.expect_error(option=re.compile(r"The path '.+' isn't an existing file.")): + self.get_config(Schema, {'option': d}) + + def test_incorrect_type_error(self) -> None: + for cls in c.Dir, c.File, c.FilesystemObject: + with self.subTest(cls): + + class Schema(Config): + option = cls() + + with self.expect_error( + option="Expected type: but received: " + ): + self.get_config(Schema, {'option': 1}) + with self.expect_error( + option="Expected type: but received: " + ): + self.get_config(Schema, {'option': []}) + + def test_with_unicode(self) -> None: + for cls in c.Dir, c.File, c.FilesystemObject: + with self.subTest(cls): + + class Schema(Config): + dir = cls() + + conf = self.get_config(Schema, {'dir': 'юникод'}) + self.assertIsInstance(conf.dir, str) + + def test_dir_bytes(self) -> None: + class Schema(Config): + dir = c.Dir() + + with self.expect_error(dir="Expected type: but received: "): + self.get_config(Schema, {'dir': b'foo'}) + + def test_config_dir_prepended(self) -> None: + for cls in c.Dir, c.File, c.FilesystemObject: + with self.subTest(cls): + base_path = os.path.dirname(os.path.abspath(__file__)) + + class Schema(Config): + dir = cls() + + conf = self.get_config( + Schema, + {'dir': 'foo'}, + config_file_path=os.path.join(base_path, 'mkdocs.yml'), + ) + self.assertEqual(conf.dir, os.path.join(base_path, 'foo')) + + def test_site_dir_is_config_dir_fails(self) -> None: + class Schema(Config): + dir = c.DocsDir() + + with self.expect_error( + dir="The 'dir' should not be the parent directory of the config file. " + "Use a child directory instead so that the 'dir' is a sibling of the config file." + ): + self.get_config( + Schema, + {'dir': '.'}, + config_file_path=os.path.join(os.path.abspath('.'), 'mkdocs.yml'), + ) + + +class ListOfPathsTest(TestCase): + def test_valid_path(self) -> None: + paths = [os.path.dirname(__file__)] + + class Schema(Config): + option = c.ListOfPaths() + + self.get_config(Schema, {'option': paths}) + + def test_missing_path(self) -> None: + paths = [os.path.join("does", "not", "exist", "i", "hope")] + + class Schema(Config): + option = c.ListOfPaths() + + with self.expect_error( + option=f"The path '{paths[0]}' isn't an existing file or directory." + ): + self.get_config(Schema, {'option': paths}) + + def test_non_path(self) -> None: + paths = [os.path.dirname(__file__), None] + + class Schema(Config): + option = c.ListOfPaths() + + with self.expect_error( + option="Expected type: but received: " + ): + self.get_config(Schema, {'option': paths}) + + def test_empty_list(self) -> None: + class Schema(Config): + option = c.ListOfPaths() + + conf = self.get_config(Schema, {'option': []}) + assert_type(conf.option, List[str]) + self.assertEqual(conf.option, []) + + def test_none(self) -> None: + class Schema(Config): + option = c.ListOfPaths() + + with self.expect_error(option="Required configuration not provided."): + self.get_config(Schema, {'option': None}) + + def test_non_list(self) -> None: + paths = os.path.dirname(__file__) + + class Schema(Config): + option = c.ListOfPaths() + + with self.expect_error(option="Expected a list of items, but a was given."): + self.get_config(Schema, {'option': paths}) + + def test_file(self) -> None: + paths = [__file__] + + class Schema(Config): + option = c.ListOfPaths() + + conf = self.get_config(Schema, {'option': paths}) + assert_type(conf.option, List[str]) + + @tempdir() + def test_paths_localized_to_config(self, base_path) -> None: + with open(os.path.join(base_path, 'foo'), 'w') as f: + f.write('hi') + + class Schema(Config): + watch = c.ListOfPaths() + + conf = self.get_config( + Schema, + {'watch': ['foo']}, + config_file_path=os.path.join(base_path, 'mkdocs.yml'), + ) + + self.assertEqual(conf.watch, [os.path.join(base_path, 'foo')]) + + +class SiteDirTest(TestCase): + class Schema(Config): + site_dir = c.SiteDir() + docs_dir = c.Dir() + + def test_doc_dir_in_site_dir(self) -> None: + j = os.path.join + # The parent dir is not the same on every system, so use the actual dir name + parent_dir = mkdocs.__file__.split(os.sep)[-3] + + test_configs = ( + {'docs_dir': j('site', 'docs'), 'site_dir': 'site'}, + {'docs_dir': 'docs', 'site_dir': '.'}, + {'docs_dir': '.', 'site_dir': '.'}, + {'docs_dir': 'docs', 'site_dir': ''}, + {'docs_dir': '', 'site_dir': ''}, + {'docs_dir': j('..', parent_dir, 'docs'), 'site_dir': 'docs'}, + {'docs_dir': 'docs', 'site_dir': '/'}, + ) + + for test_config in test_configs: + with self.subTest(test_config): + with self.expect_error( + site_dir=re.compile(r"The 'docs_dir' should not be within the 'site_dir'.*") + ): + self.get_config(self.Schema, test_config) + + def test_site_dir_in_docs_dir(self) -> None: + j = os.path.join + + test_configs = ( + {'docs_dir': 'docs', 'site_dir': j('docs', 'site')}, + {'docs_dir': '.', 'site_dir': 'site'}, + {'docs_dir': '', 'site_dir': 'site'}, + {'docs_dir': '/', 'site_dir': 'site'}, + ) + + for test_config in test_configs: + with self.subTest(test_config): + with self.expect_error( + site_dir=re.compile(r"The 'site_dir' should not be within the 'docs_dir'.*") + ): + self.get_config(self.Schema, test_config) + + def test_common_prefix(self) -> None: + """Legitimate settings with common prefixes should not fail validation.""" + + test_configs = ( + {'docs_dir': 'docs', 'site_dir': 'docs-site'}, + {'docs_dir': 'site-docs', 'site_dir': 'site'}, + ) + + for test_config in test_configs: + with self.subTest(test_config): + self.get_config(self.Schema, test_config) + + +class ThemeTest(TestCase): + def test_theme_as_string(self) -> None: + class Schema(Config): + option = c.Theme() + + conf = self.get_config(Schema, {'option': "mkdocs"}) + assert_type(conf.option, Theme) + assert_type(conf.option.name, Optional[str]) + self.assertEqual(conf.option.name, 'mkdocs') + + def test_uninstalled_theme_as_string(self) -> None: + class Schema(Config): + theme = c.Theme() + plugins = c.Plugins(theme_key='theme') + + with self.expect_error( + theme=re.compile( + r"Unrecognised theme name: 'mkdocs2'. The available installed themes are: .+" + ) + ): + self.get_config(Schema, {'theme': "mkdocs2", 'plugins': "search"}) + + def test_theme_default(self) -> None: + class Schema(Config): + option = c.Theme(default='mkdocs') + + conf = self.get_config(Schema, {'option': None}) + self.assertEqual(conf.option.name, 'mkdocs') + + def test_theme_as_simple_config(self) -> None: + config = { + 'name': 'mkdocs', + } + + class Schema(Config): + option = c.Theme() + + conf = self.get_config(Schema, {'option': config}) + self.assertEqual(conf.option.name, 'mkdocs') + + @tempdir() + def test_theme_as_complex_config(self, custom_dir) -> None: + config = { + 'name': 'mkdocs', + 'custom_dir': custom_dir, + 'static_templates': ['sitemap.html'], + 'show_sidebar': False, + } + + class Schema(Config): + option = c.Theme() + + conf = self.get_config(Schema, {'option': config}) + self.assertEqual(conf.option.name, 'mkdocs') + self.assertEqual(conf.option.custom_dir, custom_dir) + self.assertIn(custom_dir, conf.option.dirs) + self.assertEqual( + conf.option.static_templates, + {'404.html', 'sitemap.xml', 'sitemap.html'}, + ) + self.assertEqual(conf.option['show_sidebar'], False) + + def test_theme_name_is_none(self) -> None: + config = { + 'name': None, + } + + class Schema(Config): + option = c.Theme() + + with self.expect_error(option="At least one of 'name' or 'custom_dir' must be defined."): + self.get_config(Schema, {'option': config}) + + def test_theme_config_missing_name(self) -> None: + config = { + 'custom_dir': 'custom', + } + + class Schema(Config): + option = c.Theme() + + with self.expect_error(option="No theme name set."): + self.get_config(Schema, {'option': config}) + + def test_uninstalled_theme_as_config(self) -> None: + config = { + 'name': 'mkdocs2', + } + + class Schema(Config): + option = c.Theme() + + with self.expect_error( + option=re.compile( + r"Unrecognised theme name: 'mkdocs2'. The available installed themes are: .+" + ) + ): + self.get_config(Schema, {'option': config}) + + def test_theme_invalid_type(self) -> None: + config = ['mkdocs2'] + + class Schema(Config): + option = c.Theme() + + with self.expect_error( + option="Invalid type . Expected a string or key/value pairs." + ): + self.get_config(Schema, {'option': config}) + + def test_post_validation_none_theme_name_and_missing_custom_dir(self) -> None: + config = { + 'theme': { + 'name': None, + }, + } + + class Schema(Config): + theme = c.Theme() + + with self.expect_error(theme="At least one of 'name' or 'custom_dir' must be defined."): + self.get_config(Schema, config) + + @tempdir() + def test_post_validation_inexisting_custom_dir(self, abs_base_path) -> None: + path = os.path.join(abs_base_path, 'inexisting_custom_dir') + config = { + 'theme': { + 'name': None, + 'custom_dir': path, + }, + } + + class Schema(Config): + theme = c.Theme() + + with self.expect_error(theme=f"The path set in custom_dir ('{path}') does not exist."): + self.get_config(Schema, config) + + def test_post_validation_locale_none(self) -> None: + config = { + 'theme': { + 'name': 'mkdocs', + 'locale': None, + }, + } + + class Schema(Config): + theme = c.Theme() + + with self.expect_error(theme="'locale' must be a string."): + self.get_config(Schema, config) + + def test_post_validation_locale_invalid_type(self) -> None: + config = { + 'theme': { + 'name': 'mkdocs', + 'locale': 0, + }, + } + + class Schema(Config): + theme = c.Theme() + + with self.expect_error(theme="'locale' must be a string."): + self.get_config(Schema, config) + + def test_post_validation_locale(self) -> None: + config = { + 'theme': { + 'name': 'mkdocs', + 'locale': 'fr', + }, + } + + class Schema(Config): + theme = c.Theme() + + conf = self.get_config(Schema, config) + self.assertEqual(conf.theme.locale.language, 'fr') + + +class NavTest(TestCase): + class Schema(Config): + option = c.Nav() + + def test_old_format(self) -> None: + with self.expect_error( + option="Expected nav item to be a string or dict, got a list: ['index.md']" + ): + self.get_config(self.Schema, {'option': [['index.md']]}) + + def test_provided_dict(self) -> None: + conf = self.get_config(self.Schema, {'option': ['index.md', {"Page": "page.md"}]}) + self.assertEqual(conf.option, ['index.md', {'Page': 'page.md'}]) + + def test_provided_empty(self) -> None: + conf = self.get_config(self.Schema, {'option': []}) + self.assertEqual(conf.option, None) + + def test_normal_nav(self) -> None: + nav_yaml = textwrap.dedent( + '''\ + - Home: index.md + - getting-started.md + - User Guide: + - Overview: user-guide/index.md + - Installation: user-guide/installation.md + ''' + ) + nav = yaml_load(io.StringIO(nav_yaml)) + + conf = self.get_config(self.Schema, {'option': nav}) + self.assertEqual(conf.option, nav) + + def test_invalid_type_dict(self) -> None: + with self.expect_error(option="Expected nav to be a list, got a dict: {}"): + self.get_config(self.Schema, {'option': {}}) + + def test_invalid_type_int(self) -> None: + with self.expect_error(option="Expected nav to be a list, got a int: 5"): + self.get_config(self.Schema, {'option': 5}) + + def test_invalid_item_int(self) -> None: + with self.expect_error(option="Expected nav item to be a string or dict, got a int: 1"): + self.get_config(self.Schema, {'option': [1]}) + + def test_invalid_item_none(self) -> None: + with self.expect_error(option="Expected nav item to be a string or dict, got None"): + self.get_config(self.Schema, {'option': [None]}) + + def test_invalid_children_config_int(self) -> None: + with self.expect_error(option="Expected nav to be a list, got a int: 1"): + self.get_config(self.Schema, {'option': [{"foo.md": [{"bar.md": 1}]}]}) + + def test_invalid_children_config_none(self) -> None: + with self.expect_error(option="Expected nav to be a list, got None"): + self.get_config(self.Schema, {'option': [{"foo.md": None}]}) + + def test_invalid_children_empty_dict(self) -> None: + nav = ['foo', {}] + with self.expect_error(option="Expected nav item to be a dict of size 1, got a dict: {}"): + self.get_config(self.Schema, {'option': nav}) + + def test_invalid_nested_list(self) -> None: + nav = [{'aaa': [[{"bbb": "user-guide/index.md"}]]}] + with self.expect_error( + option="Expected nav item to be a string or dict, got a list: [{'bbb': 'user-guide/index.md'}]" + ): + self.get_config(self.Schema, {'option': nav}) + + def test_invalid_children_oversized_dict(self) -> None: + nav = [{"aaa": [{"bbb": "user-guide/index.md", "ccc": "user-guide/installation.md"}]}] + with self.expect_error( + option="Expected nav item to be a dict of size 1, got dict with keys ('bbb', 'ccc')" + ): + self.get_config(self.Schema, {'option': nav}) + + def test_warns_for_dict(self) -> None: + self.get_config( + self.Schema, + {'option': [{"a": {"b": "c.md", "d": "e.md"}}]}, + warnings=dict(option="Expected nav to be a list, got dict with keys ('b', 'd')"), + ) + + +class PrivateTest(TestCase): + def test_defined(self) -> None: + class Schema(Config): + option = c.Private[Any]() + + with self.expect_error(option="For internal use only."): + self.get_config(Schema, {'option': 'somevalue'}) + + +class SubConfigTest(TestCase): + def test_subconfig_wrong_type(self) -> None: + # Test that an error is raised if subconfig does not receive a dict + class Schema(Config): + option = c.SubConfig() + + for val in "not_a_dict", ("not_a_dict",), ["not_a_dict"]: + with self.subTest(val): + with self.expect_error( + option=re.compile( + r"The configuration is invalid. Expected a key-value mapping " + r"\(dict\) but received: .+" + ) + ): + self.get_config(Schema, {'option': val}) + + def test_subconfig_unknown_option(self) -> None: + class Schema(Config): + option = c.SubConfig(validate=True) + + conf = self.get_config( + Schema, + {'option': {'unknown': 0}}, + warnings=dict(option="Sub-option 'unknown': Unrecognised configuration name: unknown"), + ) + self.assertEqual(conf.option, {"unknown": 0}) + + def test_subconfig_invalid_option(self) -> None: + class Sub(Config): + cc = c.Choice(('foo', 'bar')) + + class Schema(Config): + option = c.SubConfig(Sub) + + with self.expect_error( + option="Sub-option 'cc': Expected one of: ('foo', 'bar') but received: True" + ): + self.get_config(Schema, {'option': {'cc': True}}) + + def test_subconfig_normal(self) -> None: + class Sub(Config): + cc = c.Choice(('foo', 'bar')) + + class Schema(Config): + option = c.SubConfig(Sub) + + conf = self.get_config(Schema, {'option': {'cc': 'foo'}}) + assert_type(conf.option, Sub) + self.assertEqual(conf.option, {'cc': 'foo'}) + assert_type(conf.option.cc, str) + self.assertEqual(conf.option.cc, 'foo') + + def test_subconfig_with_multiple_items(self) -> None: + # This had a bug where subsequent items would get merged into the same dict. + class Sub(Config): + value = c.Type(str) + + class Schema(Config): + the_items = c.ListOfItems(c.SubConfig(Sub)) + + conf = self.get_config( + Schema, + { + 'the_items': [ + {'value': 'a'}, + {'value': 'b'}, + ] + }, + ) + assert_type(conf.the_items, List[Sub]) + self.assertEqual(conf.the_items, [{'value': 'a'}, {'value': 'b'}]) + assert_type(conf.the_items[1].value, str) + self.assertEqual(conf.the_items[1].value, 'b') + + def test_optional(self) -> None: + class Sub(Config): + opt = c.Optional(c.Type(int)) + + class Schema(Config): + sub = c.Optional(c.ListOfItems(c.SubConfig(Sub))) + + conf = self.get_config(Schema, {}) + self.assertEqual(conf.sub, None) + + conf = self.get_config(Schema, {'sub': None}) + self.assertEqual(conf.sub, None) + + conf = self.get_config(Schema, {'sub': [{'opt': 1}, {}]}) + assert_type(conf.sub, Optional[List[Sub]]) + self.assertEqual(conf.sub, [{'opt': 1}, {'opt': None}]) + assert conf.sub is not None + assert_type(conf.sub[0].opt, Optional[int]) + self.assertEqual(conf.sub[0].opt, 1) + + conf = self.get_config(Schema, {'sub': []}) + + conf = self.get_config(Schema, {'sub': [{'opt': 1}, {'opt': 2}]}) + self.assertEqual(conf.sub, [{'opt': 1}, {'opt': 2}]) + + def test_required(self) -> None: + class Sub(Config): + opt = c.Type(int) + + class Schema(Config): + sub = c.ListOfItems(c.SubConfig(Sub)) + + with self.expect_error(sub="Required configuration not provided."): + conf = self.get_config(Schema, {}) + + with self.expect_error(sub="Required configuration not provided."): + conf = self.get_config(Schema, {'sub': None}) + + with self.expect_error( + sub="Sub-option 'opt': Expected type: but received: " + ): + conf = self.get_config(Schema, {'sub': [{'opt': 'asdf'}, {}]}) + + conf = self.get_config(Schema, {'sub': []}) + + conf = self.get_config(Schema, {'sub': [{'opt': 1}, {'opt': 2}]}) + assert_type(conf.sub, List[Sub]) + self.assertEqual(conf.sub, [{'opt': 1}, {'opt': 2}]) + assert_type(conf.sub[0].opt, int) + self.assertEqual(conf.sub[0].opt, 1) + + with self.expect_error( + sub="Sub-option 'opt': Expected type: but received: " + ): + self.get_config(Schema, {'sub': [{'opt': 'z'}, {'opt': 2}]}) + + with self.expect_error( + sub="Sub-option 'opt': Expected type: but received: " + ): + conf = self.get_config(Schema, {'sub': [{'opt': 'z'}, {'opt': 2}]}) + + with self.expect_error( + sub="The configuration is invalid. Expected a key-value mapping " + "(dict) but received: " + ): + conf = self.get_config(Schema, {'sub': [1, 2]}) + + def test_default(self) -> None: + class Sub(Config): + opt = c.Type(int) + + class Schema(Config): + sub = c.ListOfItems(c.SubConfig(Sub), default=[]) + + conf = self.get_config(Schema, {}) + assert_type(conf.sub, List[Sub]) + self.assertEqual(conf.sub, []) + + with self.expect_error(sub="Required configuration not provided."): + conf = self.get_config(Schema, {'sub': None}) + + def test_config_file_path_pass_through(self) -> None: + """Necessary to ensure FilesystemObject validates the correct path""" + + passed_config_path = None + + class SubType(c.BaseConfigOption): + def pre_validation(self, config: Config, key_name: str) -> None: + nonlocal passed_config_path + passed_config_path = config.config_file_path + + class Sub(Config): + opt = SubType() + + class Schema(Config): + sub = c.ListOfItems(c.SubConfig(Sub), default=[]) + + config_path = "foo/mkdocs.yaml" + self.get_config(Schema, {"sub": [{"opt": "bar"}]}, config_file_path=config_path) + self.assertEqual(passed_config_path, config_path) + + +class NestedSubConfigTest(TestCase): + def defaults(self): + return { + 'nav': { + 'omitted_files': logging.INFO, + 'not_found': logging.WARNING, + 'absolute_links': logging.INFO, + }, + 'links': { + 'not_found': logging.WARNING, + 'absolute_links': logging.INFO, + 'unrecognized_links': logging.INFO, + }, + } + + class Schema(Config): + validation = c.PropagatingSubConfig[defaults.MkDocsConfig.Validation]() + + def test_unspecified(self) -> None: + for cfg in {}, {'validation': {}}: + with self.subTest(cfg): + conf = self.get_config( + self.Schema, + {}, + ) + self.assertEqual(conf.validation, self.defaults()) + + def test_sets_nested_and_not_nested(self) -> None: + conf = self.get_config( + self.Schema, + {'validation': {'not_found': 'ignore', 'links': {'absolute_links': 'warn'}}}, + ) + expected = self.defaults() + expected['nav']['not_found'] = logging.DEBUG + expected['links']['not_found'] = logging.DEBUG + expected['links']['absolute_links'] = logging.WARNING + self.assertEqual(conf.validation, expected) + + def test_sets_nested_different(self) -> None: + conf = self.get_config( + self.Schema, + {'validation': {'not_found': 'ignore', 'links': {'not_found': 'warn'}}}, + ) + expected = self.defaults() + expected['nav']['not_found'] = logging.DEBUG + expected['links']['not_found'] = logging.WARNING + self.assertEqual(conf.validation, expected) + + def test_sets_only_one_nested(self) -> None: + conf = self.get_config( + self.Schema, + {'validation': {'omitted_files': 'ignore'}}, + ) + expected = self.defaults() + expected['nav']['omitted_files'] = logging.DEBUG + self.assertEqual(conf.validation, expected) + + def test_sets_nested_not_dict(self) -> None: + with self.expect_error( + validation="Sub-option 'links': Sub-option 'unrecognized_links': Expected a string, but a was given." + ): + self.get_config( + self.Schema, + {'validation': {'unrecognized_links': [], 'links': {'absolute_links': 'warn'}}}, + ) + + def test_wrong_key_nested(self) -> None: + conf = self.get_config( + self.Schema, + {'validation': {'foo': 'warn', 'not_found': 'warn'}}, + warnings=dict(validation="Sub-option 'foo': Unrecognised configuration name: foo"), + ) + expected = self.defaults() + expected['nav']['not_found'] = logging.WARNING + expected['links']['not_found'] = logging.WARNING + expected['foo'] = 'warn' + self.assertEqual(conf.validation, expected) + + def test_wrong_type_nested(self) -> None: + with self.expect_error( + validation="Sub-option 'nav': Sub-option 'omitted_files': Expected one of ['warn', 'info', 'ignore'], got 'hi'" + ): + self.get_config( + self.Schema, + {'validation': {'omitted_files': 'hi'}}, + ) + + +class MarkdownExtensionsTest(TestCase): + @patch('markdown.Markdown') + def test_simple_list(self, mock_md) -> None: + class Schema(Config): + markdown_extensions = c.MarkdownExtensions() + mdx_configs = c.Private[Dict[str, dict]]() + + config = { + 'markdown_extensions': ['foo', 'bar'], + } + conf = self.get_config(Schema, config) + assert_type(conf.markdown_extensions, List[str]) + assert_type(conf.mdx_configs, Dict[str, dict]) + self.assertEqual(conf.markdown_extensions, ['foo', 'bar']) + self.assertEqual(conf.mdx_configs, {}) + + @patch('markdown.Markdown') + def test_list_dicts(self, mock_md) -> None: + class Schema(Config): + markdown_extensions = c.MarkdownExtensions() + mdx_configs = c.Private[Dict[str, dict]]() + + config = { + 'markdown_extensions': [ + {'foo': {'foo_option': 'foo value'}}, + {'bar': {'bar_option': 'bar value'}}, + {'baz': None}, + ] + } + conf = self.get_config(Schema, config) + self.assertEqual(conf.markdown_extensions, ['foo', 'bar', 'baz']) + self.assertEqual( + conf.mdx_configs, + { + 'foo': {'foo_option': 'foo value'}, + 'bar': {'bar_option': 'bar value'}, + }, + ) + + @patch('markdown.Markdown') + def test_mixed_list(self, mock_md) -> None: + class Schema(Config): + markdown_extensions = c.MarkdownExtensions() + mdx_configs = c.Private[Dict[str, dict]]() + + config = { + 'markdown_extensions': [ + 'foo', + {'bar': {'bar_option': 'bar value'}}, + ] + } + conf = self.get_config(Schema, config) + self.assertEqual(conf.markdown_extensions, ['foo', 'bar']) + self.assertEqual( + conf.mdx_configs, + { + 'bar': {'bar_option': 'bar value'}, + }, + ) + + @patch('markdown.Markdown') + def test_dict_of_dicts(self, mock_md) -> None: + class Schema(Config): + markdown_extensions = c.MarkdownExtensions() + mdx_configs = c.Private[Dict[str, dict]]() + + config = { + 'markdown_extensions': { + 'foo': {'foo_option': 'foo value'}, + 'bar': {'bar_option': 'bar value'}, + 'baz': {}, + } + } + conf = self.get_config(Schema, config) + self.assertEqual(conf.markdown_extensions, ['foo', 'bar', 'baz']) + self.assertEqual( + conf.mdx_configs, + { + 'foo': {'foo_option': 'foo value'}, + 'bar': {'bar_option': 'bar value'}, + }, + ) + + @patch('markdown.Markdown') + def test_builtins(self, mock_md) -> None: + class Schema(Config): + markdown_extensions = c.MarkdownExtensions(builtins=['meta', 'toc']) + mdx_configs = c.Private[Dict[str, dict]]() + + config = { + 'markdown_extensions': ['foo', 'bar'], + } + conf = self.get_config(Schema, config) + self.assertEqual(conf.markdown_extensions, ['meta', 'toc', 'foo', 'bar']) + self.assertEqual(conf.mdx_configs, {}) + + def test_duplicates(self) -> None: + class Schema(Config): + markdown_extensions = c.MarkdownExtensions(builtins=['meta', 'toc']) + mdx_configs = c.Private[Dict[str, dict]]() + + config = { + 'markdown_extensions': ['meta', 'toc'], + } + conf = self.get_config(Schema, config) + self.assertEqual(conf.markdown_extensions, ['meta', 'toc']) + self.assertEqual(conf.mdx_configs, {}) + + def test_builtins_config(self) -> None: + class Schema(Config): + markdown_extensions = c.MarkdownExtensions(builtins=['meta', 'toc']) + mdx_configs = c.Private[Dict[str, dict]]() + + config = { + 'markdown_extensions': [ + {'toc': {'permalink': True}}, + ], + } + conf = self.get_config(Schema, config) + self.assertEqual(conf.markdown_extensions, ['meta', 'toc']) + self.assertEqual(conf.mdx_configs, {'toc': {'permalink': True}}) + + @patch('markdown.Markdown') + def test_configkey(self, mock_md) -> None: + class Schema(Config): + markdown_extensions = c.MarkdownExtensions(configkey='bar') + bar = c.Private[Dict[str, dict]]() + + config = { + 'markdown_extensions': [ + {'foo': {'foo_option': 'foo value'}}, + ] + } + conf = self.get_config(Schema, config) + self.assertEqual(conf.markdown_extensions, ['foo']) + self.assertEqual( + conf.bar, + { + 'foo': {'foo_option': 'foo value'}, + }, + ) + + def test_missing_default(self) -> None: + class Schema(Config): + markdown_extensions = c.MarkdownExtensions() + mdx_configs = c.Private[Dict[str, dict]]() + + conf = self.get_config(Schema, {}) + self.assertEqual(conf.markdown_extensions, []) + self.assertEqual(conf.mdx_configs, {}) + + def test_none(self) -> None: + class Schema(Config): + markdown_extensions = c.MarkdownExtensions(default=[]) + mdx_configs = c.Private[Dict[str, dict]]() + + config = { + 'markdown_extensions': None, + } + conf = self.get_config(Schema, config) + self.assertEqual(conf.markdown_extensions, []) + self.assertEqual(conf.mdx_configs, {}) + + @patch('markdown.Markdown') + def test_not_list(self, mock_md) -> None: + class Schema(Config): + option = c.MarkdownExtensions() + + with self.expect_error(option="Invalid Markdown Extensions configuration"): + self.get_config(Schema, {'option': 'not a list'}) + + @patch('markdown.Markdown') + def test_invalid_config_option(self, mock_md) -> None: + class Schema(Config): + markdown_extensions = c.MarkdownExtensions() + + config = { + 'markdown_extensions': [ + {'foo': 'not a dict'}, + ], + } + with self.expect_error( + markdown_extensions="Invalid config options for Markdown Extension 'foo'." + ): + self.get_config(Schema, config) + + @patch('markdown.Markdown') + def test_invalid_config_item(self, mock_md) -> None: + class Schema(Config): + markdown_extensions = c.MarkdownExtensions() + + config = { + 'markdown_extensions': [ + ['not a dict'], + ], + } + with self.expect_error(markdown_extensions="Invalid Markdown Extensions configuration"): + self.get_config(Schema, config) + + @patch('markdown.Markdown') + def test_invalid_dict_item(self, mock_md) -> None: + class Schema(Config): + markdown_extensions = c.MarkdownExtensions() + + config = { + 'markdown_extensions': [ + {'key1': 'value', 'key2': 'too many keys'}, + ], + } + with self.expect_error(markdown_extensions="Invalid Markdown Extensions configuration"): + self.get_config(Schema, config) + + def test_unknown_extension(self) -> None: + class Schema(Config): + markdown_extensions = c.MarkdownExtensions() + + config = { + 'markdown_extensions': ['unknown'], + } + with self.expect_error( + markdown_extensions=re.compile(r"Failed to load extension 'unknown'.\n.+") + ): + self.get_config(Schema, config) + + def test_multiple_markdown_config_instances(self) -> None: + # This had a bug where an extension config would persist to separate + # config instances that didn't specify extensions. + class Schema(Config): + markdown_extensions = c.MarkdownExtensions() + mdx_configs = c.Private[Dict[str, dict]]() + + conf = self.get_config( + Schema, + { + 'markdown_extensions': [{'toc': {'permalink': '##'}}], + }, + ) + self.assertEqual(conf.mdx_configs['toc'], {'permalink': '##'}) + + conf = self.get_config( + Schema, + {}, + ) + self.assertIsNone(conf.mdx_configs.get('toc')) + + +class _FakePluginConfig(Config): + foo = c.Type(str, default='default foo') + bar = c.Type(int, default=0) + dir = c.Optional(c.Dir(exists=False)) + + +class FakePlugin(BasePlugin[_FakePluginConfig]): + pass + + +class _FakePlugin2Config(_FakePluginConfig): + depr = c.Deprecated() + + +class FakePlugin2(BasePlugin[_FakePlugin2Config]): + supports_multiple_instances = True + + +class ThemePlugin(BasePlugin[_FakePluginConfig]): + pass + + +class ThemePlugin2(BasePlugin[_FakePluginConfig]): + pass + + +class FakeEntryPoint: + def __init__(self, name, cls): + self.name = name + self.cls = cls + + def load(self): + return self.cls + + +@patch( + 'mkdocs.plugins.entry_points', + return_value=[ + FakeEntryPoint('sample', FakePlugin), + FakeEntryPoint('sample2', FakePlugin2), + FakeEntryPoint('readthedocs/sub_plugin', ThemePlugin), + FakeEntryPoint('overridden', FakePlugin2), + FakeEntryPoint('readthedocs/overridden', ThemePlugin2), + ], +) +class PluginsTest(TestCase): + def test_plugin_config_without_options(self, mock_class) -> None: + class Schema(Config): + plugins = c.Plugins() + + cfg = { + 'plugins': ['sample'], + } + conf = self.get_config(Schema, cfg) + + assert_type(conf.plugins, PluginCollection) + self.assertIsInstance(conf.plugins, PluginCollection) + self.assertIn('sample', conf.plugins) + + plugin = conf.plugins['sample'] + assert_type(plugin, BasePlugin) + self.assertIsInstance(plugin, FakePlugin) + self.assertIsInstance(plugin.config, _FakePluginConfig) + expected = { + 'foo': 'default foo', + 'bar': 0, + 'dir': None, + } + self.assertEqual(plugin.config, expected) + + def test_plugin_config_with_options(self, mock_class) -> None: + class Schema(Config): + plugins = c.Plugins() + + cfg = { + 'plugins': [ + { + 'sample': { + 'foo': 'foo value', + 'bar': 42, + }, + } + ], + } + conf = self.get_config(Schema, cfg) + + self.assertIsInstance(conf.plugins, PluginCollection) + self.assertIn('sample', conf.plugins) + self.assertIsInstance(conf.plugins['sample'], BasePlugin) + expected = { + 'foo': 'foo value', + 'bar': 42, + 'dir': None, + } + self.assertEqual(conf.plugins['sample'].config, expected) + + def test_plugin_config_as_dict(self, mock_class) -> None: + class Schema(Config): + plugins = c.Plugins() + + cfg = { + 'plugins': { + 'sample': { + 'foo': 'foo value', + 'bar': 42, + }, + }, + } + conf = self.get_config(Schema, cfg) + + self.assertIsInstance(conf.plugins, PluginCollection) + self.assertIn('sample', conf.plugins) + self.assertIsInstance(conf.plugins['sample'], BasePlugin) + expected = { + 'foo': 'foo value', + 'bar': 42, + 'dir': None, + } + self.assertEqual(conf.plugins['sample'].config, expected) + + def test_plugin_config_with_explicit_theme_namespace(self, mock_class) -> None: + class Schema(Config): + theme = c.Theme(default='mkdocs') + plugins = c.Plugins(theme_key='theme') + + cfg = {'theme': 'readthedocs', 'plugins': ['readthedocs/sub_plugin']} + conf = self.get_config(Schema, cfg) + + self.assertEqual(set(conf.plugins), {'readthedocs/sub_plugin'}) + self.assertIsInstance(conf.plugins['readthedocs/sub_plugin'], ThemePlugin) + + cfg = {'plugins': ['readthedocs/sub_plugin']} + conf = self.get_config(Schema, cfg) + + self.assertEqual(set(conf.plugins), {'readthedocs/sub_plugin'}) + self.assertIsInstance(conf.plugins['readthedocs/sub_plugin'], ThemePlugin) + + def test_plugin_config_with_deduced_theme_namespace(self, mock_class) -> None: + class Schema(Config): + theme = c.Theme(default='mkdocs') + plugins = c.Plugins(theme_key='theme') + + cfg = {'theme': 'readthedocs', 'plugins': ['sub_plugin']} + conf = self.get_config(Schema, cfg) + + self.assertEqual(set(conf.plugins), {'readthedocs/sub_plugin'}) + self.assertIsInstance(conf.plugins['readthedocs/sub_plugin'], ThemePlugin) + + cfg = {'plugins': ['sub_plugin']} + with self.expect_error(plugins='The "sub_plugin" plugin is not installed'): + self.get_config(Schema, cfg) + + def test_plugin_config_with_deduced_theme_namespace_overridden(self, mock_class) -> None: + class Schema(Config): + theme = c.Theme(default='mkdocs') + plugins = c.Plugins(theme_key='theme') + + cfg = {'theme': 'readthedocs', 'plugins': ['overridden']} + conf = self.get_config(Schema, cfg) + + self.assertEqual(set(conf.plugins), {'readthedocs/overridden'}) + self.assertIsInstance(next(iter(conf.plugins.values())), ThemePlugin2) + + cfg = {'plugins': ['overridden']} + conf = self.get_config(Schema, cfg) + + self.assertEqual(set(conf.plugins), {'overridden'}) + self.assertIsInstance(conf.plugins['overridden'], FakePlugin2) + + def test_plugin_config_with_explicit_empty_namespace(self, mock_class) -> None: + class Schema(Config): + theme = c.Theme(default='mkdocs') + plugins = c.Plugins(theme_key='theme') + + cfg = {'theme': 'readthedocs', 'plugins': ['/overridden']} + conf = self.get_config(Schema, cfg) + + self.assertEqual(set(conf.plugins), {'overridden'}) + self.assertIsInstance(next(iter(conf.plugins.values())), FakePlugin2) + + cfg = {'plugins': ['/overridden']} + conf = self.get_config(Schema, cfg) + + self.assertEqual(set(conf.plugins), {'overridden'}) + self.assertIsInstance(conf.plugins['overridden'], FakePlugin2) + + def test_plugin_config_with_multiple_instances(self, mock_class) -> None: + class Schema(Config): + theme = c.Theme(default='mkdocs') + plugins = c.Plugins(theme_key='theme') + + cfg = { + 'plugins': [ + {'sample2': {'foo': 'foo value', 'bar': 42}}, + {'sample2': {'foo': 'foo2 value'}}, + ], + } + conf = self.get_config(Schema, cfg) + + self.assertEqual( + set(conf.plugins), + {'sample2', 'sample2 #2'}, + ) + self.assertEqual(conf.plugins['sample2'].config['bar'], 42) + self.assertEqual(conf.plugins['sample2 #2'].config['bar'], 0) + + def test_plugin_config_with_multiple_instances_and_warning(self, mock_class) -> None: + class Schema(Config): + theme = c.Theme(default='mkdocs') + plugins = c.Plugins(theme_key='theme') + + test_cfgs: list[dict[str, Any]] = [ + { + 'theme': 'readthedocs', + 'plugins': [{'sub_plugin': {}}, {'sample2': {}}, {'sub_plugin': {}}, 'sample2'], + }, + { + 'theme': 'readthedocs', + 'plugins': ['sub_plugin', 'sample2', 'sample2', 'sub_plugin'], + }, + ] + + for cfg in test_cfgs: + conf = self.get_config( + Schema, + cfg, + warnings=dict( + plugins="Plugin 'readthedocs/sub_plugin' was specified multiple times - " + "this is likely a mistake, because the plugin doesn't declare " + "`supports_multiple_instances`." + ), + ) + self.assertEqual( + set(conf.plugins), + {'readthedocs/sub_plugin', 'readthedocs/sub_plugin #2', 'sample2', 'sample2 #2'}, + ) + + def test_plugin_config_empty_list_with_empty_default(self, mock_class) -> None: + class Schema(Config): + plugins = c.Plugins(default=[]) + + cfg: dict[str, Any] = {'plugins': []} + conf = self.get_config(Schema, cfg) + + self.assertIsInstance(conf.plugins, PluginCollection) + self.assertEqual(len(conf.plugins), 0) + + def test_plugin_config_empty_list_with_default(self, mock_class) -> None: + class Schema(Config): + plugins = c.Plugins(default=['sample']) + + # Default is ignored + cfg: dict[str, Any] = {'plugins': []} + conf = self.get_config(Schema, cfg) + + self.assertIsInstance(conf.plugins, PluginCollection) + self.assertEqual(len(conf.plugins), 0) + + def test_plugin_config_none_with_empty_default(self, mock_class) -> None: + class Schema(Config): + plugins = c.Plugins(default=[]) + + cfg = {'plugins': None} + conf = self.get_config(Schema, cfg) + + self.assertIsInstance(conf.plugins, PluginCollection) + self.assertEqual(len(conf.plugins), 0) + + def test_plugin_config_none_with_default(self, mock_class) -> None: + class Schema(Config): + plugins = c.Plugins(default=['sample']) + + # Default is used. + cfg = {'plugins': None} + conf = self.get_config(Schema, cfg) + + self.assertIsInstance(conf.plugins, PluginCollection) + self.assertIn('sample', conf.plugins) + self.assertIsInstance(conf.plugins['sample'], BasePlugin) + expected = { + 'foo': 'default foo', + 'bar': 0, + 'dir': None, + } + self.assertEqual(conf.plugins['sample'].config, expected) + + def test_plugin_config_uninstalled(self, mock_class) -> None: + class Schema(Config): + plugins = c.Plugins() + + cfg = {'plugins': ['uninstalled']} + with self.expect_error(plugins='The "uninstalled" plugin is not installed'): + self.get_config(Schema, cfg) + + def test_plugin_config_not_list(self, mock_class) -> None: + class Schema(Config): + plugins = c.Plugins() + + cfg = {'plugins': 'sample'} + with self.expect_error(plugins="Invalid Plugins configuration. Expected a list or dict."): + self.get_config(Schema, cfg) + + def test_plugin_config_multivalue_dict(self, mock_class) -> None: + class Schema(Config): + plugins = c.Plugins() + + cfg = { + 'plugins': [ + { + 'sample': { + 'foo': 'foo value', + 'bar': 42, + }, + 'extra_key': 'baz', + } + ], + } + with self.expect_error(plugins="Invalid Plugins configuration"): + self.get_config(Schema, cfg) + + cfg = { + 'plugins': [ + {}, + ], + } + with self.expect_error(plugins="Invalid Plugins configuration"): + self.get_config(Schema, cfg) + + def test_plugin_config_not_string_or_dict(self, mock_class) -> None: + class Schema(Config): + plugins = c.Plugins() + + cfg = { + 'plugins': [('not a string or dict',)], + } + with self.expect_error(plugins="'('not a string or dict',)' is not a valid plugin name."): + self.get_config(Schema, cfg) + + def test_plugin_config_options_not_dict(self, mock_class) -> None: + class Schema(Config): + plugins = c.Plugins() + + cfg = { + 'plugins': [{'sample': 'not a dict'}], + } + with self.expect_error(plugins="Invalid config options for the 'sample' plugin."): + self.get_config(Schema, cfg) + + def test_plugin_config_sub_error(self, mock_class) -> None: + class Schema(Config): + plugins = c.Plugins(default=['sample']) + + cfg = { + 'plugins': { + 'sample': {'bar': 'not an int'}, + } + } + with self.expect_error( + plugins="Plugin 'sample' option 'bar': Expected type: but received: " + ): + self.get_config(Schema, cfg) + + def test_plugin_config_sub_warning(self, mock_class) -> None: + class Schema(Config): + plugins = c.Plugins() + + cfg = { + 'plugins': { + 'sample2': {'depr': 'deprecated value'}, + } + } + conf = self.get_config( + Schema, + cfg, + warnings=dict( + plugins="Plugin 'sample2' option 'depr': The configuration option " + "'depr' has been deprecated and will be removed in a future release." + ), + ) + + self.assertIsInstance(conf.plugins, PluginCollection) + self.assertIn('sample2', conf.plugins) + + +class HooksTest(TestCase): + class Schema(Config): + plugins = c.Plugins(default=[]) + hooks = c.Hooks('plugins') + + @tempdir() + def test_hooks(self, src_dir) -> None: + write_file( + b'def on_page_markdown(markdown, **kwargs): return markdown.replace("f", "z")', + os.path.join(src_dir, 'hooks', 'my_hook.py'), + ) + write_file( + b'foo foo', + os.path.join(src_dir, 'docs', 'index.md'), + ) + conf = self.get_config( + self.Schema, + {'hooks': ['hooks/my_hook.py']}, + config_file_path=os.path.join(src_dir, 'mkdocs.yml'), + ) + self.assertIn('hooks/my_hook.py', conf.plugins) + hook = conf.plugins['hooks/my_hook.py'] + self.assertTrue(hasattr(hook, 'on_page_markdown')) + self.assertEqual( + {**conf.plugins.events, 'page_markdown': [hook.on_page_markdown]}, + conf.plugins.events, + ) + self.assertEqual(hook.on_page_markdown('foo foo'), 'zoo zoo') # type: ignore[call-arg] + self.assertFalse(hasattr(hook, 'on_nav')) + + def test_hooks_wrong_type(self) -> None: + with self.expect_error(hooks="Expected a list of items, but a was given."): + self.get_config(self.Schema, {'hooks': 6}) + + with self.expect_error(hooks="Expected type: but received: "): + self.get_config(self.Schema, {'hooks': [7]}) + + +class SchemaTest(TestCase): + def test_copy(self) -> None: + class Schema(Config): + foo = c.MarkdownExtensions() + + copy.deepcopy(Schema()) + + copy.deepcopy(self.get_config(IpAddressTest.Schema, {'option': '1.2.3.4:5678'})) + copy.deepcopy(IpAddressTest.Schema) + copy.deepcopy(IpAddressTest.Schema()) + + copy.deepcopy(self.get_config(EditURITest.Schema, {})) + copy.deepcopy(EditURITest.Schema) + copy.deepcopy(EditURITest.Schema()) + + def test_subclass(self) -> None: + class A(Config): + foo = c.Type(int) + bar = c.Optional(c.Type(str)) + + class B(A): + baz = c.ListOfItems(c.Type(str)) + + conf = self.get_config(B, {'foo': 1, 'baz': ['b']}) + assert_type(conf.foo, int) + self.assertEqual(conf.foo, 1) + assert_type(conf.bar, Optional[str]) + self.assertEqual(conf.bar, None) + assert_type(conf.baz, List[str]) + self.assertEqual(conf.baz, ['b']) + + with self.expect_error(baz="Required configuration not provided."): + self.get_config(B, {'foo': 1}) + with self.expect_error(foo="Required configuration not provided."): + self.get_config(B, {'baz': ['b']}) + + bconf = self.get_config(A, {'foo': 2, 'bar': 'a'}) + assert_type(bconf.foo, int) + self.assertEqual(bconf.foo, 2) + self.assertEqual(bconf.bar, 'a') diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/config/config_tests.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/config/config_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..54693188c1b4cef148c3bd808410814ddd05362a --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/config/config_tests.py @@ -0,0 +1,266 @@ +#!/usr/bin/env python + +import os +import unittest + +import mkdocs +from mkdocs import config +from mkdocs.config import config_options as c +from mkdocs.config import defaults +from mkdocs.config.base import ValidationError +from mkdocs.exceptions import ConfigurationError +from mkdocs.localization import parse_locale +from mkdocs.tests.base import dedent, tempdir + + +class ConfigTests(unittest.TestCase): + def test_missing_config_file(self): + with self.assertRaises(ConfigurationError): + config.load_config(config_file='bad_filename.yaml') + + def test_missing_site_name(self): + conf = defaults.MkDocsConfig() + conf.load_dict({}) + errors, warnings = conf.validate() + self.assertEqual( + errors, [('site_name', ValidationError("Required configuration not provided."))] + ) + self.assertEqual(warnings, []) + + def test_nonexistant_config(self): + with self.assertRaises(ConfigurationError): + config.load_config(config_file='/path/that/is/not/real') + + @tempdir() + def test_invalid_config(self, temp_path): + file_contents = dedent( + """ + - ['index.md', 'Introduction'] + - ['index.md', 'Introduction'] + - ['index.md', 'Introduction'] + """ + ) + config_path = os.path.join(temp_path, 'foo.yml') + with open(config_path, 'w') as config_file: + config_file.write(file_contents) + + with self.assertRaises(ConfigurationError): + config.load_config(config_file=open(config_file.name, 'rb')) + + @tempdir() + def test_config_option(self, temp_path): + """ + Users can explicitly set the config file using the '--config' option. + Allows users to specify a config other than the default `mkdocs.yml`. + """ + expected_result = { + 'site_name': 'Example', + 'nav': [{'Introduction': 'index.md'}], + } + file_contents = dedent( + """ + site_name: Example + nav: + - 'Introduction': 'index.md' + """ + ) + config_path = os.path.join(temp_path, 'mkdocs.yml') + with open(config_path, 'w') as config_file: + config_file.write(file_contents) + os.mkdir(os.path.join(temp_path, 'docs')) + + result = config.load_config(config_file=config_file.name) + self.assertEqual(result['site_name'], expected_result['site_name']) + self.assertEqual(result['nav'], expected_result['nav']) + + @tempdir() + @tempdir() + def test_theme(self, mytheme, custom): + configs = [ + {}, # default theme + {"theme": "readthedocs"}, # builtin theme + {"theme": {'name': 'readthedocs'}}, # builtin as complex + {"theme": {'name': None, 'custom_dir': mytheme}}, # custom only as complex + { + "theme": {'name': 'readthedocs', 'custom_dir': custom} + }, # builtin and custom as complex + { # user defined variables + 'theme': { + 'name': 'mkdocs', + 'locale': 'fr', + 'static_templates': ['foo.html'], + 'show_sidebar': False, + 'some_var': 'bar', + } + }, + ] + + mkdocs_dir = os.path.abspath(os.path.dirname(mkdocs.__file__)) + mkdocs_templates_dir = os.path.join(mkdocs_dir, 'templates') + theme_dir = os.path.abspath(os.path.join(mkdocs_dir, 'themes')) + + results = ( + { + 'dirs': [os.path.join(theme_dir, 'mkdocs'), mkdocs_templates_dir], + 'static_templates': ['404.html', 'sitemap.xml'], + 'vars': { + 'name': 'mkdocs', + 'locale': parse_locale('en'), + 'include_search_page': False, + 'search_index_only': False, + 'analytics': {'gtag': None}, + 'highlightjs': True, + 'hljs_style': 'github', + 'hljs_languages': [], + 'navigation_depth': 2, + 'nav_style': 'primary', + 'shortcuts': {'help': 191, 'next': 78, 'previous': 80, 'search': 83}, + }, + }, + { + 'dirs': [os.path.join(theme_dir, 'readthedocs'), mkdocs_templates_dir], + 'static_templates': ['404.html', 'sitemap.xml'], + 'vars': { + 'name': 'readthedocs', + 'locale': parse_locale('en'), + 'include_search_page': True, + 'search_index_only': False, + 'analytics': {'anonymize_ip': False, 'gtag': None}, + 'highlightjs': True, + 'hljs_languages': [], + 'hljs_style': 'github', + 'include_homepage_in_sidebar': True, + 'prev_next_buttons_location': 'bottom', + 'navigation_depth': 4, + 'sticky_navigation': True, + 'logo': None, + 'titles_only': False, + 'collapse_navigation': True, + }, + }, + { + 'dirs': [os.path.join(theme_dir, 'readthedocs'), mkdocs_templates_dir], + 'static_templates': ['404.html', 'sitemap.xml'], + 'vars': { + 'name': 'readthedocs', + 'locale': parse_locale('en'), + 'include_search_page': True, + 'search_index_only': False, + 'analytics': {'anonymize_ip': False, 'gtag': None}, + 'highlightjs': True, + 'hljs_languages': [], + 'hljs_style': 'github', + 'include_homepage_in_sidebar': True, + 'prev_next_buttons_location': 'bottom', + 'navigation_depth': 4, + 'sticky_navigation': True, + 'logo': None, + 'titles_only': False, + 'collapse_navigation': True, + }, + }, + { + 'dirs': [mytheme, mkdocs_templates_dir], + 'static_templates': ['sitemap.xml'], + 'vars': {'name': None, 'locale': parse_locale('en')}, + }, + { + 'dirs': [custom, os.path.join(theme_dir, 'readthedocs'), mkdocs_templates_dir], + 'static_templates': ['404.html', 'sitemap.xml'], + 'vars': { + 'name': 'readthedocs', + 'locale': parse_locale('en'), + 'include_search_page': True, + 'search_index_only': False, + 'analytics': {'anonymize_ip': False, 'gtag': None}, + 'highlightjs': True, + 'hljs_languages': [], + 'hljs_style': 'github', + 'include_homepage_in_sidebar': True, + 'prev_next_buttons_location': 'bottom', + 'navigation_depth': 4, + 'sticky_navigation': True, + 'logo': None, + 'titles_only': False, + 'collapse_navigation': True, + }, + }, + { + 'dirs': [os.path.join(theme_dir, 'mkdocs'), mkdocs_templates_dir], + 'static_templates': ['404.html', 'sitemap.xml', 'foo.html'], + 'vars': { + 'name': 'mkdocs', + 'locale': parse_locale('fr'), + 'show_sidebar': False, + 'some_var': 'bar', + 'include_search_page': False, + 'search_index_only': False, + 'analytics': {'gtag': None}, + 'highlightjs': True, + 'hljs_style': 'github', + 'hljs_languages': [], + 'navigation_depth': 2, + 'nav_style': 'primary', + 'shortcuts': {'help': 191, 'next': 78, 'previous': 80, 'search': 83}, + }, + }, + ) + + for config_contents, result in zip(configs, results): + with self.subTest(config_contents): + conf = config.Config(schema=(('theme', c.Theme(default='mkdocs')),)) + conf.load_dict(config_contents) + errors, warnings = conf.validate() + self.assertEqual(errors, []) + self.assertEqual(warnings, []) + self.assertEqual(conf['theme'].dirs, result['dirs']) + self.assertEqual(conf['theme'].static_templates, set(result['static_templates'])) + self.assertEqual(dict(conf['theme']), result['vars']) + + def test_empty_nav(self): + conf = defaults.MkDocsConfig( + config_file_path=os.path.join(os.path.abspath('.'), 'mkdocs.yml') + ) + conf.load_dict({'site_name': 'Example'}) + conf.validate() + self.assertEqual(conf['nav'], None) + + def test_error_on_pages(self): + conf = defaults.MkDocsConfig() + conf.load_dict( + { + 'site_name': 'Example', + 'pages': ['index.md', 'about.md'], + } + ) + errors, warnings = conf.validate() + exp_error = "The configuration option 'pages' was removed from MkDocs. Use 'nav' instead." + self.assertEqual(errors, [('pages', ValidationError(exp_error))]) + self.assertEqual(warnings, []) + + def test_doc_dir_in_site_dir(self): + test_configs = ( + {'docs_dir': os.path.join('site', 'docs'), 'site_dir': 'site'}, + {'docs_dir': 'docs', 'site_dir': '.'}, + {'docs_dir': '.', 'site_dir': '.'}, + {'docs_dir': 'docs', 'site_dir': ''}, + {'docs_dir': '', 'site_dir': ''}, + {'docs_dir': 'docs', 'site_dir': 'docs'}, + ) + + for test_config in test_configs: + with self.subTest(test_config): + # Same as the default schema, but don't verify the docs_dir exists. + conf = config.Config( + schema=( + ('docs_dir', c.Dir(default='docs')), + ('site_dir', c.SiteDir(default='site')), + ), + config_file_path=os.path.join(os.path.abspath('..'), 'mkdocs.yml'), + ) + conf.load_dict(test_config) + + errors, warnings = conf.validate() + + self.assertEqual(len(errors), 1) + self.assertEqual(warnings, []) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/get_deps_tests.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/get_deps_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..58a95af995d2757a0b8575bb643ee35224d54426 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/get_deps_tests.py @@ -0,0 +1,172 @@ +import contextlib +import io +import os +import textwrap +import unittest + +from mkdocs.commands.get_deps import get_deps +from mkdocs.tests.base import tempdir + +_projects_file_path = os.path.join( + os.path.abspath(os.path.dirname(__file__)), 'integration', 'projects.yaml' +) + + +class TestGetDeps(unittest.TestCase): + @contextlib.contextmanager + def _assert_logs(self, expected): + with self.assertLogs('mkdocs.commands.get_deps') as cm: + yield + msgs = [f'{r.levelname}:{r.message}' for r in cm.records] + self.assertEqual('\n'.join(msgs), textwrap.dedent(expected).strip('\n')) + + @tempdir() + def _test_get_deps(self, tempdir, yml, expected): + if yml: + yml = 'site_name: Test\n' + textwrap.dedent(yml) + projects_path = os.path.join(tempdir, 'projects.yaml') + with open(projects_path, 'w') as f: + f.write(yml) + buf = io.StringIO() + with contextlib.redirect_stdout(buf): + get_deps(_projects_file_path, projects_path) + self.assertEqual(buf.getvalue().split(), expected) + + def test_empty_config(self): + expected_logs = "WARNING:The passed config file doesn't seem to be a mkdocs.yml config file" + with self._assert_logs(expected_logs): + self._test_get_deps('', []) + + def test_just_search(self): + cfg = ''' + plugins: [search] + ''' + self._test_get_deps(cfg, ['mkdocs']) + + def test_mkdocs_config(self): + cfg = ''' + site_name: MkDocs + theme: + name: mkdocs + locale: en + markdown_extensions: + - toc: + permalink:  + - attr_list + - def_list + - tables + - pymdownx.highlight: + use_pygments: false + - pymdownx.snippets + - pymdownx.superfences + - callouts + - mdx_gh_links: + user: mkdocs + repo: mkdocs + - mkdocs-click + plugins: + - search + - redirects: + - autorefs + - literate-nav: + nav_file: README.md + implicit_index: true + - mkdocstrings: + handlers: + python: + options: + docstring_section_style: list + ''' + self._test_get_deps( + cfg, + [ + 'markdown-callouts', + 'mdx-gh-links', + 'mkdocs', + 'mkdocs-autorefs', + 'mkdocs-click', + 'mkdocs-literate-nav', + 'mkdocs-redirects', + 'mkdocstrings', + 'mkdocstrings-python', + 'pymdown-extensions', + ], + ) + + def test_dict_keys_and_ignores_env(self): + cfg = ''' + theme: + name: material + plugins: + code-validator: + enabled: !ENV [LINT, false] + markdown_extensions: + pymdownx.emoji: + emoji_index: !!python/name:materialx.emoji.twemoji + emoji_generator: !!python/name:materialx.emoji.to_svg + ''' + self._test_get_deps( + cfg, ['mkdocs', 'mkdocs-code-validator', 'mkdocs-material', 'pymdown-extensions'] + ) + + def test_theme_precedence(self): + cfg = ''' + plugins: + - tags + theme: material + ''' + self._test_get_deps(cfg, ['mkdocs', 'mkdocs-material']) + + cfg = ''' + plugins: + - material/tags + ''' + self._test_get_deps(cfg, ['mkdocs', 'mkdocs-material']) + + cfg = ''' + plugins: + - tags + ''' + self._test_get_deps(cfg, ['mkdocs', 'mkdocs-plugin-tags']) + + def test_nonexistent(self): + cfg = ''' + plugins: + - taglttghhmdu + - syyisjupkbpo + - redirects + theme: qndyakplooyh + markdown_extensions: + - saqdhyndpvpa + ''' + expected_logs = """ + WARNING:Theme 'qndyakplooyh' is not provided by any registered project + WARNING:Plugin 'syyisjupkbpo' is not provided by any registered project + WARNING:Plugin 'taglttghhmdu' is not provided by any registered project + WARNING:Extension 'saqdhyndpvpa' is not provided by any registered project + """ + with self._assert_logs(expected_logs): + self._test_get_deps(cfg, ['mkdocs', 'mkdocs-redirects']) + + def test_git_and_shadowed(self): + cfg = ''' + theme: bootstrap4 + plugins: [blog] + ''' + self._test_get_deps( + cfg, ['git+https://github.com/andyoakley/mkdocs-blog', 'mkdocs', 'mkdocs-bootstrap4'] + ) + + def test_multi_theme(self): + cfg = ''' + theme: minty + ''' + self._test_get_deps(cfg, ['mkdocs', 'mkdocs-bootswatch']) + + def test_with_locale(self): + cfg = ''' + theme: + name: mkdocs + locale: uk + ''' + self._test_get_deps(cfg, ['mkdocs[i18n]']) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/gh_deploy_tests.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/gh_deploy_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..093e65907cec27fe42d0ce4c58c871d1d35900d5 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/gh_deploy_tests.py @@ -0,0 +1,190 @@ +import unittest +from unittest import mock + +from ghp_import import GhpError + +from mkdocs import __version__ +from mkdocs.commands import gh_deploy +from mkdocs.exceptions import Abort +from mkdocs.tests.base import load_config + + +class TestGitHubDeploy(unittest.TestCase): + @mock.patch('subprocess.Popen') + def test_is_cwd_git_repo(self, mock_popeno): + mock_popeno().wait.return_value = 0 + + self.assertTrue(gh_deploy._is_cwd_git_repo()) + + @mock.patch('subprocess.Popen') + def test_is_cwd_not_git_repo(self, mock_popeno): + mock_popeno().wait.return_value = 1 + + self.assertFalse(gh_deploy._is_cwd_git_repo()) + + @mock.patch('subprocess.Popen') + def test_get_current_sha(self, mock_popeno): + mock_popeno().communicate.return_value = (b'6d98394\n', b'') + + self.assertEqual(gh_deploy._get_current_sha('.'), '6d98394') + + @mock.patch('subprocess.Popen') + def test_get_remote_url_ssh(self, mock_popeno): + mock_popeno().communicate.return_value = ( + b'git@github.com:mkdocs/mkdocs.git\n', + b'', + ) + + expected = ('git@', 'mkdocs/mkdocs.git') + self.assertEqual(expected, gh_deploy._get_remote_url('origin')) + + @mock.patch('subprocess.Popen') + def test_get_remote_url_http(self, mock_popeno): + mock_popeno().communicate.return_value = ( + b'https://github.com/mkdocs/mkdocs.git\n', + b'', + ) + + expected = ('https://', 'mkdocs/mkdocs.git') + self.assertEqual(expected, gh_deploy._get_remote_url('origin')) + + @mock.patch('subprocess.Popen') + def test_get_remote_url_enterprise(self, mock_popeno): + mock_popeno().communicate.return_value = ( + b'https://notgh.com/mkdocs/mkdocs.git\n', + b'', + ) + + expected = (None, None) + self.assertEqual(expected, gh_deploy._get_remote_url('origin')) + + @mock.patch('mkdocs.commands.gh_deploy._is_cwd_git_repo', return_value=True) + @mock.patch('mkdocs.commands.gh_deploy._get_current_sha', return_value='shashas') + @mock.patch('mkdocs.commands.gh_deploy._get_remote_url', return_value=(None, None)) + @mock.patch('mkdocs.commands.gh_deploy._check_version') + @mock.patch('ghp_import.ghp_import') + def test_deploy(self, mock_import, check_version, get_remote, get_sha, is_repo): + config = load_config( + remote_branch='test', + ) + gh_deploy.gh_deploy(config) + + @mock.patch('mkdocs.commands.gh_deploy._is_cwd_git_repo', return_value=True) + @mock.patch('mkdocs.commands.gh_deploy._get_current_sha', return_value='shashas') + @mock.patch('mkdocs.commands.gh_deploy._get_remote_url', return_value=(None, None)) + @mock.patch('mkdocs.commands.gh_deploy._check_version') + @mock.patch('ghp_import.ghp_import') + @mock.patch('os.path.isfile', return_value=False) + def test_deploy_no_cname( + self, mock_isfile, mock_import, check_version, get_remote, get_sha, is_repo + ): + config = load_config( + remote_branch='test', + ) + gh_deploy.gh_deploy(config) + + @mock.patch('mkdocs.commands.gh_deploy._is_cwd_git_repo', return_value=True) + @mock.patch('mkdocs.commands.gh_deploy._get_current_sha', return_value='shashas') + @mock.patch( + 'mkdocs.commands.gh_deploy._get_remote_url', return_value=('git@', 'mkdocs/mkdocs.git') + ) + @mock.patch('mkdocs.commands.gh_deploy._check_version') + @mock.patch('ghp_import.ghp_import') + def test_deploy_hostname(self, mock_import, check_version, get_remote, get_sha, is_repo): + config = load_config( + remote_branch='test', + ) + gh_deploy.gh_deploy(config) + + @mock.patch('mkdocs.commands.gh_deploy._is_cwd_git_repo', return_value=True) + @mock.patch('mkdocs.commands.gh_deploy._get_current_sha', return_value='shashas') + @mock.patch('mkdocs.commands.gh_deploy._get_remote_url', return_value=(None, None)) + @mock.patch('mkdocs.commands.gh_deploy._check_version') + @mock.patch('ghp_import.ghp_import') + def test_deploy_ignore_version_default( + self, mock_import, check_version, get_remote, get_sha, is_repo + ): + config = load_config( + remote_branch='test', + ) + gh_deploy.gh_deploy(config) + check_version.assert_called_once() + + @mock.patch('mkdocs.commands.gh_deploy._is_cwd_git_repo', return_value=True) + @mock.patch('mkdocs.commands.gh_deploy._get_current_sha', return_value='shashas') + @mock.patch('mkdocs.commands.gh_deploy._get_remote_url', return_value=(None, None)) + @mock.patch('mkdocs.commands.gh_deploy._check_version') + @mock.patch('ghp_import.ghp_import') + def test_deploy_ignore_version(self, mock_import, check_version, get_remote, get_sha, is_repo): + config = load_config( + remote_branch='test', + ) + gh_deploy.gh_deploy(config, ignore_version=True) + check_version.assert_not_called() + + @mock.patch('mkdocs.commands.gh_deploy._is_cwd_git_repo', return_value=True) + @mock.patch('mkdocs.commands.gh_deploy._get_current_sha', return_value='shashas') + @mock.patch('mkdocs.commands.gh_deploy._check_version') + @mock.patch('ghp_import.ghp_import') + def test_deploy_error(self, mock_import, check_version, get_sha, is_repo): + mock_import.side_effect = GhpError('TestError123') + + config = load_config( + remote_branch='test', + ) + + with self.assertLogs('mkdocs', level='ERROR') as cm: + with self.assertRaises(Abort): + gh_deploy.gh_deploy(config) + self.assertEqual( + cm.output, + [ + 'ERROR:mkdocs.commands.gh_deploy:Failed to deploy to GitHub with error: \n' + 'TestError123' + ], + ) + + +class TestGitHubDeployLogs(unittest.TestCase): + @mock.patch('subprocess.Popen') + def test_mkdocs_newer(self, mock_popeno): + mock_popeno().communicate.return_value = ( + b'Deployed 12345678 with MkDocs version: 0.1.2\n', + b'', + ) + + with self.assertLogs('mkdocs') as cm: + gh_deploy._check_version('gh-pages') + self.assertEqual( + '\n'.join(cm.output), + f'INFO:mkdocs.commands.gh_deploy:Previous deployment was done with MkDocs ' + f'version 0.1.2; you are deploying with a newer version ({__version__})', + ) + + @mock.patch('subprocess.Popen') + def test_mkdocs_older(self, mock_popeno): + mock_popeno().communicate.return_value = ( + b'Deployed 12345678 with MkDocs version: 10.1.2\n', + b'', + ) + + with self.assertLogs('mkdocs', level='ERROR') as cm: + with self.assertRaises(Abort): + gh_deploy._check_version('gh-pages') + self.assertEqual( + '\n'.join(cm.output), + f'ERROR:mkdocs.commands.gh_deploy:Deployment terminated: Previous deployment was made with ' + f'MkDocs version 10.1.2; you are attempting to deploy with an older version ({__version__}).' + f' Use --ignore-version to deploy anyway.', + ) + + @mock.patch('subprocess.Popen') + def test_version_unknown(self, mock_popeno): + mock_popeno().communicate.return_value = (b'No version specified\n', b'') + + with self.assertLogs('mkdocs') as cm: + gh_deploy._check_version('gh-pages') + self.assertEqual( + '\n'.join(cm.output), + 'WARNING:mkdocs.commands.gh_deploy:Version check skipped: No version specified in previous deployment.', + ) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/integration.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/integration.py new file mode 100644 index 0000000000000000000000000000000000000000..a9569337c0e2ca5d69c12b0471e45ea0024ae12a --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/integration.py @@ -0,0 +1,75 @@ +""" +# MkDocs Integration tests + +This is a simple integration test that builds the MkDocs +documentation against all of the builtin themes. + +From the root of the MkDocs git repo, use: + + python -m mkdocs.tests.integration --help + + +TODOs + - Build with different configuration options. + - Build documentation other than just MkDocs as it is relatively simple. +""" + + +import logging +import os +import subprocess +import tempfile + +import click + +log = logging.getLogger('mkdocs') + +DIR = os.path.dirname(__file__) +MKDOCS_CONFIG = os.path.abspath(os.path.join(DIR, '../../mkdocs.yml')) +MKDOCS_THEMES = ['mkdocs', 'readthedocs'] +TEST_PROJECTS = os.path.abspath(os.path.join(DIR, 'integration')) + + +@click.command() +@click.option( + '--output', + help="The output directory to use when building themes", + type=click.Path(file_okay=False, writable=True), +) +def main(output=None): + if output is None: + directory = tempfile.TemporaryDirectory(prefix='mkdocs_integration-') + output = directory.name + + log.propagate = False + stream = logging.StreamHandler() + formatter = logging.Formatter("\033[1m\033[1;32m *** %(message)s *** \033[0m") + stream.setFormatter(formatter) + log.addHandler(stream) + log.setLevel(logging.DEBUG) + + base_cmd = ['mkdocs', 'build', '-q', '-s', '--site-dir'] + + log.debug("Building installed themes.") + for theme in sorted(MKDOCS_THEMES): + log.debug(f"Building theme: {theme}") + project_dir = os.path.dirname(MKDOCS_CONFIG) + out = os.path.join(output, theme) + command = base_cmd + [out, '--theme', theme] + subprocess.check_call(command, cwd=project_dir) + + log.debug("Building test projects.") + for project in os.listdir(TEST_PROJECTS): + project_dir = os.path.join(TEST_PROJECTS, project) + if not os.path.isdir(project_dir): + continue + log.debug(f"Building test project: {project}") + out = os.path.join(output, project) + command = base_cmd + [out] + subprocess.check_call(command, cwd=project_dir) + + log.debug(f"Theme and integration builds are in {output}") + + +if __name__ == '__main__': + main() diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/livereload_tests.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/livereload_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..db6b791eef81998072324278677bd64951d9435e --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/livereload_tests.py @@ -0,0 +1,646 @@ +#!/usr/bin/env python + +import contextlib +import email +import io +import sys +import threading +import time +import unittest +from pathlib import Path +from unittest import mock + +from mkdocs.livereload import LiveReloadServer +from mkdocs.tests.base import change_dir, tempdir + + +class FakeRequest: + def __init__(self, content): + self.in_file = io.BytesIO(content.encode()) + self.out_file = io.BytesIO() + self.out_file.close = lambda: None + + def makefile(self, *args, **kwargs): + return self.in_file + + def sendall(self, data): + self.out_file.write(data) + + +@contextlib.contextmanager +def testing_server(root, builder=lambda: None, mount_path="/"): + """Create the server and start most of its parts, but don't listen on a socket.""" + with mock.patch("socket.socket"): + server = LiveReloadServer( + builder, + host="localhost", + port=0, + root=root, + mount_path=mount_path, + polling_interval=0.2, + ) + server.setup_environ() + server.observer.start() + thread = threading.Thread(target=server._build_loop, daemon=True) + thread.start() + yield server + server.shutdown() + thread.join() + + +def do_request(server, content): + request = FakeRequest(content + " HTTP/1.1") + server.RequestHandlerClass(request, ("127.0.0.1", 0), server) + response = request.out_file.getvalue() + + headers, _, content = response.partition(b"\r\n\r\n") + status, _, headers = headers.partition(b"\r\n") + status = status.split(None, 1)[1].decode() + + headers = email.message_from_bytes(headers) + headers["_status"] = status + return headers, content.decode() + + +SCRIPT_REGEX = r'' + + +class BuildTests(unittest.TestCase): + @tempdir({"test.css": "div { color: red; }"}) + def test_serves_normal_file(self, site_dir): + with testing_server(site_dir) as server: + headers, output = do_request(server, "GET /test.css") + self.assertEqual(output, "div { color: red; }") + self.assertEqual(headers["_status"], "200 OK") + self.assertEqual(headers.get("content-length"), str(len(output))) + + @tempdir({"docs/foo.docs": "docs1", "mkdocs.yml": "yml1"}) + @tempdir({"foo.site": "original"}) + def test_basic_rebuild(self, site_dir, origin_dir): + docs_dir = Path(origin_dir, "docs") + + started_building = threading.Event() + + def rebuild(): + started_building.set() + Path(site_dir, "foo.site").write_text( + Path(docs_dir, "foo.docs").read_text() + Path(origin_dir, "mkdocs.yml").read_text() + ) + + with testing_server(site_dir, rebuild) as server: + server.watch(docs_dir, rebuild) + server.watch(Path(origin_dir, "mkdocs.yml"), rebuild) + time.sleep(0.01) + + _, output = do_request(server, "GET /foo.site") + self.assertEqual(output, "original") + + Path(docs_dir, "foo.docs").write_text("docs2") + self.assertTrue(started_building.wait(timeout=10)) + started_building.clear() + + _, output = do_request(server, "GET /foo.site") + self.assertEqual(output, "docs2yml1") + + Path(origin_dir, "mkdocs.yml").write_text("yml2") + self.assertTrue(started_building.wait(timeout=10)) + started_building.clear() + + _, output = do_request(server, "GET /foo.site") + self.assertEqual(output, "docs2yml2") + + @tempdir({"foo.docs": "a"}) + @tempdir({"foo.site": "original"}) + def test_rebuild_after_delete(self, site_dir, docs_dir): + started_building = threading.Event() + + def rebuild(): + started_building.set() + Path(site_dir, "foo.site").unlink() + + with testing_server(site_dir, rebuild) as server: + server.watch(docs_dir, rebuild) + time.sleep(0.01) + + Path(docs_dir, "foo.docs").write_text("b") + self.assertTrue(started_building.wait(timeout=10)) + + with self.assertLogs("mkdocs.livereload"): + _, output = do_request(server, "GET /foo.site") + + self.assertIn("404", output) + + @tempdir({"aaa": "something"}) + def test_rebuild_after_rename(self, site_dir): + started_building = threading.Event() + + with testing_server(site_dir, started_building.set) as server: + server.watch(site_dir) + time.sleep(0.01) + + Path(site_dir, "aaa").rename(Path(site_dir, "bbb")) + self.assertTrue(started_building.wait(timeout=10)) + + @tempdir() + def test_rebuild_on_edit(self, site_dir): + started_building = threading.Event() + + with open(Path(site_dir, "test"), "wb") as f: + time.sleep(0.01) + + with testing_server(site_dir, started_building.set) as server: + server.watch(site_dir) + time.sleep(0.01) + + f.write(b"hi\n") + f.flush() + + self.assertTrue(started_building.wait(timeout=10)) + + @tempdir() + def test_unwatch(self, site_dir): + started_building = threading.Event() + + with testing_server(site_dir, started_building.set) as server: + with self.assertRaises(KeyError): + server.unwatch(site_dir) + + server.watch(site_dir) + server.watch(site_dir) + server.unwatch(site_dir) + time.sleep(0.01) + + Path(site_dir, "foo").write_text("foo") + self.assertTrue(started_building.wait(timeout=10)) + started_building.clear() + + server.unwatch(site_dir) + Path(site_dir, "foo").write_text("bar") + self.assertFalse(started_building.wait(timeout=0.5)) + + with self.assertRaises(KeyError): + server.unwatch(site_dir) + + @tempdir({"foo.docs": "a"}) + @tempdir({"foo.site": "original"}) + def test_custom_action_warns(self, site_dir, docs_dir): + started_building = threading.Event() + + def rebuild(): + started_building.set() + content = Path(docs_dir, "foo.docs").read_text() + Path(site_dir, "foo.site").write_text(content * 5) + + with testing_server(site_dir) as server: + with self.assertWarnsRegex(DeprecationWarning, "func") as cm: + server.watch(docs_dir, rebuild) + time.sleep(0.01) + self.assertIn("livereload_tests.py", cm.filename) + + Path(docs_dir, "foo.docs").write_text("b") + self.assertTrue(started_building.wait(timeout=10)) + + _, output = do_request(server, "GET /foo.site") + self.assertEqual(output, "bbbbb") + + @tempdir({"foo.docs": "docs1"}) + @tempdir({"foo.extra": "extra1"}) + @tempdir({"foo.site": "original"}) + def test_multiple_dirs_can_cause_rebuild(self, site_dir, extra_dir, docs_dir): + started_building = threading.Barrier(2) + + def rebuild(): + started_building.wait(timeout=10) + content1 = Path(docs_dir, "foo.docs").read_text() + content2 = Path(extra_dir, "foo.extra").read_text() + Path(site_dir, "foo.site").write_text(content1 + content2) + + with testing_server(site_dir, rebuild) as server: + server.watch(docs_dir) + server.watch(extra_dir) + time.sleep(0.01) + + Path(docs_dir, "foo.docs").write_text("docs2") + started_building.wait(timeout=10) + + _, output = do_request(server, "GET /foo.site") + self.assertEqual(output, "docs2extra1") + + Path(extra_dir, "foo.extra").write_text("extra2") + started_building.wait(timeout=10) + + _, output = do_request(server, "GET /foo.site") + self.assertEqual(output, "docs2extra2") + + @tempdir({"foo.docs": "docs1"}) + @tempdir({"foo.extra": "extra1"}) + @tempdir({"foo.site": "original"}) + def test_multiple_dirs_changes_rebuild_only_once(self, site_dir, extra_dir, docs_dir): + started_building = threading.Event() + + def rebuild(): + self.assertFalse(started_building.is_set()) + started_building.set() + content1 = Path(docs_dir, "foo.docs").read_text() + content2 = Path(extra_dir, "foo.extra").read_text() + Path(site_dir, "foo.site").write_text(content1 + content2) + + with testing_server(site_dir, rebuild) as server: + server.watch(docs_dir) + server.watch(extra_dir) + time.sleep(0.01) + + _, output = do_request(server, "GET /foo.site") + Path(docs_dir, "foo.docs").write_text("docs2") + Path(extra_dir, "foo.extra").write_text("extra2") + self.assertTrue(started_building.wait(timeout=10)) + + _, output = do_request(server, "GET /foo.site") + self.assertEqual(output, "docs2extra2") + + @tempdir({"foo.docs": "a"}) + @tempdir({"foo.site": "original"}) + def test_change_is_detected_while_building(self, site_dir, docs_dir): + before_finished_building = threading.Barrier(2) + can_finish_building = threading.Event() + + def rebuild(): + content = Path(docs_dir, "foo.docs").read_text() + Path(site_dir, "foo.site").write_text(content * 5) + before_finished_building.wait(timeout=10) + self.assertTrue(can_finish_building.wait(timeout=10)) + + with testing_server(site_dir, rebuild) as server: + server.watch(docs_dir) + time.sleep(0.01) + + Path(docs_dir, "foo.docs").write_text("b") + before_finished_building.wait(timeout=10) + Path(docs_dir, "foo.docs").write_text("c") + can_finish_building.set() + + _, output = do_request(server, "GET /foo.site") + self.assertEqual(output, "bbbbb") + + before_finished_building.wait(timeout=10) + + _, output = do_request(server, "GET /foo.site") + self.assertEqual(output, "ccccc") + + @tempdir({"foo.docs": "a"}) + @tempdir({"foo.site": "original"}) + def test_recovers_from_build_error(self, site_dir, docs_dir): + started_building = threading.Event() + build_count = 0 + + def rebuild(): + started_building.set() + nonlocal build_count + build_count += 1 + if build_count == 1: + raise ValueError("oh no") + else: + content = Path(docs_dir, "foo.docs").read_text() + Path(site_dir, "foo.site").write_text(content * 5) + + with testing_server(site_dir, rebuild) as server: + server.watch(docs_dir) + time.sleep(0.01) + + err = io.StringIO() + with contextlib.redirect_stderr(err), self.assertLogs("mkdocs.livereload") as cm: + Path(docs_dir, "foo.docs").write_text("b") + started_building.wait(timeout=10) + + Path(docs_dir, "foo.docs").write_text("c") + + _, output = do_request(server, "GET /foo.site") + + self.assertIn("ValueError: oh no", err.getvalue()) + self.assertRegex( + "\n".join(cm.output), + r".*Detected file changes\n" + r".*An error happened during the rebuild.*\n" + r".*Detected file changes\n", + ) + self.assertEqual(output, "ccccc") + + @tempdir( + { + "normal.html": "hello", + "no_body.html": "

hi", + "empty.html": "", + "multi_body.html": "foobar", + } + ) + def test_serves_modified_html(self, site_dir): + with testing_server(site_dir) as server: + server.watch(site_dir) + + headers, output = do_request(server, "GET /normal.html") + self.assertRegex(output, fr"^hello{SCRIPT_REGEX}$") + self.assertEqual(headers.get("content-type"), "text/html") + self.assertEqual(headers.get("content-length"), str(len(output))) + + _, output = do_request(server, "GET /no_body.html") + self.assertRegex(output, fr"^

hi{SCRIPT_REGEX}$") + + headers, output = do_request(server, "GET /empty.html") + self.assertRegex(output, fr"^{SCRIPT_REGEX}$") + self.assertEqual(headers.get("content-length"), str(len(output))) + + _, output = do_request(server, "GET /multi_body.html") + self.assertRegex(output, fr"^foobar{SCRIPT_REGEX}$") + + @tempdir({"index.html": "aaa", "foo/index.html": "bbb"}) + def test_serves_directory_index(self, site_dir): + with testing_server(site_dir) as server: + headers, output = do_request(server, "GET /") + self.assertRegex(output, r"^aaa$") + self.assertEqual(headers["_status"], "200 OK") + self.assertEqual(headers.get("content-type"), "text/html") + self.assertEqual(headers.get("content-length"), str(len(output))) + + for path in "/foo/", "/foo/index.html": + _, output = do_request(server, f"GET {path}") + self.assertRegex(output, r"^bbb$") + + with self.assertLogs("mkdocs.livereload"): + headers, _ = do_request(server, "GET /foo/index.html/") + self.assertEqual(headers["_status"], "404 Not Found") + + @tempdir( + { + "foo/bar/index.html": "aaa", + "foo/測試/index.html": "bbb", + } + ) + def test_redirects_to_directory(self, site_dir): + with testing_server(site_dir, mount_path="/sub") as server: + with self.assertLogs("mkdocs.livereload"): + headers, _ = do_request(server, "GET /sub/foo/bar") + self.assertEqual(headers["_status"], "302 Found") + self.assertEqual(headers.get("location"), "/sub/foo/bar/") + + with self.assertLogs("mkdocs.livereload"): + headers, _ = do_request(server, "GET /sub/foo/測試") + self.assertEqual(headers["_status"], "302 Found") + self.assertEqual(headers.get("location"), "/sub/foo/%E6%B8%AC%E8%A9%A6/") + + with self.assertLogs("mkdocs.livereload"): + headers, _ = do_request(server, "GET /sub/foo/%E6%B8%AC%E8%A9%A6") + self.assertEqual(headers["_status"], "302 Found") + self.assertEqual(headers.get("location"), "/sub/foo/%E6%B8%AC%E8%A9%A6/") + + @tempdir({"я.html": "aaa", "测试2/index.html": "bbb"}) + def test_serves_with_unicode_characters(self, site_dir): + with testing_server(site_dir) as server: + _, output = do_request(server, "GET /я.html") + self.assertRegex(output, r"^aaa$") + _, output = do_request(server, "GET /%D1%8F.html") + self.assertRegex(output, r"^aaa$") + + with self.assertLogs("mkdocs.livereload"): + headers, _ = do_request(server, "GET /%D1.html") + self.assertEqual(headers["_status"], "404 Not Found") + + _, output = do_request(server, "GET /测试2/") + self.assertRegex(output, r"^bbb$") + _, output = do_request(server, "GET /%E6%B5%8B%E8%AF%952/index.html") + self.assertRegex(output, r"^bbb$") + + @tempdir() + def test_serves_polling_instantly(self, site_dir): + with testing_server(site_dir) as server: + _, output = do_request(server, "GET /livereload/0/0") + self.assertTrue(output.isdigit()) + + @tempdir() + def test_serves_polling_with_mount_path(self, site_dir): + with testing_server(site_dir, mount_path="/test/f*o") as server: + _, output = do_request(server, "GET /livereload/0/0") + self.assertTrue(output.isdigit()) + + @tempdir() + @tempdir() + def test_serves_polling_after_event(self, site_dir, docs_dir): + with testing_server(site_dir) as server: + initial_epoch = server._visible_epoch + + server.watch(docs_dir) + time.sleep(0.01) + + Path(docs_dir, "foo.docs").write_text("b") + + _, output = do_request(server, f"GET /livereload/{initial_epoch}/0") + + self.assertNotEqual(server._visible_epoch, initial_epoch) + self.assertEqual(output, str(server._visible_epoch)) + + @tempdir() + def test_serves_polling_with_timeout(self, site_dir): + with testing_server(site_dir) as server: + server.poll_response_timeout = 0.2 + initial_epoch = server._visible_epoch + + start_time = time.monotonic() + _, output = do_request(server, f"GET /livereload/{initial_epoch}/0") + self.assertGreaterEqual(time.monotonic(), start_time + 0.2) + self.assertEqual(output, str(initial_epoch)) + + @tempdir() + def test_error_handler(self, site_dir): + with testing_server(site_dir) as server: + server.error_handler = lambda code: b"[%d]" % code + with self.assertLogs("mkdocs.livereload") as cm: + headers, output = do_request(server, "GET /missing") + + self.assertEqual(headers["_status"], "404 Not Found") + self.assertEqual(output, "[404]") + self.assertRegex( + "\n".join(cm.output), + r'^WARNING:mkdocs.livereload:.*"GET /missing HTTP/1.1" code 404', + ) + + @tempdir() + def test_bad_error_handler(self, site_dir): + with testing_server(site_dir) as server: + server.error_handler = lambda code: 0 / 0 + with self.assertLogs("mkdocs.livereload") as cm: + headers, output = do_request(server, "GET /missing") + + self.assertEqual(headers["_status"], "404 Not Found") + self.assertIn("404", output) + self.assertRegex( + "\n".join(cm.output), r"Failed to render an error message[\s\S]+/missing.+code 404" + ) + + @tempdir( + { + "test.html": "\nhi", + "test.xml": '\n', + "test.css": "div { color: red; }", + "test.js": "use strict;", + "test.json": '{"a": "b"}', + } + ) + def test_mime_types(self, site_dir): + with testing_server(site_dir) as server: + headers, _ = do_request(server, "GET /test.html") + self.assertEqual(headers.get("content-type"), "text/html") + + headers, _ = do_request(server, "GET /test.xml") + self.assertIn(headers.get("content-type"), ["text/xml", "application/xml"]) + + headers, _ = do_request(server, "GET /test.css") + self.assertEqual(headers.get("content-type"), "text/css") + + headers, _ = do_request(server, "GET /test.js") + self.assertEqual(headers.get("content-type"), "application/javascript") + + headers, _ = do_request(server, "GET /test.json") + self.assertEqual(headers.get("content-type"), "application/json") + + @tempdir({"index.html": "aaa", "sub/sub.html": "bbb"}) + def test_serves_from_mount_path(self, site_dir): + with testing_server(site_dir, mount_path="/sub") as server: + headers, output = do_request(server, "GET /sub/") + self.assertRegex(output, r"^aaa$") + self.assertEqual(headers.get("content-type"), "text/html") + + _, output = do_request(server, "GET /sub/sub/sub.html") + self.assertRegex(output, r"^bbb$") + + with self.assertLogs("mkdocs.livereload"): + headers, _ = do_request(server, "GET /sub/sub.html") + self.assertEqual(headers["_status"], "404 Not Found") + + @tempdir() + def test_redirects_to_mount_path(self, site_dir): + with testing_server(site_dir, mount_path="/mount/path") as server: + with self.assertLogs("mkdocs.livereload"): + headers, _ = do_request(server, "GET /") + self.assertEqual(headers["_status"], "302 Found") + self.assertEqual(headers.get("location"), "/mount/path/") + + @tempdir() + def test_redirects_to_unicode_mount_path(self, site_dir): + with testing_server(site_dir, mount_path="/mount/測試") as server: + with self.assertLogs("mkdocs.livereload"): + headers, _ = do_request(server, "GET /") + self.assertEqual(headers["_status"], "302 Found") + self.assertEqual(headers.get("location"), "/mount/%E6%B8%AC%E8%A9%A6/") + + @tempdir({"mkdocs.yml": "original", "mkdocs2.yml": "original"}, prefix="tmp_dir") + @tempdir(prefix="origin_dir") + @tempdir({"subdir/foo.md": "original"}, prefix="dest_docs_dir") + def test_watches_direct_symlinks(self, dest_docs_dir, origin_dir, tmp_dir): + try: + Path(origin_dir, "docs").symlink_to(dest_docs_dir, target_is_directory=True) + Path(origin_dir, "mkdocs.yml").symlink_to(Path(tmp_dir, "mkdocs.yml")) + except NotImplementedError: # PyPy on Windows + self.skipTest("Creating symlinks not supported") + + started_building = threading.Event() + + def wait_for_build(): + result = started_building.wait(timeout=10) + started_building.clear() + with self.assertLogs("mkdocs.livereload"): + do_request(server, "GET /") + return result + + with testing_server(tmp_dir, started_building.set) as server: + server.watch(Path(origin_dir, "docs")) + server.watch(Path(origin_dir, "mkdocs.yml")) + time.sleep(0.01) + + Path(origin_dir, "unrelated.md").write_text("foo") + self.assertFalse(started_building.wait(timeout=0.5)) + + Path(tmp_dir, "mkdocs.yml").write_text("edited") + self.assertTrue(wait_for_build()) + + Path(dest_docs_dir, "subdir", "foo.md").write_text("edited") + self.assertTrue(wait_for_build()) + + @tempdir(["file_dest_1.md", "file_dest_2.md", "file_dest_unused.md"], prefix="tmp_dir") + @tempdir(["file_under.md"], prefix="dir_to_link_to") + @tempdir() + def test_watches_through_symlinks(self, docs_dir, dir_to_link_to, tmp_dir): + try: + Path(docs_dir, "link1.md").symlink_to(Path(tmp_dir, "file_dest_1.md")) + Path(docs_dir, "linked_dir").symlink_to(dir_to_link_to, target_is_directory=True) + + Path(dir_to_link_to, "sublink.md").symlink_to(Path(tmp_dir, "file_dest_2.md")) + except NotImplementedError: # PyPy on Windows + self.skipTest("Creating symlinks not supported") + + started_building = threading.Event() + + def wait_for_build(): + result = started_building.wait(timeout=10) + started_building.clear() + with self.assertLogs("mkdocs.livereload"): + do_request(server, "GET /") + return result + + with testing_server(docs_dir, started_building.set) as server: + server.watch(docs_dir) + time.sleep(0.01) + + Path(tmp_dir, "file_dest_1.md").write_text("edited") + self.assertTrue(wait_for_build()) + + Path(dir_to_link_to, "file_under.md").write_text("edited") + self.assertTrue(wait_for_build()) + + Path(tmp_dir, "file_dest_2.md").write_text("edited") + self.assertTrue(wait_for_build()) + + Path(docs_dir, "link1.md").unlink() + self.assertTrue(wait_for_build()) + + Path(tmp_dir, "file_dest_unused.md").write_text("edited") + self.assertFalse(started_building.wait(timeout=0.5)) + + @tempdir(prefix="site_dir") + @tempdir(["docs/unused.md", "README.md"], prefix="origin_dir") + def test_watches_through_relative_symlinks(self, origin_dir, site_dir): + docs_dir = Path(origin_dir, "docs") + with change_dir(docs_dir): + try: + Path(docs_dir, "README.md").symlink_to(Path("..", "README.md")) + except NotImplementedError: # PyPy on Windows + self.skipTest("Creating symlinks not supported") + + started_building = threading.Event() + + with testing_server(docs_dir, started_building.set) as server: + server.watch(docs_dir) + time.sleep(0.01) + + Path(origin_dir, "README.md").write_text("edited") + self.assertTrue(started_building.wait(timeout=10)) + + @tempdir() + def test_watch_with_broken_symlinks(self, docs_dir): + Path(docs_dir, "subdir").mkdir() + + try: + if sys.platform != "win32": + Path(docs_dir, "subdir", "circular").symlink_to(Path(docs_dir)) + + Path(docs_dir, "broken_1").symlink_to(Path(docs_dir, "oh no")) + Path(docs_dir, "broken_2").symlink_to(Path(docs_dir, "oh no"), target_is_directory=True) + Path(docs_dir, "broken_3").symlink_to(Path(docs_dir, "broken_2")) + except NotImplementedError: # PyPy on Windows + self.skipTest("Creating symlinks not supported") + + started_building = threading.Event() + with testing_server(docs_dir, started_building.set) as server: + server.watch(docs_dir) + time.sleep(0.01) + + Path(docs_dir, "subdir", "test").write_text("test") + self.assertTrue(started_building.wait(timeout=10)) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/localization_tests.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/localization_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..05a966c3e43d9190db38d719e1a316442b10eb42 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/localization_tests.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python + + +import unittest +from unittest import mock + +from mkdocs.config.base import ValidationError +from mkdocs.localization import install_translations, parse_locale +from mkdocs.tests.base import tempdir + + +class LocalizationTests(unittest.TestCase): + def setUp(self): + self.env = mock.Mock() + + def test_jinja_extension_installed(self): + install_translations(self.env, parse_locale('en'), []) + self.env.add_extension.assert_called_once_with('jinja2.ext.i18n') + + def test_valid_language(self): + locale = parse_locale('en') + self.assertEqual(locale.language, 'en') + + def test_valid_language_territory(self): + locale = parse_locale('en_US') + self.assertEqual(locale.language, 'en') + self.assertEqual(locale.territory, 'US') + self.assertEqual(str(locale), 'en_US') + + def test_unknown_locale(self): + self.assertRaises(ValidationError, parse_locale, 'foo') + + def test_invalid_locale(self): + self.assertRaises(ValidationError, parse_locale, '42') + + @tempdir() + def test_no_translations_found(self, dir_without_translations): + with self.assertLogs('mkdocs') as cm: + install_translations(self.env, parse_locale('fr_CA'), [dir_without_translations]) + self.assertEqual( + '\n'.join(cm.output), + "WARNING:mkdocs.localization:No translations could be found for the locale 'fr_CA'. " + "Defaulting to English.", + ) + self.env.install_null_translations.assert_called_once() + + @tempdir + def test_translations_found(self, tdir): + translations = mock.Mock() + + with mock.patch('mkdocs.localization.Translations.load', return_value=translations): + install_translations(self.env, parse_locale('en'), [tdir]) + + self.env.install_gettext_translations.assert_called_once_with(translations) + + @tempdir() + @tempdir() + def test_merge_translations(self, custom_dir, theme_dir): + custom_dir_translations = mock.Mock() + theme_dir_translations = mock.Mock() + + def side_effet(*args, **kwargs): + dirname = args[0] + if dirname.startswith(custom_dir): + return custom_dir_translations + elif dirname.startswith(theme_dir): + return theme_dir_translations + else: + self.fail() + + with mock.patch('mkdocs.localization.Translations.load', side_effect=side_effet): + install_translations(self.env, parse_locale('en'), [custom_dir, theme_dir]) + + theme_dir_translations.merge.assert_called_once_with(custom_dir_translations) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/new_tests.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/new_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..120cfa5e76059a17f1df56c785bd492ec287090c --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/new_tests.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python + +import os +import unittest + +from mkdocs.commands import new +from mkdocs.tests.base import change_dir, tempdir + + +class NewTests(unittest.TestCase): + @tempdir() + def test_new(self, temp_dir): + with change_dir(temp_dir): + new.new("myproject") + + expected_paths = [ + os.path.join(temp_dir, "myproject"), + os.path.join(temp_dir, "myproject", "mkdocs.yml"), + os.path.join(temp_dir, "myproject", "docs"), + os.path.join(temp_dir, "myproject", "docs", "index.md"), + ] + + for expected_path in expected_paths: + self.assertTrue(os.path.exists(expected_path)) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/plugin_tests.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/plugin_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..78e52876284befff86e14ce88c25939a2dd176f5 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/plugin_tests.py @@ -0,0 +1,304 @@ +#!/usr/bin/env python +from __future__ import annotations + +import os +import unittest +from typing import TYPE_CHECKING, Optional + +if TYPE_CHECKING: + from typing_extensions import assert_type +else: + + def assert_type(val, typ): + return None + + +from mkdocs import plugins +from mkdocs.commands import build +from mkdocs.config import base +from mkdocs.config import config_options as c +from mkdocs.config.base import ValidationError +from mkdocs.exceptions import Abort, BuildError, PluginError +from mkdocs.tests.base import load_config, tempdir + + +class _DummyPluginConfig(base.Config): + foo = c.Type(str, default='default foo') + bar = c.Type(int, default=0) + dir = c.Optional(c.Dir(exists=False)) + + +class DummyPlugin(plugins.BasePlugin[_DummyPluginConfig]): + def on_page_content(self, html, **kwargs) -> str: + """modify page content by prepending `foo` config value.""" + return f'{self.config.foo} {html}' + + def on_nav(self, nav, **kwargs) -> None: + """do nothing (return None) to not modify item.""" + return None + + def on_page_read_source(self, **kwargs) -> str: + """create new source by prepending `foo` config value to 'source'.""" + return f'{self.config.foo} source' + + def on_pre_build(self, **kwargs) -> None: + """do nothing (return None).""" + return None + + +class TestPluginClass(unittest.TestCase): + def test_valid_plugin_options(self) -> None: + test_dir = 'test' + + options = { + 'foo': 'some value', + 'dir': test_dir, + } + + cfg_fname = os.path.join('tmp', 'test', 'fname.yml') + cfg_fname = os.path.abspath(cfg_fname) + + cfg_dirname = os.path.dirname(cfg_fname) + expected = { + 'foo': 'some value', + 'bar': 0, + 'dir': os.path.join(cfg_dirname, test_dir), + } + + plugin = DummyPlugin() + errors, warnings = plugin.load_config(options, config_file_path=cfg_fname) + self.assertEqual(errors, []) + self.assertEqual(warnings, []) + + assert_type(plugin.config, _DummyPluginConfig) + self.assertEqual(plugin.config, expected) + + assert_type(plugin.config.bar, int) + self.assertEqual(plugin.config.bar, 0) + assert_type(plugin.config.dir, Optional[str]) + + def test_invalid_plugin_options(self): + plugin = DummyPlugin() + errors, warnings = plugin.load_config({'foo': 42}) + self.assertEqual( + errors, + [('foo', ValidationError("Expected type: but received: "))], + ) + self.assertEqual(warnings, []) + + errors, warnings = plugin.load_config({'bar': 'a string'}) + self.assertEqual( + errors, + [('bar', ValidationError("Expected type: but received: "))], + ) + self.assertEqual(warnings, []) + + errors, warnings = plugin.load_config({'invalid_key': 'value'}) + self.assertEqual(errors, []) + self.assertEqual( + warnings, [('invalid_key', "Unrecognised configuration name: invalid_key")] + ) + + +class TestPluginCollection(unittest.TestCase): + def test_correct_events_registered(self): + collection = plugins.PluginCollection() + plugin = DummyPlugin() + collection['foo'] = plugin + self.assertEqual( + collection.events, + { + 'startup': [], + 'shutdown': [], + 'serve': [], + 'config': [], + 'pre_build': [plugin.on_pre_build], + 'files': [], + 'nav': [plugin.on_nav], + 'env': [], + 'post_build': [], + 'build_error': [], + 'pre_template': [], + 'template_context': [], + 'post_template': [], + 'pre_page': [], + 'page_read_source': [plugin.on_page_read_source], + 'page_markdown': [], + 'page_content': [plugin.on_page_content], + 'page_context': [], + 'post_page': [], + }, + ) + + def test_event_priorities(self) -> None: + class PrioPlugin(plugins.BasePlugin): + config_scheme = base.get_schema(_DummyPluginConfig) + + @plugins.event_priority(100) + def on_page_content(self, html, **kwargs) -> None: + pass + + @plugins.event_priority(-100) + def on_nav(self, nav, **kwargs) -> None: + pass + + def on_page_read_source(self, **kwargs) -> None: + pass + + @plugins.event_priority(-50) + def on_post_build(self, **kwargs) -> None: + pass + + collection = plugins.PluginCollection() + collection['dummy'] = dummy = DummyPlugin() + collection['prio'] = prio = PrioPlugin() + self.assertEqual( + collection.events['page_content'], + [prio.on_page_content, dummy.on_page_content], + ) + self.assertEqual( + collection.events['nav'], + [dummy.on_nav, prio.on_nav], + ) + self.assertEqual( + collection.events['page_read_source'], + [dummy.on_page_read_source, prio.on_page_read_source], + ) + self.assertEqual( + collection.events['post_build'], + [prio.on_post_build], + ) + + def test_set_plugin_on_collection(self): + collection = plugins.PluginCollection() + plugin = DummyPlugin() + collection['foo'] = plugin + self.assertEqual(list(collection.items()), [('foo', plugin)]) + + def test_set_multiple_plugins_on_collection(self): + collection = plugins.PluginCollection() + plugin1 = DummyPlugin() + collection['foo'] = plugin1 + plugin2 = DummyPlugin() + collection['bar'] = plugin2 + self.assertEqual(list(collection.items()), [('foo', plugin1), ('bar', plugin2)]) + + def test_run_event_on_collection(self): + collection = plugins.PluginCollection() + plugin = DummyPlugin() + plugin.load_config({'foo': 'new'}) + collection['foo'] = plugin + self.assertEqual( + collection.on_page_content('page content', page=None, config={}, files=[]), + 'new page content', + ) + + def test_run_event_twice_on_collection(self): + collection = plugins.PluginCollection() + plugin1 = DummyPlugin() + plugin1.load_config({'foo': 'new'}) + collection['foo'] = plugin1 + plugin2 = DummyPlugin() + plugin2.load_config({'foo': 'second'}) + collection['bar'] = plugin2 + self.assertEqual( + collection.on_page_content('page content', page=None, config={}, files=[]), + 'second new page content', + ) + + def test_event_returns_None(self): + collection = plugins.PluginCollection() + plugin = DummyPlugin() + plugin.load_config({'foo': 'new'}) + collection['foo'] = plugin + self.assertEqual(collection.on_nav(['nav item'], config={}, files=[]), ['nav item']) + + def test_event_empty_item(self): + collection = plugins.PluginCollection() + plugin = DummyPlugin() + plugin.load_config({'foo': 'new'}) + collection['foo'] = plugin + self.assertEqual(collection.on_page_read_source(page=None, config={}), 'new source') + + def test_event_empty_item_returns_None(self): + collection = plugins.PluginCollection() + plugin = DummyPlugin() + plugin.load_config({'foo': 'new'}) + collection['foo'] = plugin + self.assertEqual(collection.on_pre_build(config={}), None) + + def test_run_undefined_event_on_collection(self): + collection = plugins.PluginCollection() + self.assertEqual( + collection.on_page_markdown('page markdown', page=None, config={}, files=[]), + 'page markdown', + ) + + def test_run_unknown_event_on_collection(self): + collection = plugins.PluginCollection() + with self.assertRaises(KeyError): + collection.run_event('unknown', 'page content') + + @tempdir() + def test_run_build_error_event(self, site_dir): + build_errors = [] + + class PluginRaisingError(plugins.BasePlugin): + def __init__(self, error_on): + self.error_on = error_on + + def on_pre_page(self, page, **kwargs): + if self.error_on == 'pre_page': + raise BuildError('pre page error') + return page + + def on_page_markdown(self, markdown, **kwargs): + if self.error_on == 'page_markdown': + raise BuildError('page markdown error') + return markdown + + def on_page_content(self, html, **kwargs): + if self.error_on == 'page_content': + raise PluginError('page content error') + return html + + def on_post_page(self, html, **kwargs): + if self.error_on == 'post_page': + raise ValueError('post page error') + + def on_build_error(self, error, **kwargs): + build_errors.append(error) + + cfg = load_config(site_dir=site_dir) + cfg.plugins['errorplugin'] = PluginRaisingError(error_on='pre_page') + with self.assertLogs('mkdocs', level='ERROR'): + self.assertRaises(Abort, build.build, cfg) + + cfg = load_config(site_dir=site_dir) + cfg.plugins['errorplugin'] = PluginRaisingError(error_on='page_markdown') + with self.assertLogs('mkdocs', level='ERROR'): + self.assertRaises(Abort, build.build, cfg) + + cfg = load_config(site_dir=site_dir) + cfg.plugins['errorplugin'] = PluginRaisingError(error_on='page_content') + with self.assertLogs('mkdocs', level='ERROR'): + self.assertRaises(Abort, build.build, cfg) + + cfg = load_config(site_dir=site_dir) + cfg.plugins['errorplugin'] = PluginRaisingError(error_on='post_page') + with self.assertLogs('mkdocs', level='ERROR'): + self.assertRaises(ValueError, build.build, cfg) + + cfg = load_config(site_dir=site_dir) + cfg.plugins['errorplugin'] = PluginRaisingError(error_on='') + build.build(cfg) + + self.assertEqual(len(build_errors), 4) + self.assertIs(build_errors[0].__class__, BuildError) + self.assertEqual(str(build_errors[0]), 'pre page error') + self.assertIs(build_errors[1].__class__, BuildError) + self.assertEqual(str(build_errors[1]), 'page markdown error') + self.assertIs(build_errors[2].__class__, PluginError) + self.assertEqual(str(build_errors[2]), 'page content error') + self.assertIs(build_errors[3].__class__, ValueError) + self.assertEqual(str(build_errors[3]), 'post page error') diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/search_tests.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/search_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..b8ece67a9e691763bbe20e6f1f5f60079aa72a12 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/search_tests.py @@ -0,0 +1,635 @@ +#!/usr/bin/env python + +import json +import unittest +from unittest import mock + +from mkdocs.config.config_options import ValidationError +from mkdocs.contrib import search +from mkdocs.contrib.search import search_index +from mkdocs.structure.files import File +from mkdocs.structure.pages import Page +from mkdocs.structure.toc import get_toc +from mkdocs.tests.base import dedent, get_markdown_toc, load_config + + +def strip_whitespace(string): + return string.replace("\n", "").replace(" ", "") + + +class SearchConfigTests(unittest.TestCase): + def test_lang_default(self): + option = search.LangOption(default=['en']) + value = option.validate(None) + self.assertEqual(['en'], value) + + def test_lang_str(self): + option = search.LangOption() + value = option.validate('en') + self.assertEqual(['en'], value) + + def test_lang_list(self): + option = search.LangOption() + value = option.validate(['en']) + self.assertEqual(['en'], value) + + def test_lang_multi_list(self): + option = search.LangOption() + value = option.validate(['en', 'es', 'fr']) + self.assertEqual(['en', 'es', 'fr'], value) + + def test_lang_no_default_none(self): + option = search.LangOption() + value = option.validate(None) + self.assertIsNone(value) + + def test_lang_no_default_str(self): + option = search.LangOption(default=[]) + value = option.validate('en') + self.assertEqual(['en'], value) + + def test_lang_no_default_list(self): + option = search.LangOption(default=[]) + value = option.validate(['en']) + self.assertEqual(['en'], value) + + def test_lang_bad_type(self): + option = search.LangOption() + with self.assertRaises(ValidationError): + option.validate({}) + + def test_lang_bad_code(self): + option = search.LangOption() + value = option.validate(['foo']) + self.assertEqual(['en'], value) + + def test_lang_good_and_bad_code(self): + option = search.LangOption() + value = option.validate(['en', 'foo']) + self.assertEqual(['en'], value) + + def test_lang_missing_and_with_territory(self): + option = search.LangOption() + value = option.validate(['cs_CZ', 'pt_BR', 'fr']) + self.assertEqual(['fr', 'en', 'pt'], value) + + +class SearchPluginTests(unittest.TestCase): + def test_plugin_config_defaults(self): + expected = { + 'lang': None, + 'separator': r'[\s\-]+', + 'min_search_length': 3, + 'prebuild_index': False, + 'indexing': 'full', + } + plugin = search.SearchPlugin() + errors, warnings = plugin.load_config({}) + self.assertEqual(plugin.config, expected) + self.assertEqual(errors, []) + self.assertEqual(warnings, []) + + def test_plugin_config_lang(self): + expected = { + 'lang': ['es'], + 'separator': r'[\s\-]+', + 'min_search_length': 3, + 'prebuild_index': False, + 'indexing': 'full', + } + plugin = search.SearchPlugin() + errors, warnings = plugin.load_config({'lang': 'es'}) + self.assertEqual(plugin.config, expected) + self.assertEqual(errors, []) + self.assertEqual(warnings, []) + + def test_plugin_config_separator(self): + expected = { + 'lang': None, + 'separator': r'[\s\-\.]+', + 'min_search_length': 3, + 'prebuild_index': False, + 'indexing': 'full', + } + plugin = search.SearchPlugin() + errors, warnings = plugin.load_config({'separator': r'[\s\-\.]+'}) + self.assertEqual(plugin.config, expected) + self.assertEqual(errors, []) + self.assertEqual(warnings, []) + + def test_plugin_config_min_search_length(self): + expected = { + 'lang': None, + 'separator': r'[\s\-]+', + 'min_search_length': 2, + 'prebuild_index': False, + 'indexing': 'full', + } + plugin = search.SearchPlugin() + errors, warnings = plugin.load_config({'min_search_length': 2}) + self.assertEqual(plugin.config, expected) + self.assertEqual(errors, []) + self.assertEqual(warnings, []) + + def test_plugin_config_prebuild_index(self): + expected = { + 'lang': None, + 'separator': r'[\s\-]+', + 'min_search_length': 3, + 'prebuild_index': True, + 'indexing': 'full', + } + plugin = search.SearchPlugin() + errors, warnings = plugin.load_config({'prebuild_index': True}) + self.assertEqual(plugin.config, expected) + self.assertEqual(errors, []) + self.assertEqual(warnings, []) + + def test_plugin_config_indexing(self): + expected = { + 'lang': None, + 'separator': r'[\s\-]+', + 'min_search_length': 3, + 'prebuild_index': False, + 'indexing': 'titles', + } + plugin = search.SearchPlugin() + errors, warnings = plugin.load_config({'indexing': 'titles'}) + self.assertEqual(plugin.config, expected) + self.assertEqual(errors, []) + self.assertEqual(warnings, []) + + def test_event_on_config_defaults(self): + plugin = search.SearchPlugin() + plugin.load_config({}) + result = plugin.on_config(load_config(theme='mkdocs', extra_javascript=[])) + self.assertFalse(result['theme']['search_index_only']) + self.assertFalse(result['theme']['include_search_page']) + self.assertEqual(result['theme'].static_templates, {'404.html', 'sitemap.xml'}) + self.assertEqual(len(result['theme'].dirs), 3) + self.assertEqual(result['extra_javascript'], ['search/main.js']) + self.assertEqual(plugin.config.lang, [result['theme']['locale'].language]) + + def test_event_on_config_lang(self): + plugin = search.SearchPlugin() + plugin.load_config({'lang': 'es'}) + result = plugin.on_config(load_config(theme='mkdocs', extra_javascript=[])) + self.assertFalse(result['theme']['search_index_only']) + self.assertFalse(result['theme']['include_search_page']) + self.assertEqual(result['theme'].static_templates, {'404.html', 'sitemap.xml'}) + self.assertEqual(len(result['theme'].dirs), 3) + self.assertEqual(result['extra_javascript'], ['search/main.js']) + self.assertEqual(plugin.config.lang, ['es']) + + def test_event_on_config_theme_locale(self): + plugin = search.SearchPlugin() + plugin.load_config({}) + result = plugin.on_config( + load_config(theme={'name': 'mkdocs', 'locale': 'fr'}, extra_javascript=[]) + ) + self.assertFalse(result['theme']['search_index_only']) + self.assertFalse(result['theme']['include_search_page']) + self.assertEqual(result['theme'].static_templates, {'404.html', 'sitemap.xml'}) + self.assertEqual(len(result['theme'].dirs), 3) + self.assertEqual(result['extra_javascript'], ['search/main.js']) + self.assertEqual(plugin.config.lang, [result['theme']['locale'].language]) + + def test_event_on_config_include_search_page(self): + plugin = search.SearchPlugin() + plugin.load_config({}) + config = load_config( + theme={'name': 'mkdocs', 'include_search_page': True}, extra_javascript=[] + ) + result = plugin.on_config(config) + self.assertFalse(result['theme']['search_index_only']) + self.assertTrue(result['theme']['include_search_page']) + self.assertEqual( + result['theme'].static_templates, {'404.html', 'sitemap.xml', 'search.html'} + ) + self.assertEqual(len(result['theme'].dirs), 3) + self.assertEqual(result['extra_javascript'], ['search/main.js']) + + def test_event_on_config_search_index_only(self): + plugin = search.SearchPlugin() + plugin.load_config({}) + config = load_config( + theme={'name': 'mkdocs', 'search_index_only': True}, extra_javascript=[] + ) + result = plugin.on_config(config) + self.assertTrue(result['theme']['search_index_only']) + self.assertFalse(result['theme']['include_search_page']) + self.assertEqual(result['theme'].static_templates, {'404.html', 'sitemap.xml'}) + self.assertEqual(len(result['theme'].dirs), 2) + self.assertEqual(len(result['extra_javascript']), 0) + + @mock.patch('mkdocs.utils.write_file', autospec=True) + @mock.patch('mkdocs.utils.copy_file', autospec=True) + def test_event_on_post_build_defaults(self, mock_copy_file, mock_write_file): + plugin = search.SearchPlugin() + plugin.load_config({}) + config = load_config(theme='mkdocs') + plugin.on_config(config) + plugin.on_pre_build(config) + plugin.on_post_build(config) + self.assertEqual(mock_copy_file.call_count, 0) + self.assertEqual(mock_write_file.call_count, 1) + + @mock.patch('mkdocs.utils.write_file', autospec=True) + @mock.patch('mkdocs.utils.copy_file', autospec=True) + def test_event_on_post_build_single_lang(self, mock_copy_file, mock_write_file): + plugin = search.SearchPlugin() + plugin.load_config({'lang': ['es']}) + config = load_config(theme='mkdocs') + plugin.on_pre_build(config) + plugin.on_post_build(config) + self.assertEqual(mock_copy_file.call_count, 2) + self.assertEqual(mock_write_file.call_count, 1) + + @mock.patch('mkdocs.utils.write_file', autospec=True) + @mock.patch('mkdocs.utils.copy_file', autospec=True) + def test_event_on_post_build_multi_lang(self, mock_copy_file, mock_write_file): + plugin = search.SearchPlugin() + plugin.load_config({'lang': ['es', 'fr']}) + config = load_config(theme='mkdocs') + plugin.on_pre_build(config) + plugin.on_post_build(config) + self.assertEqual(mock_copy_file.call_count, 4) + self.assertEqual(mock_write_file.call_count, 1) + + @mock.patch('mkdocs.utils.write_file', autospec=True) + @mock.patch('mkdocs.utils.copy_file', autospec=True) + def test_event_on_post_build_search_index_only(self, mock_copy_file, mock_write_file): + plugin = search.SearchPlugin() + plugin.load_config({'lang': ['es']}) + config = load_config(theme={'name': 'mkdocs', 'search_index_only': True}) + plugin.on_pre_build(config) + plugin.on_post_build(config) + self.assertEqual(mock_copy_file.call_count, 0) + self.assertEqual(mock_write_file.call_count, 1) + + +class SearchIndexTests(unittest.TestCase): + def test_html_stripping(self): + stripper = search_index.ContentParser() + + stripper.feed("

Testing

Content

") + + self.assertEqual(stripper.stripped_html, "Testing\nContent") + + def test_content_parser(self): + parser = search_index.ContentParser() + + parser.feed('

Title

TEST') + parser.close() + + self.assertEqual( + parser.data, [search_index.ContentSection(text=["TEST"], id_="title", title="Title")] + ) + + def test_content_parser_no_id(self): + parser = search_index.ContentParser() + + parser.feed("

Title

TEST") + parser.close() + + self.assertEqual( + parser.data, [search_index.ContentSection(text=["TEST"], id_=None, title="Title")] + ) + + def test_content_parser_content_before_header(self): + parser = search_index.ContentParser() + + parser.feed("Content Before H1

Title

TEST") + parser.close() + + self.assertEqual( + parser.data, [search_index.ContentSection(text=["TEST"], id_=None, title="Title")] + ) + + def test_content_parser_no_sections(self): + parser = search_index.ContentParser() + + parser.feed("No H1 or H2TitleTEST") + + self.assertEqual(parser.data, []) + + def test_find_toc_by_id(self): + """ + Test finding the relevant TOC item by the tag ID. + """ + index = search_index.SearchIndex() + + md = dedent( + """ + # Heading 1 + ## Heading 2 + ### Heading 3 + """ + ) + toc = get_toc(get_markdown_toc(md)) + + toc_item = index._find_toc_by_id(toc, "heading-1") + self.assertEqual(toc_item.url, "#heading-1") + self.assertEqual(toc_item.title, "Heading 1") + + toc_item2 = index._find_toc_by_id(toc, "heading-2") + self.assertEqual(toc_item2.url, "#heading-2") + self.assertEqual(toc_item2.title, "Heading 2") + + toc_item3 = index._find_toc_by_id(toc, "heading-3") + self.assertEqual(toc_item3.url, "#heading-3") + self.assertEqual(toc_item3.title, "Heading 3") + + def test_create_search_index(self): + html_content = """ +

Heading 1

+

Content 1

+

Heading 2

+

Content 2

+

Heading 3

+

Content 3

+ """ + + base_cfg = load_config() + pages = [ + Page( + 'Home', + File('index.md', base_cfg.docs_dir, base_cfg.site_dir, base_cfg.use_directory_urls), + base_cfg, + ), + Page( + 'About', + File('about.md', base_cfg.docs_dir, base_cfg.site_dir, base_cfg.use_directory_urls), + base_cfg, + ), + ] + + md = dedent( + """ + # Heading 1 + ## Heading 2 + ### Heading 3 + """ + ) + toc = get_toc(get_markdown_toc(md)) + + full_content = ''.join(f"Heading{i}Content{i}" for i in range(1, 4)) + + plugin = search.SearchPlugin() + errors, warnings = plugin.load_config({}) + + for page in pages: + # Fake page.read_source() and page.render() + page.markdown = md + page.toc = toc + page.content = html_content + + index = search_index.SearchIndex(**plugin.config) + index.add_entry_from_context(page) + + self.assertEqual(len(index._entries), 4) + + loc = page.url + + self.assertEqual(index._entries[0]['title'], page.title) + self.assertEqual(strip_whitespace(index._entries[0]['text']), full_content) + self.assertEqual(index._entries[0]['location'], loc) + + self.assertEqual(index._entries[1]['title'], "Heading 1") + self.assertEqual(index._entries[1]['text'], "Content 1") + self.assertEqual(index._entries[1]['location'], f"{loc}#heading-1") + + self.assertEqual(index._entries[2]['title'], "Heading 2") + self.assertEqual(strip_whitespace(index._entries[2]['text']), "Content2") + self.assertEqual(index._entries[2]['location'], f"{loc}#heading-2") + + self.assertEqual(index._entries[3]['title'], "Heading 3") + self.assertEqual(strip_whitespace(index._entries[3]['text']), "Content3") + self.assertEqual(index._entries[3]['location'], f"{loc}#heading-3") + + def test_search_indexing_options(self): + def test_page(title, filename, config): + test_page = Page( + title, + File(filename, config.docs_dir, config.site_dir, config.use_directory_urls), + config, + ) + test_page.content = """ +

Heading 1

+

Content 1

+

Heading 2

+

Content 2

+

Heading 3

+

Content 3

""" + test_page.markdown = dedent( + """ + # Heading 1 + ## Heading 2 + ### Heading 3""" + ) + test_page.toc = get_toc(get_markdown_toc(test_page.markdown)) + return test_page + + def validate_full(data, page): + self.assertEqual(len(data), 4) + for x in data: + self.assertTrue(x['title']) + self.assertTrue(x['text']) + + def validate_sections(data, page): + # Sanity + self.assertEqual(len(data), 4) + # Page + self.assertEqual(data[0]['title'], page.title) + self.assertFalse(data[0]['text']) + # Headings + for x in data[1:]: + self.assertTrue(x['title']) + self.assertFalse(x['text']) + + def validate_titles(data, page): + # Sanity + self.assertEqual(len(data), 1) + for x in data: + self.assertFalse(x['text']) + + for option, validate in { + 'full': validate_full, + 'sections': validate_sections, + 'titles': validate_titles, + }.items(): + with self.subTest(option): + plugin = search.SearchPlugin() + + # Load plugin config, overriding indexing for test case + errors, warnings = plugin.load_config({'indexing': option}) + self.assertEqual(errors, []) + self.assertEqual(warnings, []) + + base_cfg = load_config(plugins=['search']) + base_cfg.plugins['search'].config.indexing = option + + pages = [ + test_page('Home', 'index.md', base_cfg), + test_page('About', 'about.md', base_cfg), + ] + + for page in pages: + index = search_index.SearchIndex(**plugin.config) + index.add_entry_from_context(page) + data = index.generate_search_index() + validate(json.loads(data)['docs'], page) + + @mock.patch('subprocess.Popen', autospec=True) + def test_prebuild_index(self, mock_popen): + # See https://stackoverflow.com/a/36501078/866026 + mock_popen.return_value = mock.Mock() + mock_popen_obj = mock_popen.return_value + mock_popen_obj.communicate.return_value = ('{"mock": "index"}', None) + mock_popen_obj.returncode = 0 + + index = search_index.SearchIndex(prebuild_index=True) + expected = { + 'docs': [], + 'config': {'prebuild_index': True}, + 'index': {'mock': 'index'}, + } + result = json.loads(index.generate_search_index()) + self.assertEqual(mock_popen.call_count, 1) + self.assertEqual(mock_popen_obj.communicate.call_count, 1) + self.assertEqual(result, expected) + + @mock.patch('subprocess.Popen', autospec=True) + def test_prebuild_index_returns_error(self, mock_popen): + # See https://stackoverflow.com/a/36501078/866026 + mock_popen.return_value = mock.Mock() + mock_popen_obj = mock_popen.return_value + mock_popen_obj.communicate.return_value = ('', 'Some Error') + mock_popen_obj.returncode = 0 + + index = search_index.SearchIndex(prebuild_index=True) + expected = { + 'docs': [], + 'config': {'prebuild_index': True}, + } + with self.assertLogs('mkdocs') as cm: + result = json.loads(index.generate_search_index()) + self.assertEqual( + '\n'.join(cm.output), + 'WARNING:mkdocs.contrib.search.search_index:Failed to pre-build search index. Error: Some Error', + ) + + self.assertEqual(mock_popen.call_count, 1) + self.assertEqual(mock_popen_obj.communicate.call_count, 1) + self.assertEqual(result, expected) + + @mock.patch('subprocess.Popen', autospec=True) + def test_prebuild_index_raises_ioerror(self, mock_popen): + # See https://stackoverflow.com/a/36501078/866026 + mock_popen.return_value = mock.Mock() + mock_popen_obj = mock_popen.return_value + mock_popen_obj.communicate.side_effect = OSError + mock_popen_obj.returncode = 1 + + index = search_index.SearchIndex(prebuild_index=True) + expected = { + 'docs': [], + 'config': {'prebuild_index': True}, + } + with self.assertLogs('mkdocs') as cm: + result = json.loads(index.generate_search_index()) + self.assertEqual( + '\n'.join(cm.output), + 'WARNING:mkdocs.contrib.search.search_index:Failed to pre-build search index. Error: ', + ) + + self.assertEqual(mock_popen.call_count, 1) + self.assertEqual(mock_popen_obj.communicate.call_count, 1) + self.assertEqual(result, expected) + + @mock.patch('subprocess.Popen', autospec=True, side_effect=OSError) + def test_prebuild_index_raises_oserror(self, mock_popen): + # See https://stackoverflow.com/a/36501078/866026 + mock_popen.return_value = mock.Mock() + mock_popen_obj = mock_popen.return_value + mock_popen_obj.communicate.return_value = ('foo', 'bar') + mock_popen_obj.returncode = 0 + + index = search_index.SearchIndex(prebuild_index=True) + expected = { + 'docs': [], + 'config': {'prebuild_index': True}, + } + with self.assertLogs('mkdocs') as cm: + result = json.loads(index.generate_search_index()) + self.assertEqual( + '\n'.join(cm.output), + 'WARNING:mkdocs.contrib.search.search_index:Failed to pre-build search index. Error: ', + ) + + self.assertEqual(mock_popen.call_count, 1) + self.assertEqual(mock_popen_obj.communicate.call_count, 0) + self.assertEqual(result, expected) + + @mock.patch('subprocess.Popen', autospec=True) + def test_prebuild_index_false(self, mock_popen): + # See https://stackoverflow.com/a/36501078/866026 + mock_popen.return_value = mock.Mock() + mock_popen_obj = mock_popen.return_value + mock_popen_obj.communicate.return_value = ('', '') + mock_popen_obj.returncode = 0 + + index = search_index.SearchIndex(prebuild_index=False) + expected = { + 'docs': [], + 'config': {'prebuild_index': False}, + } + result = json.loads(index.generate_search_index()) + self.assertEqual(mock_popen.call_count, 0) + self.assertEqual(mock_popen_obj.communicate.call_count, 0) + self.assertEqual(result, expected) + + @unittest.skipUnless(search_index.haslunrpy, 'lunr.py is not installed') + @mock.patch('mkdocs.contrib.search.search_index.lunr', autospec=True) + def test_prebuild_index_python(self, mock_lunr): + mock_lunr.return_value.serialize.return_value = {'mock': 'index'} + index = search_index.SearchIndex(prebuild_index='python', lang='en') + expected = { + 'docs': [], + 'config': {'prebuild_index': 'python', 'lang': 'en'}, + 'index': {'mock': 'index'}, + } + result = json.loads(index.generate_search_index()) + self.assertEqual(mock_lunr.call_count, 1) + self.assertEqual(result, expected) + + @unittest.skipIf(search_index.haslunrpy, 'lunr.py is installed') + def test_prebuild_index_python_missing_lunr(self): + # When the lunr.py dependencies are not installed no prebuilt index is created. + index = search_index.SearchIndex(prebuild_index='python', lang='en') + expected = { + 'docs': [], + 'config': {'prebuild_index': 'python', 'lang': 'en'}, + } + with self.assertLogs('mkdocs', level='WARNING'): + result = json.loads(index.generate_search_index()) + self.assertEqual(result, expected) + + @mock.patch('subprocess.Popen', autospec=True) + def test_prebuild_index_node(self, mock_popen): + # See https://stackoverflow.com/a/36501078/866026 + mock_popen.return_value = mock.Mock() + mock_popen_obj = mock_popen.return_value + mock_popen_obj.communicate.return_value = ('{"mock": "index"}', None) + mock_popen_obj.returncode = 0 + + index = search_index.SearchIndex(prebuild_index='node') + expected = { + 'docs': [], + 'config': {'prebuild_index': 'node'}, + 'index': {'mock': 'index'}, + } + result = json.loads(index.generate_search_index()) + self.assertEqual(mock_popen.call_count, 1) + self.assertEqual(mock_popen_obj.communicate.call_count, 1) + self.assertEqual(result, expected) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/structure/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/structure/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/structure/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/structure/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..72bc818ddbc76b0f82ddb6ff0b631978814f239a Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/structure/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/structure/__pycache__/file_tests.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/structure/__pycache__/file_tests.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..736cd0da099144305c99af8fa7b41fff5da5dbc9 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/structure/__pycache__/file_tests.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/structure/__pycache__/nav_tests.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/structure/__pycache__/nav_tests.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f4a686ebac788c98fe03d7e511598415bb365ea9 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/structure/__pycache__/nav_tests.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/structure/__pycache__/page_tests.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/structure/__pycache__/page_tests.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..76d5c27889a0131c33d2e981f1885f2bd0dcd392 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/structure/__pycache__/page_tests.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/structure/__pycache__/toc_tests.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/structure/__pycache__/toc_tests.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..69ba9874b4f3ab607a3c509627ec028fc0601656 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/structure/__pycache__/toc_tests.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/structure/file_tests.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/structure/file_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..86c107117b098cb061c8cf6e68cec5a6350e3495 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/structure/file_tests.py @@ -0,0 +1,747 @@ +import os +import sys +import unittest +from unittest import mock + +from mkdocs.structure.files import File, Files, _sort_files, get_files +from mkdocs.tests.base import PathAssertionMixin, load_config, tempdir + + +class TestFiles(PathAssertionMixin, unittest.TestCase): + def test_file_eq(self): + file = File('a.md', '/path/to/docs', '/path/to/site', use_directory_urls=False) + self.assertTrue( + file == File('a.md', '/path/to/docs', '/path/to/site', use_directory_urls=False) + ) + + def test_file_ne(self): + file = File('a.md', '/path/to/docs', '/path/to/site', use_directory_urls=False) + # Different filename + self.assertTrue( + file != File('b.md', '/path/to/docs', '/path/to/site', use_directory_urls=False) + ) + # Different src_path + self.assertTrue( + file != File('a.md', '/path/to/other', '/path/to/site', use_directory_urls=False) + ) + # Different URL + self.assertTrue( + file != File('a.md', '/path/to/docs', '/path/to/site', use_directory_urls=True) + ) + + @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows") + def test_src_path_windows(self): + f = File('foo\\a.md', '/path/to/docs', '/path/to/site', use_directory_urls=False) + self.assertEqual(f.src_uri, 'foo/a.md') + self.assertEqual(f.src_path, 'foo\\a.md') + f.src_uri = 'foo/b.md' + self.assertEqual(f.src_uri, 'foo/b.md') + self.assertEqual(f.src_path, 'foo\\b.md') + f.src_path = 'foo/c.md' + self.assertEqual(f.src_uri, 'foo/c.md') + self.assertEqual(f.src_path, 'foo\\c.md') + f.src_path = 'foo\\d.md' + self.assertEqual(f.src_uri, 'foo/d.md') + self.assertEqual(f.src_path, 'foo\\d.md') + f.src_uri = 'foo\\e.md' + self.assertEqual(f.src_uri, 'foo\\e.md') + self.assertEqual(f.src_path, 'foo\\e.md') + + def test_sort_files(self): + self.assertEqual( + _sort_files(['b.md', 'bb.md', 'a.md', 'index.md', 'aa.md']), + ['index.md', 'a.md', 'aa.md', 'b.md', 'bb.md'], + ) + + self.assertEqual( + _sort_files(['b.md', 'index.html', 'a.md', 'index.md']), + ['index.html', 'index.md', 'a.md', 'b.md'], + ) + + self.assertEqual( + _sort_files(['a.md', 'index.md', 'b.md', 'index.html']), + ['index.html', 'index.md', 'a.md', 'b.md'], + ) + + self.assertEqual( + _sort_files(['.md', '_.md', 'a.md', 'index.md', '1.md']), + ['index.md', '.md', '1.md', '_.md', 'a.md'], + ) + + self.assertEqual( + _sort_files(['a.md', 'b.md', 'a.md']), + ['a.md', 'a.md', 'b.md'], + ) + + self.assertEqual( + _sort_files(['A.md', 'B.md', 'README.md']), + ['README.md', 'A.md', 'B.md'], + ) + + def test_md_file(self): + f = File('foo.md', '/path/to/docs', '/path/to/site', use_directory_urls=False) + self.assertEqual(f.src_uri, 'foo.md') + self.assertPathsEqual(f.abs_src_path, '/path/to/docs/foo.md') + self.assertEqual(f.dest_uri, 'foo.html') + self.assertPathsEqual(f.abs_dest_path, '/path/to/site/foo.html') + self.assertEqual(f.url, 'foo.html') + self.assertEqual(f.name, 'foo') + self.assertTrue(f.is_documentation_page()) + self.assertFalse(f.is_static_page()) + self.assertFalse(f.is_media_file()) + self.assertFalse(f.is_javascript()) + self.assertFalse(f.is_css()) + + def test_md_file_use_directory_urls(self): + f = File('foo.md', '/path/to/docs', '/path/to/site', use_directory_urls=True) + self.assertEqual(f.src_uri, 'foo.md') + self.assertPathsEqual(f.abs_src_path, '/path/to/docs/foo.md') + self.assertEqual(f.dest_uri, 'foo/index.html') + self.assertPathsEqual(f.abs_dest_path, '/path/to/site/foo/index.html') + self.assertEqual(f.url, 'foo/') + self.assertEqual(f.name, 'foo') + self.assertTrue(f.is_documentation_page()) + self.assertFalse(f.is_static_page()) + self.assertFalse(f.is_media_file()) + self.assertFalse(f.is_javascript()) + self.assertFalse(f.is_css()) + + def test_md_file_nested(self): + f = File('foo/bar.md', '/path/to/docs', '/path/to/site', use_directory_urls=False) + self.assertEqual(f.src_uri, 'foo/bar.md') + self.assertPathsEqual(f.abs_src_path, '/path/to/docs/foo/bar.md') + self.assertEqual(f.dest_uri, 'foo/bar.html') + self.assertPathsEqual(f.abs_dest_path, '/path/to/site/foo/bar.html') + self.assertEqual(f.url, 'foo/bar.html') + self.assertEqual(f.name, 'bar') + self.assertTrue(f.is_documentation_page()) + self.assertFalse(f.is_static_page()) + self.assertFalse(f.is_media_file()) + self.assertFalse(f.is_javascript()) + self.assertFalse(f.is_css()) + + def test_md_file_nested_use_directory_urls(self): + f = File('foo/bar.md', '/path/to/docs', '/path/to/site', use_directory_urls=True) + self.assertEqual(f.src_uri, 'foo/bar.md') + self.assertPathsEqual(f.abs_src_path, '/path/to/docs/foo/bar.md') + self.assertEqual(f.dest_uri, 'foo/bar/index.html') + self.assertPathsEqual(f.abs_dest_path, '/path/to/site/foo/bar/index.html') + self.assertEqual(f.url, 'foo/bar/') + self.assertEqual(f.name, 'bar') + self.assertTrue(f.is_documentation_page()) + self.assertFalse(f.is_static_page()) + self.assertFalse(f.is_media_file()) + self.assertFalse(f.is_javascript()) + self.assertFalse(f.is_css()) + + def test_md_index_file(self): + f = File('index.md', '/path/to/docs', '/path/to/site', use_directory_urls=False) + self.assertEqual(f.src_uri, 'index.md') + self.assertPathsEqual(f.abs_src_path, '/path/to/docs/index.md') + self.assertEqual(f.dest_uri, 'index.html') + self.assertPathsEqual(f.abs_dest_path, '/path/to/site/index.html') + self.assertEqual(f.url, 'index.html') + self.assertEqual(f.name, 'index') + self.assertTrue(f.is_documentation_page()) + self.assertFalse(f.is_static_page()) + self.assertFalse(f.is_media_file()) + self.assertFalse(f.is_javascript()) + self.assertFalse(f.is_css()) + + def test_md_readme_index_file(self): + f = File('README.md', '/path/to/docs', '/path/to/site', use_directory_urls=False) + self.assertEqual(f.src_uri, 'README.md') + self.assertPathsEqual(f.abs_src_path, '/path/to/docs/README.md') + self.assertEqual(f.dest_uri, 'index.html') + self.assertPathsEqual(f.abs_dest_path, '/path/to/site/index.html') + self.assertEqual(f.url, 'index.html') + self.assertEqual(f.name, 'index') + self.assertTrue(f.is_documentation_page()) + self.assertFalse(f.is_static_page()) + self.assertFalse(f.is_media_file()) + self.assertFalse(f.is_javascript()) + self.assertFalse(f.is_css()) + + def test_md_index_file_use_directory_urls(self): + f = File('index.md', '/path/to/docs', '/path/to/site', use_directory_urls=True) + self.assertEqual(f.src_uri, 'index.md') + self.assertPathsEqual(f.abs_src_path, '/path/to/docs/index.md') + self.assertEqual(f.dest_uri, 'index.html') + self.assertPathsEqual(f.abs_dest_path, '/path/to/site/index.html') + self.assertEqual(f.url, './') + self.assertEqual(f.name, 'index') + self.assertTrue(f.is_documentation_page()) + self.assertFalse(f.is_static_page()) + self.assertFalse(f.is_media_file()) + self.assertFalse(f.is_javascript()) + self.assertFalse(f.is_css()) + + def test_md_readme_index_file_use_directory_urls(self): + f = File('README.md', '/path/to/docs', '/path/to/site', use_directory_urls=True) + self.assertEqual(f.src_uri, 'README.md') + self.assertPathsEqual(f.abs_src_path, '/path/to/docs/README.md') + self.assertEqual(f.dest_uri, 'index.html') + self.assertPathsEqual(f.abs_dest_path, '/path/to/site/index.html') + self.assertEqual(f.url, './') + self.assertEqual(f.name, 'index') + self.assertTrue(f.is_documentation_page()) + self.assertFalse(f.is_static_page()) + self.assertFalse(f.is_media_file()) + self.assertFalse(f.is_javascript()) + self.assertFalse(f.is_css()) + + def test_md_index_file_nested(self): + f = File('foo/index.md', '/path/to/docs', '/path/to/site', use_directory_urls=False) + self.assertEqual(f.src_uri, 'foo/index.md') + self.assertPathsEqual(f.abs_src_path, '/path/to/docs/foo/index.md') + self.assertEqual(f.dest_uri, 'foo/index.html') + self.assertPathsEqual(f.abs_dest_path, '/path/to/site/foo/index.html') + self.assertEqual(f.url, 'foo/index.html') + self.assertEqual(f.name, 'index') + self.assertTrue(f.is_documentation_page()) + self.assertFalse(f.is_static_page()) + self.assertFalse(f.is_media_file()) + self.assertFalse(f.is_javascript()) + self.assertFalse(f.is_css()) + + def test_md_index_file_nested_use_directory_urls(self): + f = File('foo/index.md', '/path/to/docs', '/path/to/site', use_directory_urls=True) + self.assertEqual(f.src_uri, 'foo/index.md') + self.assertPathsEqual(f.abs_src_path, '/path/to/docs/foo/index.md') + self.assertEqual(f.dest_uri, 'foo/index.html') + self.assertPathsEqual(f.abs_dest_path, '/path/to/site/foo/index.html') + self.assertEqual(f.url, 'foo/') + self.assertEqual(f.name, 'index') + self.assertTrue(f.is_documentation_page()) + self.assertFalse(f.is_static_page()) + self.assertFalse(f.is_media_file()) + self.assertFalse(f.is_javascript()) + self.assertFalse(f.is_css()) + + def test_static_file(self): + f = File('foo/bar.html', '/path/to/docs', '/path/to/site', use_directory_urls=False) + self.assertEqual(f.src_uri, 'foo/bar.html') + self.assertPathsEqual(f.abs_src_path, '/path/to/docs/foo/bar.html') + self.assertEqual(f.dest_uri, 'foo/bar.html') + self.assertPathsEqual(f.abs_dest_path, '/path/to/site/foo/bar.html') + self.assertEqual(f.url, 'foo/bar.html') + self.assertEqual(f.name, 'bar') + self.assertFalse(f.is_documentation_page()) + self.assertTrue(f.is_static_page()) + self.assertFalse(f.is_media_file()) + self.assertFalse(f.is_javascript()) + self.assertFalse(f.is_css()) + + def test_static_file_use_directory_urls(self): + f = File('foo/bar.html', '/path/to/docs', '/path/to/site', use_directory_urls=True) + self.assertEqual(f.src_uri, 'foo/bar.html') + self.assertPathsEqual(f.abs_src_path, '/path/to/docs/foo/bar.html') + self.assertEqual(f.dest_uri, 'foo/bar.html') + self.assertPathsEqual(f.abs_dest_path, '/path/to/site/foo/bar.html') + self.assertEqual(f.url, 'foo/bar.html') + self.assertEqual(f.name, 'bar') + self.assertFalse(f.is_documentation_page()) + self.assertTrue(f.is_static_page()) + self.assertFalse(f.is_media_file()) + self.assertFalse(f.is_javascript()) + self.assertFalse(f.is_css()) + + def test_media_file(self): + f = File('foo/bar.jpg', '/path/to/docs', '/path/to/site', use_directory_urls=False) + self.assertEqual(f.src_uri, 'foo/bar.jpg') + self.assertPathsEqual(f.abs_src_path, '/path/to/docs/foo/bar.jpg') + self.assertEqual(f.dest_uri, 'foo/bar.jpg') + self.assertPathsEqual(f.abs_dest_path, '/path/to/site/foo/bar.jpg') + self.assertEqual(f.url, 'foo/bar.jpg') + self.assertEqual(f.name, 'bar') + self.assertFalse(f.is_documentation_page()) + self.assertFalse(f.is_static_page()) + self.assertTrue(f.is_media_file()) + self.assertFalse(f.is_javascript()) + self.assertFalse(f.is_css()) + + def test_media_file_use_directory_urls(self): + f = File('foo/bar.jpg', '/path/to/docs', '/path/to/site', use_directory_urls=True) + self.assertEqual(f.src_uri, 'foo/bar.jpg') + self.assertPathsEqual(f.abs_src_path, '/path/to/docs/foo/bar.jpg') + self.assertEqual(f.dest_uri, 'foo/bar.jpg') + self.assertPathsEqual(f.abs_dest_path, '/path/to/site/foo/bar.jpg') + self.assertEqual(f.url, 'foo/bar.jpg') + self.assertEqual(f.name, 'bar') + self.assertFalse(f.is_documentation_page()) + self.assertFalse(f.is_static_page()) + self.assertTrue(f.is_media_file()) + self.assertFalse(f.is_javascript()) + self.assertFalse(f.is_css()) + + def test_javascript_file(self): + f = File('foo/bar.js', '/path/to/docs', '/path/to/site', use_directory_urls=False) + self.assertEqual(f.src_uri, 'foo/bar.js') + self.assertPathsEqual(f.abs_src_path, '/path/to/docs/foo/bar.js') + self.assertEqual(f.dest_uri, 'foo/bar.js') + self.assertPathsEqual(f.abs_dest_path, '/path/to/site/foo/bar.js') + self.assertEqual(f.url, 'foo/bar.js') + self.assertEqual(f.name, 'bar') + self.assertFalse(f.is_documentation_page()) + self.assertFalse(f.is_static_page()) + self.assertTrue(f.is_media_file()) + self.assertTrue(f.is_javascript()) + self.assertFalse(f.is_css()) + + def test_javascript_file_use_directory_urls(self): + f = File('foo/bar.js', '/path/to/docs', '/path/to/site', use_directory_urls=True) + self.assertEqual(f.src_uri, 'foo/bar.js') + self.assertPathsEqual(f.abs_src_path, '/path/to/docs/foo/bar.js') + self.assertEqual(f.dest_uri, 'foo/bar.js') + self.assertPathsEqual(f.abs_dest_path, '/path/to/site/foo/bar.js') + self.assertEqual(f.url, 'foo/bar.js') + self.assertEqual(f.name, 'bar') + self.assertFalse(f.is_documentation_page()) + self.assertFalse(f.is_static_page()) + self.assertTrue(f.is_media_file()) + self.assertTrue(f.is_javascript()) + self.assertFalse(f.is_css()) + + def test_css_file(self): + f = File('foo/bar.css', '/path/to/docs', '/path/to/site', use_directory_urls=False) + self.assertEqual(f.src_uri, 'foo/bar.css') + self.assertPathsEqual(f.abs_src_path, '/path/to/docs/foo/bar.css') + self.assertEqual(f.dest_uri, 'foo/bar.css') + self.assertPathsEqual(f.abs_dest_path, '/path/to/site/foo/bar.css') + self.assertEqual(f.url, 'foo/bar.css') + self.assertEqual(f.name, 'bar') + self.assertFalse(f.is_documentation_page()) + self.assertFalse(f.is_static_page()) + self.assertTrue(f.is_media_file()) + self.assertFalse(f.is_javascript()) + self.assertTrue(f.is_css()) + + def test_css_file_use_directory_urls(self): + f = File('foo/bar.css', '/path/to/docs', '/path/to/site', use_directory_urls=True) + self.assertEqual(f.src_uri, 'foo/bar.css') + self.assertPathsEqual(f.abs_src_path, '/path/to/docs/foo/bar.css') + self.assertEqual(f.dest_uri, 'foo/bar.css') + self.assertPathsEqual(f.abs_dest_path, '/path/to/site/foo/bar.css') + self.assertEqual(f.url, 'foo/bar.css') + self.assertEqual(f.name, 'bar') + self.assertFalse(f.is_documentation_page()) + self.assertFalse(f.is_static_page()) + self.assertTrue(f.is_media_file()) + self.assertFalse(f.is_javascript()) + self.assertTrue(f.is_css()) + + def test_file_name_with_space(self): + f = File('foo bar.md', '/path/to/docs', '/path/to/site', use_directory_urls=False) + self.assertEqual(f.src_uri, 'foo bar.md') + self.assertPathsEqual(f.abs_src_path, '/path/to/docs/foo bar.md') + self.assertEqual(f.dest_uri, 'foo bar.html') + self.assertPathsEqual(f.abs_dest_path, '/path/to/site/foo bar.html') + self.assertEqual(f.url, 'foo%20bar.html') + self.assertEqual(f.name, 'foo bar') + + def test_file_name_with_custom_dest_uri(self): + for use_directory_urls in True, False: + with self.subTest(use_directory_urls=use_directory_urls): + f = File( + 'stuff/foo.md', + src_dir='/path/to/docs', + dest_dir='/path/to/site', + use_directory_urls=use_directory_urls, + dest_uri='stuff/1-foo/index.html', + ) + self.assertEqual(f.src_uri, 'stuff/foo.md') + self.assertPathsEqual(f.abs_src_path, '/path/to/docs/stuff/foo.md') + self.assertEqual(f.dest_uri, 'stuff/1-foo/index.html') + self.assertPathsEqual(f.abs_dest_path, '/path/to/site/stuff/1-foo/index.html') + if use_directory_urls: + self.assertEqual(f.url, 'stuff/1-foo/') + else: + self.assertEqual(f.url, 'stuff/1-foo/index.html') + self.assertEqual(f.name, 'foo') + + def test_files(self): + fs = [ + File('index.md', '/path/to/docs', '/path/to/site', use_directory_urls=True), + File('foo/bar.md', '/path/to/docs', '/path/to/site', use_directory_urls=True), + File('foo/bar.html', '/path/to/docs', '/path/to/site', use_directory_urls=True), + File('foo/bar.jpg', '/path/to/docs', '/path/to/site', use_directory_urls=True), + File('foo/bar.js', '/path/to/docs', '/path/to/site', use_directory_urls=True), + File('foo/bar.css', '/path/to/docs', '/path/to/site', use_directory_urls=True), + ] + files = Files(fs) + self.assertEqual(list(files), fs) + self.assertEqual(len(files), 6) + self.assertEqual(files.documentation_pages(), [fs[0], fs[1]]) + self.assertEqual(files.static_pages(), [fs[2]]) + self.assertEqual(files.media_files(), [fs[3], fs[4], fs[5]]) + self.assertEqual(files.javascript_files(), [fs[4]]) + self.assertEqual(files.css_files(), [fs[5]]) + self.assertEqual(files.get_file_from_path('foo/bar.jpg'), fs[3]) + self.assertEqual(files.get_file_from_path('foo/bar.jpg'), fs[3]) + self.assertEqual(files.get_file_from_path('missing.jpg'), None) + self.assertTrue(fs[2].src_uri in files.src_uris) + extra_file = File('extra.md', '/path/to/docs', '/path/to/site', use_directory_urls=True) + self.assertFalse(extra_file.src_uri in files.src_uris) + files.append(extra_file) + self.assertEqual(len(files), 7) + self.assertTrue(extra_file.src_uri in files.src_uris) + self.assertEqual(files.documentation_pages(), [fs[0], fs[1], extra_file]) + files.remove(fs[1]) + self.assertEqual(files.documentation_pages(), [fs[0], extra_file]) + + @tempdir( + files=[ + 'favicon.ico', + 'index.md', + ] + ) + @tempdir( + files=[ + 'base.html', + 'favicon.ico', + 'style.css', + 'foo.md', + 'README', + '.ignore.txt', + '.ignore/file.txt', + 'foo/.ignore.txt', + 'foo/.ignore/file.txt', + ] + ) + def test_add_files_from_theme(self, tdir, ddir): + config = load_config(docs_dir=ddir, theme={'name': None, 'custom_dir': tdir}) + env = config.theme.get_env() + files = get_files(config) + self.assertEqual( + [file.src_path for file in files], + ['index.md', 'favicon.ico'], + ) + files.add_files_from_theme(env, config) + self.assertEqual( + [file.src_path for file in files], + ['index.md', 'favicon.ico', 'style.css'], + ) + # Ensure theme file does not override docs_dir file + self.assertEqual( + files.get_file_from_path('favicon.ico').abs_src_path, + os.path.normpath(os.path.join(ddir, 'favicon.ico')), + ) + + def test_get_relative_url_use_directory_urls(self): + to_files = [ + 'index.md', + 'foo/index.md', + 'foo/bar/index.md', + 'foo/bar/baz/index.md', + 'foo.md', + 'foo/bar.md', + 'foo/bar/baz.md', + ] + to_file_urls = [ + './', + 'foo/', + 'foo/bar/', + 'foo/bar/baz/', + 'foo/', + 'foo/bar/', + 'foo/bar/baz/', + ] + + from_file = File('img.jpg', '/path/to/docs', '/path/to/site', use_directory_urls=True) + self.assertEqual(from_file.url, 'img.jpg') + + expected = [ + 'img.jpg', # img.jpg relative to . + '../img.jpg', # img.jpg relative to foo/ + '../../img.jpg', # img.jpg relative to foo/bar/ + '../../../img.jpg', # img.jpg relative to foo/bar/baz/ + '../img.jpg', # img.jpg relative to foo + '../../img.jpg', # img.jpg relative to foo/bar + '../../../img.jpg', # img.jpg relative to foo/bar/baz + ] + for i, filename in enumerate(to_files): + file = File(filename, '/path/to/docs', '/path/to/site', use_directory_urls=True) + self.assertEqual(file.url, to_file_urls[i]) + self.assertEqual(from_file.url_relative_to(file.url), expected[i]) + self.assertEqual(from_file.url_relative_to(file), expected[i]) + + from_file = File('foo/img.jpg', '/path/to/docs', '/path/to/site', use_directory_urls=True) + self.assertEqual(from_file.url, 'foo/img.jpg') + + expected = [ + 'foo/img.jpg', # foo/img.jpg relative to . + 'img.jpg', # foo/img.jpg relative to foo/ + '../img.jpg', # foo/img.jpg relative to foo/bar/ + '../../img.jpg', # foo/img.jpg relative to foo/bar/baz/ + 'img.jpg', # foo/img.jpg relative to foo + '../img.jpg', # foo/img.jpg relative to foo/bar + '../../img.jpg', # foo/img.jpg relative to foo/bar/baz + ] + for i, filename in enumerate(to_files): + file = File(filename, '/path/to/docs', '/path/to/site', use_directory_urls=True) + self.assertEqual(file.url, to_file_urls[i]) + self.assertEqual(from_file.url_relative_to(file.url), expected[i]) + self.assertEqual(from_file.url_relative_to(file), expected[i]) + + from_file = File('index.html', '/path/to/docs', '/path/to/site', use_directory_urls=True) + self.assertEqual(from_file.url, './') + + expected = [ + './', # . relative to . + '../', # . relative to foo/ + '../../', # . relative to foo/bar/ + '../../../', # . relative to foo/bar/baz/ + '../', # . relative to foo + '../../', # . relative to foo/bar + '../../../', # . relative to foo/bar/baz + ] + for i, filename in enumerate(to_files): + file = File(filename, '/path/to/docs', '/path/to/site', use_directory_urls=True) + self.assertEqual(file.url, to_file_urls[i]) + self.assertEqual(from_file.url_relative_to(file.url), expected[i]) + self.assertEqual(from_file.url_relative_to(file), expected[i]) + + from_file = File('file.md', '/path/to/docs', '/path/to/site', use_directory_urls=True) + self.assertEqual(from_file.url, 'file/') + + expected = [ + 'file/', # file relative to . + '../file/', # file relative to foo/ + '../../file/', # file relative to foo/bar/ + '../../../file/', # file relative to foo/bar/baz/ + '../file/', # file relative to foo + '../../file/', # file relative to foo/bar + '../../../file/', # file relative to foo/bar/baz + ] + for i, filename in enumerate(to_files): + file = File(filename, '/path/to/docs', '/path/to/site', use_directory_urls=True) + self.assertEqual(file.url, to_file_urls[i]) + self.assertEqual(from_file.url_relative_to(file.url), expected[i]) + self.assertEqual(from_file.url_relative_to(file), expected[i]) + + def test_get_relative_url(self): + to_files = [ + 'index.md', + 'foo/index.md', + 'foo/bar/index.md', + 'foo/bar/baz/index.md', + 'foo.md', + 'foo/bar.md', + 'foo/bar/baz.md', + ] + to_file_urls = [ + 'index.html', + 'foo/index.html', + 'foo/bar/index.html', + 'foo/bar/baz/index.html', + 'foo.html', + 'foo/bar.html', + 'foo/bar/baz.html', + ] + + from_file = File('img.jpg', '/path/to/docs', '/path/to/site', use_directory_urls=False) + self.assertEqual(from_file.url, 'img.jpg') + + expected = [ + 'img.jpg', # img.jpg relative to . + '../img.jpg', # img.jpg relative to foo/ + '../../img.jpg', # img.jpg relative to foo/bar/ + '../../../img.jpg', # img.jpg relative to foo/bar/baz/ + 'img.jpg', # img.jpg relative to foo.html + '../img.jpg', # img.jpg relative to foo/bar.html + '../../img.jpg', # img.jpg relative to foo/bar/baz.html + ] + for i, filename in enumerate(to_files): + with self.subTest(from_file=from_file.src_path, to_file=filename): + file = File(filename, '/path/to/docs', '/path/to/site', use_directory_urls=False) + self.assertEqual(file.url, to_file_urls[i]) + self.assertEqual(from_file.url_relative_to(file.url), expected[i]) + self.assertEqual(from_file.url_relative_to(file), expected[i]) + + from_file = File('foo/img.jpg', '/path/to/docs', '/path/to/site', use_directory_urls=False) + self.assertEqual(from_file.url, 'foo/img.jpg') + + expected = [ + 'foo/img.jpg', # foo/img.jpg relative to . + 'img.jpg', # foo/img.jpg relative to foo/ + '../img.jpg', # foo/img.jpg relative to foo/bar/ + '../../img.jpg', # foo/img.jpg relative to foo/bar/baz/ + 'foo/img.jpg', # foo/img.jpg relative to foo.html + 'img.jpg', # foo/img.jpg relative to foo/bar.html + '../img.jpg', # foo/img.jpg relative to foo/bar/baz.html + ] + for i, filename in enumerate(to_files): + with self.subTest(from_file=from_file.src_path, to_file=filename): + file = File(filename, '/path/to/docs', '/path/to/site', use_directory_urls=False) + self.assertEqual(file.url, to_file_urls[i]) + self.assertEqual(from_file.url_relative_to(file.url), expected[i]) + self.assertEqual(from_file.url_relative_to(file), expected[i]) + + from_file = File('index.html', '/path/to/docs', '/path/to/site', use_directory_urls=False) + self.assertEqual(from_file.url, 'index.html') + + expected = [ + 'index.html', # index.html relative to . + '../index.html', # index.html relative to foo/ + '../../index.html', # index.html relative to foo/bar/ + '../../../index.html', # index.html relative to foo/bar/baz/ + 'index.html', # index.html relative to foo.html + '../index.html', # index.html relative to foo/bar.html + '../../index.html', # index.html relative to foo/bar/baz.html + ] + for i, filename in enumerate(to_files): + with self.subTest(from_file=from_file.src_path, to_file=filename): + file = File(filename, '/path/to/docs', '/path/to/site', use_directory_urls=False) + self.assertEqual(file.url, to_file_urls[i]) + self.assertEqual(from_file.url_relative_to(file.url), expected[i]) + self.assertEqual(from_file.url_relative_to(file), expected[i]) + + from_file = File('file.html', '/path/to/docs', '/path/to/site', use_directory_urls=False) + self.assertEqual(from_file.url, 'file.html') + + expected = [ + 'file.html', # file.html relative to . + '../file.html', # file.html relative to foo/ + '../../file.html', # file.html relative to foo/bar/ + '../../../file.html', # file.html relative to foo/bar/baz/ + 'file.html', # file.html relative to foo.html + '../file.html', # file.html relative to foo/bar.html + '../../file.html', # file.html relative to foo/bar/baz.html + ] + for i, filename in enumerate(to_files): + with self.subTest(from_file=from_file.src_path, to_file=filename): + file = File(filename, '/path/to/docs', '/path/to/site', use_directory_urls=False) + self.assertEqual(file.url, to_file_urls[i]) + self.assertEqual(from_file.url_relative_to(file.url), expected[i]) + self.assertEqual(from_file.url_relative_to(file), expected[i]) + + @tempdir( + files=[ + 'index.md', + 'readme.md', + 'bar.css', + 'bar.html', + 'bar.jpg', + 'bar.js', + 'bar.md', + '.dotfile', + 'templates/foo.html', + ] + ) + def test_get_files(self, tdir): + config = load_config(docs_dir=tdir, extra_css=['bar.css'], extra_javascript=['bar.js']) + files = get_files(config) + self.assertIsInstance(files, Files) + self.assertEqual( + [f.src_path for f in files if f.inclusion.is_included()], + ['index.md', 'bar.css', 'bar.html', 'bar.jpg', 'bar.js', 'bar.md', 'readme.md'], + ) + self.assertEqual( + [f.src_path for f in files if f.inclusion.is_excluded()], + ['.dotfile', 'templates/foo.html'], + ) + + @tempdir( + files=[ + 'README.md', + 'foo.md', + ] + ) + def test_get_files_include_readme_without_index(self, tdir): + config = load_config(docs_dir=tdir) + files = get_files(config) + self.assertIsInstance(files, Files) + self.assertEqual([f.src_path for f in files], ['README.md', 'foo.md']) + + @tempdir( + files=[ + 'index.md', + 'README.md', + 'foo.md', + ] + ) + def test_get_files_exclude_readme_with_index(self, tdir): + config = load_config(docs_dir=tdir) + with self.assertLogs('mkdocs') as cm: + files = get_files(config) + self.assertRegex( + '\n'.join(cm.output), + r"^WARNING:mkdocs.structure.files:" + r"Excluding 'README.md' from the site because it conflicts with 'index.md'.$", + ) + self.assertIsInstance(files, Files) + self.assertEqual([f.src_path for f in files], ['index.md', 'foo.md']) + + @tempdir() + @tempdir(files={'test.txt': 'source content'}) + def test_copy_file(self, src_dir, dest_dir): + file = File('test.txt', src_dir, dest_dir, use_directory_urls=False) + dest_path = os.path.join(dest_dir, 'test.txt') + self.assertPathNotExists(dest_path) + file.copy_file() + self.assertPathIsFile(dest_path) + + @tempdir(files={'test.txt': 'source content'}) + def test_copy_file_same_file(self, dest_dir): + file = File('test.txt', dest_dir, dest_dir, use_directory_urls=False) + dest_path = os.path.join(dest_dir, 'test.txt') + file.copy_file() + self.assertPathIsFile(dest_path) + with open(dest_path, encoding='utf-8') as f: + self.assertEqual(f.read(), 'source content') + + @tempdir(files={'test.txt': 'destination content'}) + @tempdir(files={'test.txt': 'source content'}) + def test_copy_file_clean_modified(self, src_dir, dest_dir): + file = File('test.txt', src_dir, dest_dir, use_directory_urls=False) + file.is_modified = mock.Mock(return_value=True) + dest_path = os.path.join(dest_dir, 'test.txt') + file.copy_file(dirty=False) + self.assertPathIsFile(dest_path) + with open(dest_path, encoding='utf-8') as f: + self.assertEqual(f.read(), 'source content') + + @tempdir(files={'test.txt': 'destination content'}) + @tempdir(files={'test.txt': 'source content'}) + def test_copy_file_dirty_modified(self, src_dir, dest_dir): + file = File('test.txt', src_dir, dest_dir, use_directory_urls=False) + file.is_modified = mock.Mock(return_value=True) + dest_path = os.path.join(dest_dir, 'test.txt') + file.copy_file(dirty=True) + self.assertPathIsFile(dest_path) + with open(dest_path, encoding='utf-8') as f: + self.assertEqual(f.read(), 'source content') + + @tempdir(files={'test.txt': 'destination content'}) + @tempdir(files={'test.txt': 'source content'}) + def test_copy_file_dirty_not_modified(self, src_dir, dest_dir): + file = File('test.txt', src_dir, dest_dir, use_directory_urls=False) + file.is_modified = mock.Mock(return_value=False) + dest_path = os.path.join(dest_dir, 'test.txt') + file.copy_file(dirty=True) + self.assertPathIsFile(dest_path) + with open(dest_path, encoding='utf-8') as f: + self.assertEqual(f.read(), 'destination content') + + def test_files_append_remove_src_paths(self): + fs = [ + File('index.md', '/path/to/docs', '/path/to/site', use_directory_urls=True), + File('foo/bar.md', '/path/to/docs', '/path/to/site', use_directory_urls=True), + File('foo/bar.html', '/path/to/docs', '/path/to/site', use_directory_urls=True), + File('foo/bar.jpg', '/path/to/docs', '/path/to/site', use_directory_urls=True), + File('foo/bar.js', '/path/to/docs', '/path/to/site', use_directory_urls=True), + File('foo/bar.css', '/path/to/docs', '/path/to/site', use_directory_urls=True), + ] + files = Files(fs) + self.assertEqual(len(files), 6) + self.assertEqual(len(files.src_uris), 6) + extra_file = File('extra.md', '/path/to/docs', '/path/to/site', use_directory_urls=True) + self.assertFalse(extra_file.src_uri in files.src_uris) + files.append(extra_file) + self.assertEqual(len(files), 7) + self.assertEqual(len(files.src_uris), 7) + self.assertTrue(extra_file.src_uri in files.src_uris) + files.remove(extra_file) + self.assertEqual(len(files), 6) + self.assertEqual(len(files.src_uris), 6) + self.assertFalse(extra_file.src_uri in files.src_uris) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/structure/nav_tests.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/structure/nav_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..44ae2adc21be110b83a0e42f16d4bbb3afbfeb4b --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/structure/nav_tests.py @@ -0,0 +1,483 @@ +#!/usr/bin/env python + +import sys +import unittest + +from mkdocs.structure.files import File, Files +from mkdocs.structure.nav import Section, _get_by_type, get_navigation +from mkdocs.structure.pages import Page +from mkdocs.tests.base import dedent, load_config + + +class SiteNavigationTests(unittest.TestCase): + maxDiff = None + + def test_simple_nav(self): + nav_cfg = [ + {'Home': 'index.md'}, + {'About': 'about.md'}, + ] + expected = dedent( + """ + Page(title='Home', url='/') + Page(title='About', url='/about/') + """ + ) + cfg = load_config(nav=nav_cfg, site_url='http://example.com/') + fs = [ + File(list(item.values())[0], cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls) + for item in nav_cfg + ] + files = Files(fs) + site_navigation = get_navigation(files, cfg) + self.assertEqual(str(site_navigation).strip(), expected) + self.assertEqual(len(site_navigation.items), 2) + self.assertEqual(len(site_navigation.pages), 2) + self.assertEqual(repr(site_navigation.homepage), "Page(title='Home', url='/')") + + def test_nav_no_directory_urls(self): + nav_cfg = [ + {'Home': 'index.md'}, + {'About': 'about.md'}, + ] + expected = dedent( + """ + Page(title='Home', url='/index.html') + Page(title='About', url='/about.html') + """ + ) + cfg = load_config(nav=nav_cfg, use_directory_urls=False, site_url='http://example.com/') + fs = [ + File(list(item.values())[0], cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls) + for item in nav_cfg + ] + files = Files(fs) + site_navigation = get_navigation(files, cfg) + self.assertEqual(str(site_navigation).strip(), expected) + self.assertEqual(len(site_navigation.items), 2) + self.assertEqual(len(site_navigation.pages), 2) + self.assertEqual(repr(site_navigation.homepage), "Page(title='Home', url='/index.html')") + + def test_nav_missing_page(self): + nav_cfg = [ + {'Home': 'index.md'}, + ] + expected = dedent( + """ + Page(title='Home', url='/') + """ + ) + cfg = load_config(nav=nav_cfg, site_url='http://example.com/') + fs = [ + File('index.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls), + File('page_not_in_nav.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls), + ] + files = Files(fs) + site_navigation = get_navigation(files, cfg) + self.assertEqual(str(site_navigation).strip(), expected) + self.assertEqual(len(site_navigation.items), 1) + self.assertEqual(len(site_navigation.pages), 1) + for file in files: + self.assertIsInstance(file.page, Page) + + def test_nav_no_title(self): + nav_cfg = [ + 'index.md', + {'About': 'about.md'}, + ] + expected = dedent( + """ + Page(title=[blank], url='/') + Page(title='About', url='/about/') + """ + ) + cfg = load_config(nav=nav_cfg, site_url='http://example.com/') + fs = [ + File(nav_cfg[0], cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls), + File(nav_cfg[1]['About'], cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls), + ] + files = Files(fs) + site_navigation = get_navigation(files, cfg) + self.assertEqual(str(site_navigation).strip(), expected) + self.assertEqual(len(site_navigation.items), 2) + self.assertEqual(len(site_navigation.pages), 2) + + def test_nav_external_links(self): + nav_cfg = [ + {'Home': 'index.md'}, + {'Local': '/local.html'}, + {'External': 'http://example.com/external.html'}, + ] + expected = dedent( + """ + Page(title='Home', url='/') + Link(title='Local', url='/local.html') + Link(title='External', url='http://example.com/external.html') + """ + ) + cfg = load_config(nav=nav_cfg, site_url='http://example.com/') + fs = [File('index.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls)] + files = Files(fs) + with self.assertLogs('mkdocs', level='DEBUG') as cm: + site_navigation = get_navigation(files, cfg) + self.assertEqual( + cm.output, + [ + "INFO:mkdocs.structure.nav:An absolute path to '/local.html' is included in the 'nav' configuration, which presumably points to an external resource.", + "DEBUG:mkdocs.structure.nav:An external link to 'http://example.com/external.html' is included in the 'nav' configuration.", + ], + ) + self.assertEqual(str(site_navigation).strip(), expected) + self.assertEqual(len(site_navigation.items), 3) + self.assertEqual(len(site_navigation.pages), 1) + + def test_nav_bad_links(self): + nav_cfg = [ + {'Home': 'index.md'}, + {'Missing': 'missing.html'}, + {'Bad External': 'example.com'}, + ] + expected = dedent( + """ + Page(title='Home', url='/') + Link(title='Missing', url='missing.html') + Link(title='Bad External', url='example.com') + """ + ) + cfg = load_config(nav=nav_cfg, site_url='http://example.com/') + fs = [File('index.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls)] + files = Files(fs) + with self.assertLogs('mkdocs') as cm: + site_navigation = get_navigation(files, cfg) + self.assertEqual( + cm.output, + [ + "WARNING:mkdocs.structure.nav:A relative path to 'missing.html' is included in the 'nav' configuration, which is not found in the documentation files.", + "WARNING:mkdocs.structure.nav:A relative path to 'example.com' is included in the 'nav' configuration, which is not found in the documentation files.", + ], + ) + self.assertEqual(str(site_navigation).strip(), expected) + self.assertEqual(len(site_navigation.items), 3) + self.assertEqual(len(site_navigation.pages), 1) + + def test_indented_nav(self): + nav_cfg = [ + {'Home': 'index.md'}, + { + 'API Guide': [ + {'Running': 'api-guide/running.md'}, + {'Testing': 'api-guide/testing.md'}, + {'Debugging': 'api-guide/debugging.md'}, + { + 'Advanced': [ + {'Part 1': 'api-guide/advanced/part-1.md'}, + ] + }, + ] + }, + { + 'About': [ + {'Release notes': 'about/release-notes.md'}, + {'License': '/license.html'}, + ] + }, + {'External': 'https://example.com/'}, + ] + expected = dedent( + """ + Page(title='Home', url='/') + Section(title='API Guide') + Page(title='Running', url='/api-guide/running/') + Page(title='Testing', url='/api-guide/testing/') + Page(title='Debugging', url='/api-guide/debugging/') + Section(title='Advanced') + Page(title='Part 1', url='/api-guide/advanced/part-1/') + Section(title='About') + Page(title='Release notes', url='/about/release-notes/') + Link(title='License', url='/license.html') + Link(title='External', url='https://example.com/') + """ + ) + cfg = load_config(nav=nav_cfg, site_url='http://example.com/') + fs = [ + 'index.md', + 'api-guide/running.md', + 'api-guide/testing.md', + 'api-guide/debugging.md', + 'api-guide/advanced/part-1.md', + 'about/release-notes.md', + ] + files = Files([File(s, cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls) for s in fs]) + site_navigation = get_navigation(files, cfg) + self.assertEqual(str(site_navigation).strip(), expected) + self.assertEqual(len(site_navigation.items), 4) + self.assertEqual(len(site_navigation.pages), 6) + self.assertEqual(repr(site_navigation.homepage), "Page(title='Home', url='/')") + self.assertIsNone(site_navigation.items[0].parent) + self.assertEqual(site_navigation.items[0].ancestors, []) + self.assertIsNone(site_navigation.items[1].parent) + self.assertEqual(site_navigation.items[1].ancestors, []) + self.assertEqual(len(site_navigation.items[1].children), 4) + self.assertEqual( + repr(site_navigation.items[1].children[0].parent), "Section(title='API Guide')" + ) + self.assertEqual(site_navigation.items[1].children[0].ancestors, [site_navigation.items[1]]) + self.assertEqual( + repr(site_navigation.items[1].children[1].parent), "Section(title='API Guide')" + ) + self.assertEqual(site_navigation.items[1].children[1].ancestors, [site_navigation.items[1]]) + self.assertEqual( + repr(site_navigation.items[1].children[2].parent), "Section(title='API Guide')" + ) + self.assertEqual(site_navigation.items[1].children[2].ancestors, [site_navigation.items[1]]) + self.assertEqual( + repr(site_navigation.items[1].children[3].parent), "Section(title='API Guide')" + ) + self.assertEqual(site_navigation.items[1].children[3].ancestors, [site_navigation.items[1]]) + self.assertEqual(len(site_navigation.items[1].children[3].children), 1) + self.assertEqual( + repr(site_navigation.items[1].children[3].children[0].parent), + "Section(title='Advanced')", + ) + self.assertEqual( + site_navigation.items[1].children[3].children[0].ancestors, + [site_navigation.items[1].children[3], site_navigation.items[1]], + ) + self.assertIsNone(site_navigation.items[2].parent) + self.assertEqual(len(site_navigation.items[2].children), 2) + self.assertEqual( + repr(site_navigation.items[2].children[0].parent), "Section(title='About')" + ) + self.assertEqual(site_navigation.items[2].children[0].ancestors, [site_navigation.items[2]]) + self.assertEqual( + repr(site_navigation.items[2].children[1].parent), "Section(title='About')" + ) + self.assertEqual(site_navigation.items[2].children[1].ancestors, [site_navigation.items[2]]) + self.assertIsNone(site_navigation.items[3].parent) + self.assertEqual(site_navigation.items[3].ancestors, []) + self.assertIsNone(site_navigation.items[3].children) + + def test_nested_ungrouped_nav(self): + nav_cfg = [ + {'Home': 'index.md'}, + {'Contact': 'about/contact.md'}, + {'License Title': 'about/sub/license.md'}, + ] + expected = dedent( + """ + Page(title='Home', url='/') + Page(title='Contact', url='/about/contact/') + Page(title='License Title', url='/about/sub/license/') + """ + ) + cfg = load_config(nav=nav_cfg, site_url='http://example.com/') + fs = [ + File(list(item.values())[0], cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls) + for item in nav_cfg + ] + files = Files(fs) + site_navigation = get_navigation(files, cfg) + self.assertEqual(str(site_navigation).strip(), expected) + self.assertEqual(len(site_navigation.items), 3) + self.assertEqual(len(site_navigation.pages), 3) + + def test_nested_ungrouped_nav_no_titles(self): + nav_cfg = [ + 'index.md', + 'about/contact.md', + 'about/sub/license.md', + ] + expected = dedent( + """ + Page(title=[blank], url='/') + Page(title=[blank], url='/about/contact/') + Page(title=[blank], url='/about/sub/license/') + """ + ) + + cfg = load_config(nav=nav_cfg, site_url='http://example.com/') + fs = [File(item, cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls) for item in nav_cfg] + files = Files(fs) + site_navigation = get_navigation(files, cfg) + self.assertEqual(str(site_navigation).strip(), expected) + self.assertEqual(len(site_navigation.items), 3) + self.assertEqual(len(site_navigation.pages), 3) + self.assertEqual(repr(site_navigation.homepage), "Page(title=[blank], url='/')") + + @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows") + def test_nested_ungrouped_no_titles_windows(self): + nav_cfg = [ + 'index.md', + 'about\\contact.md', + 'about\\sub\\license.md', + ] + expected = dedent( + """ + Page(title=[blank], url='/') + Page(title=[blank], url='/about/contact/') + Page(title=[blank], url='/about/sub/license/') + """ + ) + + cfg = load_config(nav=nav_cfg, site_url='http://example.com/') + fs = [File(item, cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls) for item in nav_cfg] + files = Files(fs) + site_navigation = get_navigation(files, cfg) + self.assertEqual(str(site_navigation).strip(), expected) + self.assertEqual(len(site_navigation.items), 3) + self.assertEqual(len(site_navigation.pages), 3) + + def test_nav_from_files(self): + expected = dedent( + """ + Page(title=[blank], url='/') + Page(title=[blank], url='/about/') + """ + ) + cfg = load_config(site_url='http://example.com/') + fs = [ + File('index.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls), + File('about.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls), + ] + files = Files(fs) + site_navigation = get_navigation(files, cfg) + self.assertEqual(str(site_navigation).strip(), expected) + self.assertEqual(len(site_navigation.items), 2) + self.assertEqual(len(site_navigation.pages), 2) + self.assertEqual(repr(site_navigation.homepage), "Page(title=[blank], url='/')") + + def test_nav_from_nested_files(self): + expected = dedent( + """ + Page(title=[blank], url='/') + Section(title='About') + Page(title=[blank], url='/about/license/') + Page(title=[blank], url='/about/release-notes/') + Section(title='Api guide') + Page(title=[blank], url='/api-guide/debugging/') + Page(title=[blank], url='/api-guide/running/') + Page(title=[blank], url='/api-guide/testing/') + Section(title='Advanced') + Page(title=[blank], url='/api-guide/advanced/part-1/') + """ + ) + cfg = load_config(site_url='http://example.com/') + fs = [ + 'index.md', + 'about/license.md', + 'about/release-notes.md', + 'api-guide/debugging.md', + 'api-guide/running.md', + 'api-guide/testing.md', + 'api-guide/advanced/part-1.md', + ] + files = Files([File(s, cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls) for s in fs]) + site_navigation = get_navigation(files, cfg) + self.assertEqual(str(site_navigation).strip(), expected) + self.assertEqual(len(site_navigation.items), 3) + self.assertEqual(len(site_navigation.pages), 7) + self.assertEqual(repr(site_navigation.homepage), "Page(title=[blank], url='/')") + + def test_nav_page_subclass(self): + class PageSubclass(Page): + pass + + nav_cfg = [ + {'Home': 'index.md'}, + {'About': 'about.md'}, + ] + expected = dedent( + """ + PageSubclass(title=[blank], url='/') + PageSubclass(title=[blank], url='/about/') + """ + ) + cfg = load_config(nav=nav_cfg, site_url='http://example.com/') + fs = [ + File(list(item.values())[0], cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls) + for item in nav_cfg + ] + files = Files(fs) + for file in files: + PageSubclass(None, file, cfg) + site_navigation = get_navigation(files, cfg) + self.assertEqual(str(site_navigation).strip(), expected) + self.assertEqual(len(site_navigation.items), 2) + self.assertEqual(len(site_navigation.pages), 2) + self.assertEqual(repr(site_navigation.homepage), "PageSubclass(title=[blank], url='/')") + + def test_active(self): + nav_cfg = [ + {'Home': 'index.md'}, + { + 'API Guide': [ + {'Running': 'api-guide/running.md'}, + {'Testing': 'api-guide/testing.md'}, + {'Debugging': 'api-guide/debugging.md'}, + { + 'Advanced': [ + {'Part 1': 'api-guide/advanced/part-1.md'}, + ] + }, + ] + }, + { + 'About': [ + {'Release notes': 'about/release-notes.md'}, + {'License': 'about/license.md'}, + ] + }, + ] + cfg = load_config(nav=nav_cfg, site_url='http://example.com/') + fs = [ + 'index.md', + 'api-guide/running.md', + 'api-guide/testing.md', + 'api-guide/debugging.md', + 'api-guide/advanced/part-1.md', + 'about/release-notes.md', + 'about/license.md', + ] + files = Files([File(s, cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls) for s in fs]) + site_navigation = get_navigation(files, cfg) + # Confirm nothing is active + self.assertTrue(all(page.active is False for page in site_navigation.pages)) + self.assertTrue(all(item.active is False for item in site_navigation.items)) + # Activate + site_navigation.items[1].children[3].children[0].active = True + # Confirm ancestors are activated + self.assertTrue(site_navigation.items[1].children[3].children[0].active) + self.assertTrue(site_navigation.items[1].children[3].active) + self.assertTrue(site_navigation.items[1].active) + # Confirm non-ancestors are not activated + self.assertFalse(site_navigation.items[0].active) + self.assertFalse(site_navigation.items[1].children[0].active) + self.assertFalse(site_navigation.items[1].children[1].active) + self.assertFalse(site_navigation.items[1].children[2].active) + self.assertFalse(site_navigation.items[2].active) + self.assertFalse(site_navigation.items[2].children[0].active) + self.assertFalse(site_navigation.items[2].children[1].active) + # Deactivate + site_navigation.items[1].children[3].children[0].active = False + # Confirm ancestors are deactivated + self.assertFalse(site_navigation.items[1].children[3].children[0].active) + self.assertFalse(site_navigation.items[1].children[3].active) + self.assertFalse(site_navigation.items[1].active) + + def test_get_by_type_nested_sections(self): + nav_cfg = [ + { + 'Section 1': [ + { + 'Section 2': [ + {'Page': 'page.md'}, + ] + }, + ] + }, + ] + cfg = load_config(nav=nav_cfg, site_url='http://example.com/') + fs = [File('page.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls)] + files = Files(fs) + site_navigation = get_navigation(files, cfg) + self.assertEqual(len(_get_by_type(site_navigation, Section)), 2) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/structure/page_tests.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/structure/page_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..97a79c4701dd13b435c08cab2c565ca72308e039 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/structure/page_tests.py @@ -0,0 +1,1249 @@ +from __future__ import annotations + +import os +import sys +import textwrap +import unittest +from unittest import mock + +from mkdocs.config.defaults import MkDocsConfig +from mkdocs.structure.files import File, Files +from mkdocs.structure.pages import Page, _RelativePathTreeprocessor +from mkdocs.tests.base import dedent, tempdir + +DOCS_DIR = os.path.join( + os.path.abspath(os.path.dirname(__file__)), '..', 'integration', 'subpages', 'docs' +) + + +def load_config(**cfg) -> MkDocsConfig: + cfg.setdefault('site_name', 'Example') + cfg.setdefault( + 'docs_dir', + os.path.join( + os.path.abspath(os.path.dirname(__file__)), '..', 'integration', 'minimal', 'docs' + ), + ) + conf = MkDocsConfig() + conf.load_dict(cfg) + errors_warnings = conf.validate() + assert errors_warnings == ([], []), errors_warnings + return conf + + +class PageTests(unittest.TestCase): + def test_homepage(self): + cfg = load_config(docs_dir=DOCS_DIR) + fl = File('index.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls) + self.assertIsNone(fl.page) + pg = Page('Foo', fl, cfg) + self.assertEqual(fl.page, pg) + self.assertEqual(pg.url, '') + self.assertEqual(pg.abs_url, None) + self.assertEqual(pg.canonical_url, None) + self.assertEqual(pg.edit_url, None) + self.assertEqual(pg.file, fl) + self.assertEqual(pg.content, None) + self.assertTrue(pg.is_homepage) + self.assertTrue(pg.is_index) + self.assertTrue(pg.is_page) + self.assertFalse(pg.is_section) + self.assertTrue(pg.is_top_level) + self.assertEqual(pg.markdown, None) + self.assertEqual(pg.meta, {}) + self.assertEqual(pg.next_page, None) + self.assertEqual(pg.parent, None) + self.assertEqual(pg.previous_page, None) + self.assertEqual(pg.title, 'Foo') + self.assertEqual(pg.toc, []) + + def test_nested_index_page(self): + cfg = load_config(docs_dir=DOCS_DIR) + fl = File('sub1/index.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls) + pg = Page('Foo', fl, cfg) + pg.parent = 'foo' + self.assertEqual(pg.url, 'sub1/') + self.assertEqual(pg.abs_url, None) + self.assertEqual(pg.canonical_url, None) + self.assertEqual(pg.edit_url, None) + self.assertEqual(pg.file, fl) + self.assertEqual(pg.content, None) + self.assertFalse(pg.is_homepage) + self.assertTrue(pg.is_index) + self.assertTrue(pg.is_page) + self.assertFalse(pg.is_section) + self.assertFalse(pg.is_top_level) + self.assertEqual(pg.markdown, None) + self.assertEqual(pg.meta, {}) + self.assertEqual(pg.next_page, None) + self.assertEqual(pg.parent, 'foo') + self.assertEqual(pg.previous_page, None) + self.assertEqual(pg.title, 'Foo') + self.assertEqual(pg.toc, []) + + def test_nested_index_page_no_parent(self): + cfg = load_config(docs_dir=DOCS_DIR) + fl = File('sub1/index.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls) + pg = Page('Foo', fl, cfg) + pg.parent = None # non-homepage at nav root level; see #1919. + self.assertEqual(pg.url, 'sub1/') + self.assertEqual(pg.abs_url, None) + self.assertEqual(pg.canonical_url, None) + self.assertEqual(pg.edit_url, None) + self.assertEqual(pg.file, fl) + self.assertEqual(pg.content, None) + self.assertFalse(pg.is_homepage) + self.assertTrue(pg.is_index) + self.assertTrue(pg.is_page) + self.assertFalse(pg.is_section) + self.assertTrue(pg.is_top_level) + self.assertEqual(pg.markdown, None) + self.assertEqual(pg.meta, {}) + self.assertEqual(pg.next_page, None) + self.assertEqual(pg.parent, None) + self.assertEqual(pg.previous_page, None) + self.assertEqual(pg.title, 'Foo') + self.assertEqual(pg.toc, []) + + def test_nested_index_page_no_parent_no_directory_urls(self): + cfg = load_config(docs_dir=DOCS_DIR, use_directory_urls=False) + fl = File('sub1/index.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls) + pg = Page('Foo', fl, cfg) + pg.parent = None # non-homepage at nav root level; see #1919. + self.assertEqual(pg.url, 'sub1/index.html') + self.assertEqual(pg.abs_url, None) + self.assertEqual(pg.canonical_url, None) + self.assertEqual(pg.edit_url, None) + self.assertEqual(pg.file, fl) + self.assertEqual(pg.content, None) + self.assertFalse(pg.is_homepage) + self.assertTrue(pg.is_index) + self.assertTrue(pg.is_page) + self.assertFalse(pg.is_section) + self.assertTrue(pg.is_top_level) + self.assertEqual(pg.markdown, None) + self.assertEqual(pg.meta, {}) + self.assertEqual(pg.next_page, None) + self.assertEqual(pg.parent, None) + self.assertEqual(pg.previous_page, None) + self.assertEqual(pg.title, 'Foo') + self.assertEqual(pg.toc, []) + + def test_nested_nonindex_page(self): + cfg = load_config(docs_dir=DOCS_DIR) + fl = File('sub1/non-index.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls) + pg = Page('Foo', fl, cfg) + pg.parent = 'foo' + self.assertEqual(pg.url, 'sub1/non-index/') + self.assertEqual(pg.abs_url, None) + self.assertEqual(pg.canonical_url, None) + self.assertEqual(pg.edit_url, None) + self.assertEqual(pg.file, fl) + self.assertEqual(pg.content, None) + self.assertFalse(pg.is_homepage) + self.assertFalse(pg.is_index) + self.assertTrue(pg.is_page) + self.assertFalse(pg.is_section) + self.assertFalse(pg.is_top_level) + self.assertEqual(pg.markdown, None) + self.assertEqual(pg.meta, {}) + self.assertEqual(pg.next_page, None) + self.assertEqual(pg.parent, 'foo') + self.assertEqual(pg.previous_page, None) + self.assertEqual(pg.title, 'Foo') + self.assertEqual(pg.toc, []) + + def test_page_defaults(self): + cfg = load_config() + fl = File('testing.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls) + pg = Page('Foo', fl, cfg) + self.assertRegex(pg.update_date, r'\d{4}-\d{2}-\d{2}') + self.assertEqual(pg.url, 'testing/') + self.assertEqual(pg.abs_url, None) + self.assertEqual(pg.canonical_url, None) + self.assertEqual(pg.edit_url, None) + self.assertEqual(pg.file, fl) + self.assertEqual(pg.content, None) + self.assertFalse(pg.is_homepage) + self.assertFalse(pg.is_index) + self.assertTrue(pg.is_page) + self.assertFalse(pg.is_section) + self.assertTrue(pg.is_top_level) + self.assertEqual(pg.markdown, None) + self.assertEqual(pg.meta, {}) + self.assertEqual(pg.next_page, None) + self.assertEqual(pg.parent, None) + self.assertEqual(pg.previous_page, None) + self.assertEqual(pg.title, 'Foo') + self.assertEqual(pg.toc, []) + + def test_page_no_directory_url(self): + cfg = load_config(use_directory_urls=False) + fl = File('testing.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls) + pg = Page('Foo', fl, cfg) + self.assertEqual(pg.url, 'testing.html') + self.assertEqual(pg.abs_url, None) + self.assertEqual(pg.canonical_url, None) + self.assertEqual(pg.edit_url, None) + self.assertEqual(pg.file, fl) + self.assertEqual(pg.content, None) + self.assertFalse(pg.is_homepage) + self.assertFalse(pg.is_index) + self.assertTrue(pg.is_page) + self.assertFalse(pg.is_section) + self.assertTrue(pg.is_top_level) + self.assertEqual(pg.markdown, None) + self.assertEqual(pg.meta, {}) + self.assertEqual(pg.next_page, None) + self.assertEqual(pg.parent, None) + self.assertEqual(pg.previous_page, None) + self.assertEqual(pg.title, 'Foo') + self.assertEqual(pg.toc, []) + + def test_page_canonical_url(self): + cfg = load_config(site_url='http://example.com') + fl = File('testing.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls) + pg = Page('Foo', fl, cfg) + self.assertEqual(pg.url, 'testing/') + self.assertEqual(pg.abs_url, '/testing/') + self.assertEqual(pg.canonical_url, 'http://example.com/testing/') + self.assertEqual(pg.edit_url, None) + self.assertEqual(pg.file, fl) + self.assertEqual(pg.content, None) + self.assertFalse(pg.is_homepage) + self.assertFalse(pg.is_index) + self.assertTrue(pg.is_page) + self.assertFalse(pg.is_section) + self.assertTrue(pg.is_top_level) + self.assertEqual(pg.markdown, None) + self.assertEqual(pg.meta, {}) + self.assertEqual(pg.next_page, None) + self.assertEqual(pg.parent, None) + self.assertEqual(pg.previous_page, None) + self.assertEqual(pg.title, 'Foo') + self.assertEqual(pg.toc, []) + + def test_page_canonical_url_nested(self): + cfg = load_config(site_url='http://example.com/foo/') + fl = File('testing.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls) + pg = Page('Foo', fl, cfg) + self.assertEqual(pg.url, 'testing/') + self.assertEqual(pg.abs_url, '/foo/testing/') + self.assertEqual(pg.canonical_url, 'http://example.com/foo/testing/') + self.assertEqual(pg.edit_url, None) + self.assertEqual(pg.file, fl) + self.assertEqual(pg.content, None) + self.assertFalse(pg.is_homepage) + self.assertFalse(pg.is_index) + self.assertTrue(pg.is_page) + self.assertFalse(pg.is_section) + self.assertTrue(pg.is_top_level) + self.assertEqual(pg.markdown, None) + self.assertEqual(pg.meta, {}) + self.assertEqual(pg.next_page, None) + self.assertEqual(pg.parent, None) + self.assertEqual(pg.previous_page, None) + self.assertEqual(pg.title, 'Foo') + self.assertEqual(pg.toc, []) + + def test_page_canonical_url_nested_no_slash(self): + cfg = load_config(site_url='http://example.com/foo') + fl = File('testing.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls) + pg = Page('Foo', fl, cfg) + self.assertEqual(pg.url, 'testing/') + self.assertEqual(pg.abs_url, '/foo/testing/') + self.assertEqual(pg.canonical_url, 'http://example.com/foo/testing/') + self.assertEqual(pg.edit_url, None) + self.assertEqual(pg.file, fl) + self.assertEqual(pg.content, None) + self.assertFalse(pg.is_homepage) + self.assertFalse(pg.is_index) + self.assertTrue(pg.is_page) + self.assertFalse(pg.is_section) + self.assertTrue(pg.is_top_level) + self.assertEqual(pg.markdown, None) + self.assertEqual(pg.meta, {}) + self.assertEqual(pg.next_page, None) + self.assertEqual(pg.parent, None) + self.assertEqual(pg.previous_page, None) + self.assertEqual(pg.title, 'Foo') + self.assertEqual(pg.toc, []) + + def test_predefined_page_title(self): + cfg = load_config() + fl = File('testing.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls) + pg = Page('Page Title', fl, cfg) + pg.read_source(cfg) + self.assertEqual(pg.url, 'testing/') + self.assertEqual(pg.abs_url, None) + self.assertEqual(pg.canonical_url, None) + self.assertEqual(pg.edit_url, None) + self.assertEqual(pg.file, fl) + self.assertEqual(pg.content, None) + self.assertFalse(pg.is_homepage) + self.assertFalse(pg.is_index) + self.assertTrue(pg.is_page) + self.assertFalse(pg.is_section) + self.assertTrue(pg.is_top_level) + self.assertTrue(pg.markdown.startswith('# Welcome to MkDocs\n')) + self.assertEqual(pg.meta, {}) + self.assertEqual(pg.next_page, None) + self.assertEqual(pg.parent, None) + self.assertEqual(pg.previous_page, None) + self.assertEqual(pg.title, 'Page Title') + self.assertEqual(pg.toc, []) + + def test_page_title_from_markdown(self): + cfg = load_config() + fl = File('testing.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls) + pg = Page(None, fl, cfg) + pg.read_source(cfg) + self.assertEqual(pg.url, 'testing/') + self.assertEqual(pg.abs_url, None) + self.assertEqual(pg.canonical_url, None) + self.assertEqual(pg.edit_url, None) + self.assertEqual(pg.file, fl) + self.assertEqual(pg.content, None) + self.assertFalse(pg.is_homepage) + self.assertFalse(pg.is_index) + self.assertTrue(pg.is_page) + self.assertFalse(pg.is_section) + self.assertTrue(pg.is_top_level) + self.assertTrue(pg.markdown.startswith('# Welcome to MkDocs\n')) + self.assertEqual(pg.meta, {}) + self.assertEqual(pg.next_page, None) + self.assertEqual(pg.parent, None) + self.assertEqual(pg.previous_page, None) + self.assertEqual(pg.title, 'Welcome to MkDocs') + pg.render(cfg, fl) + self.assertEqual(pg.title, 'Welcome to MkDocs') + + _SETEXT_CONTENT = dedent( + ''' + Welcome to MkDocs Setext + ======================== + + This tests extracting a setext style title. + ''' + ) + + @tempdir(files={'testing_setext_title.md': _SETEXT_CONTENT}) + def test_page_title_from_setext_markdown(self, docs_dir): + cfg = load_config() + fl = File('testing_setext_title.md', docs_dir, docs_dir, use_directory_urls=True) + pg = Page(None, fl, cfg) + self.assertIsNone(pg.title) + pg.read_source(cfg) + self.assertEqual(pg.title, 'Testing setext title') + pg.render(cfg, fl) + self.assertEqual(pg.title, 'Welcome to MkDocs Setext') + + @tempdir(files={'testing_setext_title.md': _SETEXT_CONTENT}) + def test_page_title_from_markdown_stripped_anchorlinks(self, docs_dir): + cfg = MkDocsConfig() + cfg.site_name = 'example' + cfg.markdown_extensions = {'toc': {'permalink': '&'}} + self.assertEqual(cfg.validate(), ([], [])) + fl = File('testing_setext_title.md', docs_dir, docs_dir, use_directory_urls=True) + pg = Page(None, fl, cfg) + pg.read_source(cfg) + pg.render(cfg, fl) + self.assertEqual(pg.title, 'Welcome to MkDocs Setext') + + _FORMATTING_CONTENT = dedent( + ''' + # \\*Hello --- *beautiful* `world` + + Hi. + ''' + ) + + @tempdir(files={'testing_formatting.md': _FORMATTING_CONTENT}) + def test_page_title_from_markdown_strip_formatting(self, docs_dir): + cfg = load_config() + cfg.markdown_extensions.append('smarty') + fl = File('testing_formatting.md', docs_dir, docs_dir, use_directory_urls=True) + pg = Page(None, fl, cfg) + pg.read_source(cfg) + pg.render(cfg, fl) + self.assertEqual(pg.title, '*Hello — beautiful world') + + _ATTRLIST_CONTENT = dedent( + ''' + # Welcome to MkDocs Attr { #welcome } + + This tests extracting the title, with enabled attr_list markdown_extension. + ''' + ) + + @tempdir(files={'testing_attr_list.md': _ATTRLIST_CONTENT}) + def test_page_title_from_markdown_stripped_attr_list(self, docs_dir): + cfg = load_config() + cfg.markdown_extensions.append('attr_list') + fl = File('testing_attr_list.md', docs_dir, docs_dir, use_directory_urls=True) + pg = Page(None, fl, cfg) + pg.read_source(cfg) + pg.render(cfg, fl) + self.assertEqual(pg.title, 'Welcome to MkDocs Attr') + + @tempdir(files={'testing_attr_list.md': _ATTRLIST_CONTENT}) + def test_page_title_from_markdown_preserved_attr_list(self, docs_dir): + cfg = load_config() + fl = File('testing_attr_list.md', docs_dir, docs_dir, use_directory_urls=True) + pg = Page(None, fl, cfg) + pg.read_source(cfg) + pg.render(cfg, fl) + self.assertEqual(pg.title, 'Welcome to MkDocs Attr { #welcome }') + + def test_page_title_from_meta(self): + cfg = load_config(docs_dir=DOCS_DIR) + fl = File('metadata.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls) + pg = Page(None, fl, cfg) + pg.read_source(cfg) + self.assertEqual(pg.url, 'metadata/') + self.assertEqual(pg.abs_url, None) + self.assertEqual(pg.canonical_url, None) + self.assertEqual(pg.edit_url, None) + self.assertEqual(pg.file, fl) + self.assertEqual(pg.content, None) + self.assertFalse(pg.is_homepage) + self.assertFalse(pg.is_index) + self.assertTrue(pg.is_page) + self.assertFalse(pg.is_section) + self.assertTrue(pg.is_top_level) + self.assertTrue(pg.markdown.startswith('# Welcome to MkDocs\n')) + self.assertEqual(pg.meta, {'title': 'A Page Title'}) + self.assertEqual(pg.next_page, None) + self.assertEqual(pg.parent, None) + self.assertEqual(pg.previous_page, None) + self.assertEqual(pg.title, 'A Page Title') + self.assertEqual(pg.toc, []) + pg.render(cfg, fl) + self.assertEqual(pg.title, 'A Page Title') + + def test_page_title_from_filename(self): + cfg = load_config(docs_dir=DOCS_DIR) + fl = File('page-title.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls) + pg = Page(None, fl, cfg) + pg.read_source(cfg) + self.assertEqual(pg.url, 'page-title/') + self.assertEqual(pg.abs_url, None) + self.assertEqual(pg.canonical_url, None) + self.assertEqual(pg.edit_url, None) + self.assertEqual(pg.file, fl) + self.assertEqual(pg.content, None) + self.assertFalse(pg.is_homepage) + self.assertFalse(pg.is_index) + self.assertTrue(pg.is_page) + self.assertFalse(pg.is_section) + self.assertTrue(pg.is_top_level) + self.assertTrue(pg.markdown.startswith('Page content.\n')) + self.assertEqual(pg.meta, {}) + self.assertEqual(pg.next_page, None) + self.assertEqual(pg.parent, None) + self.assertEqual(pg.previous_page, None) + self.assertEqual(pg.title, 'Page title') + pg.render(cfg, fl) + self.assertEqual(pg.title, 'Page title') + + def test_page_title_from_capitalized_filename(self): + cfg = load_config(docs_dir=DOCS_DIR) + fl = File('pageTitle.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls) + pg = Page(None, fl, cfg) + pg.read_source(cfg) + self.assertEqual(pg.url, 'pageTitle/') + self.assertEqual(pg.abs_url, None) + self.assertEqual(pg.canonical_url, None) + self.assertEqual(pg.edit_url, None) + self.assertEqual(pg.file, fl) + self.assertEqual(pg.content, None) + self.assertFalse(pg.is_homepage) + self.assertFalse(pg.is_index) + self.assertTrue(pg.is_page) + self.assertFalse(pg.is_section) + self.assertTrue(pg.is_top_level) + self.assertTrue(pg.markdown.startswith('Page content.\n')) + self.assertEqual(pg.meta, {}) + self.assertEqual(pg.next_page, None) + self.assertEqual(pg.parent, None) + self.assertEqual(pg.previous_page, None) + self.assertEqual(pg.title, 'pageTitle') + + def test_page_title_from_homepage_filename(self): + cfg = load_config(docs_dir=DOCS_DIR) + fl = File('index.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls) + pg = Page(None, fl, cfg) + pg.read_source(cfg) + self.assertEqual(pg.url, '') + self.assertEqual(pg.abs_url, None) + self.assertEqual(pg.canonical_url, None) + self.assertEqual(pg.edit_url, None) + self.assertEqual(pg.file, fl) + self.assertEqual(pg.content, None) + self.assertTrue(pg.is_homepage) + self.assertTrue(pg.is_index) + self.assertTrue(pg.is_page) + self.assertFalse(pg.is_section) + self.assertTrue(pg.is_top_level) + self.assertTrue(pg.markdown.startswith('## Test')) + self.assertEqual(pg.meta, {}) + self.assertEqual(pg.next_page, None) + self.assertEqual(pg.parent, None) + self.assertEqual(pg.previous_page, None) + self.assertEqual(pg.title, 'Home') + self.assertEqual(pg.toc, []) + + def test_page_eq(self): + cfg = load_config() + fl = File('testing.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls) + pg = Page('Foo', fl, cfg) + self.assertTrue(pg == Page('Foo', fl, cfg)) + + def test_page_ne(self): + cfg = load_config() + f1 = File('testing.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls) + f2 = File('index.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls) + pg = Page('Foo', f1, cfg) + # Different Title + self.assertTrue(pg != Page('Bar', f1, cfg)) + # Different File + self.assertTrue(pg != Page('Foo', f2, cfg)) + + @tempdir() + def test_BOM(self, docs_dir): + md_src = '# An UTF-8 encoded file with a BOM' + cfg = load_config(docs_dir=docs_dir) + fl = File('index.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls) + pg = Page(None, fl, cfg) + # Create an UTF-8 Encoded file with BOM (as Microsoft editors do). See #1186 + with open(fl.abs_src_path, 'w', encoding='utf-8-sig') as f: + f.write(md_src) + # Now read the file. + pg.read_source(cfg) + # Ensure the BOM (`\ufeff`) is removed + self.assertNotIn('\ufeff', pg.markdown) + self.assertEqual(pg.markdown, md_src) + self.assertEqual(pg.meta, {}) + + def test_page_edit_url( + self, paths={'testing.md': 'testing/', 'sub1/non-index.md': 'sub1/non-index/'} + ): + for case in [ + dict( + config={'repo_url': 'http://github.com/mkdocs/mkdocs'}, + edit_url='http://github.com/mkdocs/mkdocs/edit/master/docs/testing.md', + edit_url2='http://github.com/mkdocs/mkdocs/edit/master/docs/sub1/non-index.md', + ), + dict( + config={'repo_url': 'https://github.com/mkdocs/mkdocs/'}, + edit_url='https://github.com/mkdocs/mkdocs/edit/master/docs/testing.md', + edit_url2='https://github.com/mkdocs/mkdocs/edit/master/docs/sub1/non-index.md', + ), + dict( + config={'repo_url': 'http://example.com'}, + edit_url=None, + edit_url2=None, + ), + dict( + config={'repo_url': 'http://example.com', 'edit_uri': 'edit/master'}, + edit_url='http://example.com/edit/master/testing.md', + edit_url2='http://example.com/edit/master/sub1/non-index.md', + ), + dict( + config={'repo_url': 'http://example.com', 'edit_uri': '/edit/master'}, + edit_url='http://example.com/edit/master/testing.md', + edit_url2='http://example.com/edit/master/sub1/non-index.md', + ), + dict( + config={'repo_url': 'http://example.com/foo/', 'edit_uri': '/edit/master/'}, + edit_url='http://example.com/edit/master/testing.md', + edit_url2='http://example.com/edit/master/sub1/non-index.md', + ), + dict( + config={'repo_url': 'http://example.com/foo', 'edit_uri': '/edit/master/'}, + edit_url='http://example.com/edit/master/testing.md', + edit_url2='http://example.com/edit/master/sub1/non-index.md', + ), + dict( + config={'repo_url': 'http://example.com/foo/', 'edit_uri': '/edit/master'}, + edit_url='http://example.com/edit/master/testing.md', + edit_url2='http://example.com/edit/master/sub1/non-index.md', + ), + dict( + config={'repo_url': 'http://example.com/foo/', 'edit_uri': 'edit/master/'}, + edit_url='http://example.com/foo/edit/master/testing.md', + edit_url2='http://example.com/foo/edit/master/sub1/non-index.md', + ), + dict( + config={'repo_url': 'http://example.com/foo', 'edit_uri': 'edit/master/'}, + edit_url='http://example.com/foo/edit/master/testing.md', + edit_url2='http://example.com/foo/edit/master/sub1/non-index.md', + ), + dict( + config={'repo_url': 'http://example.com', 'edit_uri': '?query=edit/master'}, + edit_url='http://example.com?query=edit/master/testing.md', + edit_url2='http://example.com?query=edit/master/sub1/non-index.md', + ), + dict( + config={'repo_url': 'http://example.com/', 'edit_uri': '?query=edit/master/'}, + edit_url='http://example.com/?query=edit/master/testing.md', + edit_url2='http://example.com/?query=edit/master/sub1/non-index.md', + ), + dict( + config={'repo_url': 'http://example.com', 'edit_uri': '#edit/master'}, + edit_url='http://example.com#edit/master/testing.md', + edit_url2='http://example.com#edit/master/sub1/non-index.md', + ), + dict( + config={'repo_url': 'http://example.com/', 'edit_uri': '#edit/master/'}, + edit_url='http://example.com/#edit/master/testing.md', + edit_url2='http://example.com/#edit/master/sub1/non-index.md', + ), + dict( + config={'edit_uri': 'http://example.com/edit/master'}, + edit_url='http://example.com/edit/master/testing.md', + edit_url2='http://example.com/edit/master/sub1/non-index.md', + ), + dict( + config={'edit_uri_template': 'https://github.com/project/repo/wiki/{path_noext}'}, + edit_url='https://github.com/project/repo/wiki/testing', + edit_url2='https://github.com/project/repo/wiki/sub1/non-index', + ), + dict( + config={ + 'repo_url': 'https://github.com/project/repo/wiki', + 'edit_uri_template': '{path_noext}/_edit', + }, + edit_url='https://github.com/project/repo/wiki/testing/_edit', + edit_url2='https://github.com/project/repo/wiki/sub1/non-index/_edit', + ), + dict( + config={ + 'repo_url': 'https://gitlab.com/project/repo', + 'edit_uri_template': '-/sse/master/docs%2F{path!q}', + }, + edit_url='https://gitlab.com/project/repo/-/sse/master/docs%2Ftesting.md', + edit_url2='https://gitlab.com/project/repo/-/sse/master/docs%2Fsub1%2Fnon-index.md', + ), + dict( + config={ + 'repo_url': 'https://bitbucket.org/project/repo/', + 'edit_uri_template': 'src/master/docs/{path}?mode=edit', + }, + edit_url='https://bitbucket.org/project/repo/src/master/docs/testing.md?mode=edit', + edit_url2='https://bitbucket.org/project/repo/src/master/docs/sub1/non-index.md?mode=edit', + ), + dict( + config={ + 'repo_url': 'http://example.com', + 'edit_uri': '', + 'edit_uri_template': '', + }, # Set to blank value + edit_url=None, + edit_url2=None, + ), + dict(config={}, edit_url=None, edit_url2=None), # Nothing defined + ]: + for i, path in enumerate(paths, 1): + edit_url_key = f'edit_url{i}' if i > 1 else 'edit_url' + with self.subTest(case['config'], path=path): + cfg = load_config(**case['config']) + fl = File(path, cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls) + pg = Page('Foo', fl, cfg) + self.assertEqual(pg.url, paths[path]) + self.assertEqual(pg.edit_url, case[edit_url_key]) + + @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows") + def test_page_edit_url_windows(self): + self.test_page_edit_url( + paths={'testing.md': 'testing/', 'sub1\\non-index.md': 'sub1/non-index/'} + ) + + def test_page_edit_url_warning(self): + for case in [ + dict( + config={'edit_uri': 'edit/master'}, + edit_url='edit/master/testing.md', + warning="WARNING:mkdocs.structure.pages:edit_uri: " + "'edit/master/testing.md' is not a valid URL, it should include the http:// (scheme)", + ), + ]: + with self.subTest(case['config']): + with self.assertLogs('mkdocs') as cm: + cfg = load_config(**case['config']) + fl = File('testing.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls) + pg = Page('Foo', fl, cfg) + self.assertEqual(pg.url, 'testing/') + self.assertEqual(pg.edit_url, case['edit_url']) + self.assertEqual(cm.output, [case['warning']]) + + def test_page_render(self): + cfg = load_config() + fl = File('testing.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls) + pg = Page('Foo', fl, cfg) + pg.read_source(cfg) + self.assertEqual(pg.content, None) + self.assertEqual(pg.toc, []) + pg.render(cfg, [fl]) + self.assertTrue( + pg.content.startswith('

Welcome to MkDocs

\n') + ) + self.assertEqual( + str(pg.toc).strip(), + dedent( + """ + Welcome to MkDocs - #welcome-to-mkdocs + Commands - #commands + Project layout - #project-layout + """ + ), + ) + + def test_missing_page(self): + cfg = load_config() + fl = File('missing.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls) + pg = Page('Foo', fl, cfg) + with self.assertLogs('mkdocs') as cm: + with self.assertRaises(OSError): + pg.read_source(cfg) + self.assertEqual( + '\n'.join(cm.output), 'ERROR:mkdocs.structure.pages:File not found: missing.md' + ) + + +class SourceDateEpochTests(unittest.TestCase): + def setUp(self): + self.default = os.environ.get('SOURCE_DATE_EPOCH', None) + os.environ['SOURCE_DATE_EPOCH'] = '0' + + def test_source_date_epoch(self): + cfg = load_config() + fl = File('testing.md', cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls) + pg = Page('Foo', fl, cfg) + self.assertEqual(pg.update_date, '1970-01-01') + + def tearDown(self): + if self.default is not None: + os.environ['SOURCE_DATE_EPOCH'] = self.default + else: + del os.environ['SOURCE_DATE_EPOCH'] + + +class RelativePathExtensionTests(unittest.TestCase): + def get_rendered_result( + self, *, content: str, files: list[str], logs: str = '', **kwargs + ) -> str: + cfg = load_config(docs_dir=DOCS_DIR, **kwargs) + fs = [File(f, cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls) for f in files] + pg = Page('Foo', fs[0], cfg) + + with mock.patch('mkdocs.structure.pages.open', mock.mock_open(read_data=content)): + pg.read_source(cfg) + if logs: + with self.assertLogs('mkdocs.structure.pages') as cm: + pg.render(cfg, Files(fs)) + msgs = [f'{r.levelname}:{r.message}' for r in cm.records] + self.assertEqual('\n'.join(msgs), textwrap.dedent(logs).strip('\n')) + elif sys.version_info >= (3, 10): + with self.assertNoLogs('mkdocs.structure.pages'): + pg.render(cfg, Files(fs)) + else: + pg.render(cfg, Files(fs)) + + assert pg.content is not None + content = pg.content + if content.startswith('

') and content.endswith('

'): + content = content[3:-4] + return content + + def test_relative_html_link(self): + self.assertEqual( + self.get_rendered_result( + content='[link](non-index.md)', files=['index.md', 'non-index.md'] + ), + 'link', + ) + self.assertEqual( + self.get_rendered_result( + use_directory_urls=False, + content='[link](non-index.md)', + files=['index.md', 'non-index.md'], + ), + 'link', + ) + + def test_relative_html_link_index(self): + self.assertEqual( + self.get_rendered_result( + content='[link](index.md)', files=['non-index.md', 'index.md'] + ), + 'link', + ) + self.assertEqual( + self.get_rendered_result( + use_directory_urls=False, + content='[link](index.md)', + files=['non-index.md', 'index.md'], + ), + 'link', + ) + + def test_relative_html_link_sub_index(self): + self.assertEqual( + self.get_rendered_result( + content='[link](sub2/index.md)', files=['index.md', 'sub2/index.md'] + ), + 'link', + ) + self.assertEqual( + self.get_rendered_result( + use_directory_urls=False, + content='[link](sub2/index.md)', + files=['index.md', 'sub2/index.md'], + ), + 'link', + ) + + def test_relative_html_link_sub_page(self): + self.assertEqual( + self.get_rendered_result( + content='[link](sub2/non-index.md)', files=['index.md', 'sub2/non-index.md'] + ), + 'link', + ) + self.assertEqual( + self.get_rendered_result( + use_directory_urls=False, + content='[link](sub2/non-index.md)', + files=['index.md', 'sub2/non-index.md'], + ), + 'link', + ) + + def test_relative_doc_link_without_extension(self): + self.assertEqual( + self.get_rendered_result( + use_directory_urls=False, + content='[link](bar/Dockerfile)', + files=['foo/bar.md', 'foo/bar/Dockerfile'], + ), + 'link', + ) + self.assertEqual( + self.get_rendered_result( + content='[link](bar/Dockerfile)', + files=['foo/bar.md', 'foo/bar/Dockerfile'], + ), + 'link', + ) + + def test_relative_html_link_with_encoded_space(self): + self.assertEqual( + self.get_rendered_result( + content='[link](file%20name.md)', files=['index.md', 'file name.md'] + ), + 'link', + ) + + def test_relative_html_link_with_unencoded_space(self): + self.assertEqual( + self.get_rendered_result( + use_directory_urls=False, + content='[link](file name.md)', + files=['index.md', 'file name.md'], + ), + 'link', + ) + + def test_relative_html_link_parent_index(self): + self.assertEqual( + self.get_rendered_result( + content='[link](../index.md)', files=['sub2/non-index.md', 'index.md'] + ), + 'link', + ) + self.assertEqual( + self.get_rendered_result( + use_directory_urls=False, + content='[link](../index.md)', + files=['sub2/non-index.md', 'index.md'], + ), + 'link', + ) + + def test_relative_html_link_hash(self): + self.assertEqual( + self.get_rendered_result( + content='[link](non-index.md#hash)', files=['index.md', 'non-index.md'] + ), + 'link', + ) + + def test_relative_html_link_sub_index_hash(self): + self.assertEqual( + self.get_rendered_result( + content='[link](sub2/index.md#hash)', files=['index.md', 'sub2/index.md'] + ), + 'link', + ) + self.assertEqual( + self.get_rendered_result( + use_directory_urls=False, + content='[link](sub2/index.md#hash)', + files=['index.md', 'sub2/index.md'], + ), + 'link', + ) + + def test_relative_html_link_sub_page_hash(self): + self.assertEqual( + self.get_rendered_result( + content='[link](sub2/non-index.md#hash)', files=['index.md', 'sub2/non-index.md'] + ), + 'link', + ) + + def test_relative_html_link_hash_only(self): + for use_directory_urls in True, False: + self.assertEqual( + self.get_rendered_result( + use_directory_urls=use_directory_urls, + content='[link](#hash)', + files=['index.md'], + ), + 'link', + ) + + def test_relative_image_link_from_homepage(self): + for use_directory_urls in True, False: + self.assertEqual( + self.get_rendered_result( + use_directory_urls=use_directory_urls, + content='![image](image.png)', + files=['index.md', 'image.png'], + ), + 'image', # no opening ./ + ) + + def test_relative_image_link_from_subpage(self): + self.assertEqual( + self.get_rendered_result( + content='![image](../image.png)', files=['sub2/non-index.md', 'image.png'] + ), + 'image', + ) + + def test_relative_image_link_from_sibling(self): + self.assertEqual( + self.get_rendered_result( + content='![image](image.png)', files=['non-index.md', 'image.png'] + ), + 'image', + ) + self.assertEqual( + self.get_rendered_result( + use_directory_urls=False, + content='![image](image.png)', + files=['non-index.md', 'image.png'], + ), + 'image', + ) + + def test_no_links(self): + self.assertEqual( + self.get_rendered_result(content='*__not__ a link*.', files=['index.md']), + 'not a link.', + ) + + def test_bad_relative_doc_link(self): + self.assertEqual( + self.get_rendered_result( + content='[link](non-existent.md)', + files=['index.md'], + logs="WARNING:Doc file 'index.md' contains a relative link 'non-existent.md', but the target is not found among documentation files.", + ), + 'link', + ) + self.assertEqual( + self.get_rendered_result( + validation=dict(links=dict(not_found='info')), + content='[link](../non-existent.md)', + files=['sub/index.md'], + logs="INFO:Doc file 'sub/index.md' contains a relative link '../non-existent.md', but the target 'non-existent.md' is not found among documentation files.", + ), + 'link', + ) + + def test_relative_slash_link_with_suggestion(self): + self.assertEqual( + self.get_rendered_result( + content='[link](../about/)', + files=['foo/index.md', 'about.md'], + logs="INFO:Doc file 'foo/index.md' contains an unrecognized relative link '../about/', it was left as is. Did you mean '../about.md'?", + ), + 'link', + ) + self.assertEqual( + self.get_rendered_result( + validation=dict(links=dict(unrecognized_links='warn')), + content='[link](../#example)', + files=['foo/bar.md', 'index.md'], + logs="WARNING:Doc file 'foo/bar.md' contains an unrecognized relative link '../#example', it was left as is. Did you mean '../index.md#example'?", + ), + 'link', + ) + + def test_self_anchor_link_with_suggestion(self): + self.assertEqual( + self.get_rendered_result( + content='[link](./#test)', + files=['index.md'], + logs="INFO:Doc file 'index.md' contains an unrecognized relative link './#test', it was left as is. Did you mean '#test'?", + ), + 'link', + ) + + def test_external_link(self): + self.assertEqual( + self.get_rendered_result( + content='[external](http://example.com/index.md)', files=['index.md'] + ), + 'external', + ) + + def test_absolute_link_with_suggestion(self): + self.assertEqual( + self.get_rendered_result( + content='[absolute link](/path/to/file.md)', + files=['index.md', 'path/to/file.md'], + logs="INFO:Doc file 'index.md' contains an absolute link '/path/to/file.md', it was left as is. Did you mean 'path/to/file.md'?", + ), + 'absolute link', + ) + self.assertEqual( + self.get_rendered_result( + use_directory_urls=False, + content='[absolute link](/path/to/file/)', + files=['path/index.md', 'path/to/file.md'], + logs="INFO:Doc file 'path/index.md' contains an absolute link '/path/to/file/', it was left as is.", + ), + 'absolute link', + ) + self.assertEqual( + self.get_rendered_result( + content='[absolute link](/path/to/file)', + files=['path/index.md', 'path/to/file.md'], + logs="INFO:Doc file 'path/index.md' contains an absolute link '/path/to/file', it was left as is. Did you mean 'to/file.md'?", + ), + 'absolute link', + ) + + def test_absolute_link(self): + self.assertEqual( + self.get_rendered_result( + validation=dict(links=dict(absolute_links='warn')), + content='[absolute link](/path/to/file.md)', + files=['index.md'], + logs="WARNING:Doc file 'index.md' contains an absolute link '/path/to/file.md', it was left as is.", + ), + 'absolute link', + ) + self.assertEqual( + self.get_rendered_result( + validation=dict(links=dict(absolute_links='ignore')), + content='[absolute link](/path/to/file.md)', + files=['index.md'], + ), + 'absolute link', + ) + + def test_image_link_with_suggestion(self): + self.assertEqual( + self.get_rendered_result( + content='![image](../image.png)', + files=['foo/bar.md', 'foo/image.png'], + logs="WARNING:Doc file 'foo/bar.md' contains a relative link '../image.png', but the target 'image.png' is not found among documentation files. Did you mean 'image.png'?", + ), + 'image', + ) + self.assertEqual( + self.get_rendered_result( + content='![image](/image.png)', + files=['foo/bar.md', 'image.png'], + logs="INFO:Doc file 'foo/bar.md' contains an absolute link '/image.png', it was left as is. Did you mean '../image.png'?", + ), + 'image', + ) + + def test_absolute_win_local_path(self): + for use_directory_urls in True, False: + self.assertEqual( + self.get_rendered_result( + use_directory_urls=use_directory_urls, + content='[absolute local path](\\image.png)', + files=['index.md'], + logs="INFO:Doc file 'index.md' contains an absolute link '\\image.png', it was left as is.", + ), + 'absolute local path', + ) + + def test_email_link(self): + self.assertEqual( + self.get_rendered_result(content='', files=['index.md']), + # Markdown's default behavior is to obscure email addresses by entity-encoding them. + # The following is equivalent to: 'mail@example.com' + 'mail@' + 'example.com', + ) + + def test_invalid_email_link(self): + self.assertEqual( + self.get_rendered_result( + content='[contact](mail@example.com)', + files=['index.md'], + logs="WARNING:Doc file 'index.md' contains a relative link 'mail@example.com', but the target is not found among documentation files. Did you mean 'mailto:mail@example.com'?", + ), + 'contact', + ) + + def test_possible_target_uris(self): + def test(paths, expected='', exp_true=None, exp_false=None): + """Test that `possible_target_uris` yields expected values, for use_directory_urls = true and false""" + for use_directory_urls, expected_paths in ( + (True, exp_true or expected), + (False, exp_false or expected), + ): + with self.subTest(paths, use_directory_urls=use_directory_urls): + src_path, dest_path = paths + f = File(src_path, '', '', use_directory_urls) + actual = _RelativePathTreeprocessor._possible_target_uris( + f, dest_path, use_directory_urls + ) + self.assertEqual(list(actual), expected_paths.split(', ')) + + test(('index.md', 'index.md'), expected='index.md') + test(('index.md', 'foo/bar.md'), expected='foo/bar.md') + test( + ('index.md', 'foo/bar'), + expected='foo/bar, foo/bar/index.md, foo/bar/README.md, foo/bar.md', + ) + + test(('index.md', 'foo/bar.html'), expected='foo/bar.html, foo/bar.md') + test( + ('foo.md', 'foo/bar.html'), + exp_true='foo/bar.html, foo/bar.md, foo/foo/bar.html, foo/foo/bar.md', + exp_false='foo/bar.html, foo/bar.md', + ) + + test(('foo.md', 'index.md'), exp_true='index.md, foo/index.md', exp_false='index.md') + test(('foo.md', 'foo.md'), exp_true='foo.md, foo/foo.md', exp_false='foo.md') + test(('foo.md', 'bar.md'), exp_true='bar.md, foo/bar.md', exp_false='bar.md') + test( + ('foo.md', 'foo/bar.md'), exp_true='foo/bar.md, foo/foo/bar.md', exp_false='foo/bar.md' + ) + test( + ('foo.md', 'foo'), + exp_true='foo, foo/index.md, foo/README.md, foo.md, foo/foo, foo/foo/index.md, foo/foo/README.md, foo/foo.md', + exp_false='foo, foo/index.md, foo/README.md, foo.md', + ) + test( + ('foo.md', 'foo/bar'), + exp_true='foo/bar, foo/bar/index.md, foo/bar/README.md, foo/bar.md, foo/foo/bar, foo/foo/bar/index.md, foo/foo/bar/README.md, foo/foo/bar.md', + exp_false='foo/bar, foo/bar/index.md, foo/bar/README.md, foo/bar.md', + ) + test( + ('foo.md', 'foo/bar/'), + exp_true='foo/bar, foo/bar/index.md, foo/bar/README.md, foo/bar.md, foo/foo/bar, foo/foo/bar/index.md, foo/foo/bar/README.md, foo/foo/bar.md', + exp_false='foo/bar, foo/bar/index.md, foo/bar/README.md', + ) + + test( + ('foo.md', 'foo.html'), + exp_true='foo.html, foo.md, foo/foo.html, foo/foo.md', + exp_false='foo.html, foo.md', + ) + test( + ('foo.md', '../foo/'), + exp_true='../foo, foo, foo/index.md, foo/README.md, foo.md', + exp_false='../foo', + ) + test( + ('foo.md', 'foo/'), + exp_true='foo, foo/index.md, foo/README.md, foo.md, foo/foo, foo/foo/index.md, foo/foo/README.md, foo/foo.md', + exp_false='foo, foo/index.md, foo/README.md', + ) + test(('foo/index.md', 'index.md'), expected='foo/index.md') + test(('foo/index.md', 'foo/bar.html'), expected='foo/foo/bar.html, foo/foo/bar.md') + test(('foo/index.md', '../foo.html'), expected='foo.html, foo.md') + test(('foo/index.md', '../'), expected='., index.md, README.md') + test( + ('foo/bar.md', 'index.md'), + exp_true='foo/index.md, foo/bar/index.md', + exp_false='foo/index.md', + ) + test( + ('foo/bar.md', 'foo.md'), + exp_true='foo/foo.md, foo/bar/foo.md', + exp_false='foo/foo.md', + ) + test( + ('foo/bar.md', 'bar.md'), + exp_true='foo/bar.md, foo/bar/bar.md', + exp_false='foo/bar.md', + ) + test( + ('foo/bar.md', 'foo/bar.md'), + exp_true='foo/foo/bar.md, foo/bar/foo/bar.md', + exp_false='foo/foo/bar.md', + ) + test( + ('foo/bar.md', 'foo'), + exp_true='foo/foo, foo/foo/index.md, foo/foo/README.md, foo/foo.md, foo/bar/foo, foo/bar/foo/index.md, foo/bar/foo/README.md, foo/bar/foo.md', + exp_false='foo/foo, foo/foo/index.md, foo/foo/README.md, foo/foo.md', + ) + test( + ('foo/bar.md', 'foo/bar'), + exp_true='foo/foo/bar, foo/foo/bar/index.md, foo/foo/bar/README.md, foo/foo/bar.md, foo/bar/foo/bar, foo/bar/foo/bar/index.md, foo/bar/foo/bar/README.md, foo/bar/foo/bar.md', + exp_false='foo/foo/bar, foo/foo/bar/index.md, foo/foo/bar/README.md, foo/foo/bar.md', + ) + test( + ('foo/bar.md', 'foo.html'), + exp_true='foo/foo.html, foo/foo.md, foo/bar/foo.html, foo/bar/foo.md', + exp_false='foo/foo.html, foo/foo.md', + ) + test( + ('foo/bar.md', 'foo/bar.html'), + exp_true='foo/foo/bar.html, foo/foo/bar.md, foo/bar/foo/bar.html, foo/bar/foo/bar.md', + exp_false='foo/foo/bar.html, foo/foo/bar.md', + ) + test( + ('foo/bar.md', '../foo/bar.html'), + exp_true='foo/bar.html, foo/bar.md, foo/foo/bar.html, foo/foo/bar.md', + exp_false='foo/bar.html, foo/bar.md', + ) + test( + ('foo/bar.md', '../foo'), + exp_true='foo, foo/index.md, foo/README.md, foo.md, foo/foo, foo/foo/index.md, foo/foo/README.md, foo/foo.md', + exp_false='foo, foo/index.md, foo/README.md, foo.md', + ) + test( + ('foo/bar.md', '../'), + exp_true='., index.md, README.md, foo, foo/index.md, foo/README.md', + exp_false='., index.md, README.md', + ) + + for src in 'foo/bar.md', 'foo.md', 'foo/index.md': + test((src, '/foo'), expected='foo, foo/index.md, foo/README.md, foo.md') + test((src, '/foo/bar.md'), expected='foo/bar.md') + test((src, '/foo/bar.html'), expected='foo/bar.html, foo/bar.md') + + for dest in '', '.', './': + test(('index.md', dest), expected='., index.md') + test(('foo/bar.md', dest), expected='foo, foo/bar.md') + + test( + ('foo/bar.md', '../test.png'), + exp_true='test.png, test.png.md, foo/test.png, foo/test.png.md', + exp_false='test.png, test.png.md', + ) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/structure/toc_tests.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/structure/toc_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..2f83e1c6e0d7ae45a507b11a1fac64ed048eec70 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/structure/toc_tests.py @@ -0,0 +1,198 @@ +#!/usr/bin/env python + +import unittest + +from mkdocs.structure.toc import get_toc +from mkdocs.tests.base import dedent, get_markdown_toc + + +class TableOfContentsTests(unittest.TestCase): + def test_indented_toc(self): + md = dedent( + """ + # Heading 1 + ## Heading 2 + ### Heading 3 + """ + ) + expected = dedent( + """ + Heading 1 - #heading-1 + Heading 2 - #heading-2 + Heading 3 - #heading-3 + """ + ) + toc = get_toc(get_markdown_toc(md)) + self.assertEqual(str(toc).strip(), expected) + self.assertEqual(len(toc), 1) + + def test_indented_toc_html(self): + md = dedent( + """ + # Heading 1 + ## Heading 2 + ## Heading 3 + """ + ) + expected = dedent( + """ + Heading 1 - #heading-1 + Heading 2 - #heading-2 + Heading 3 - #heading-3 + """ + ) + toc = get_toc(get_markdown_toc(md)) + self.assertEqual(str(toc).strip(), expected) + self.assertEqual(len(toc), 1) + + def test_flat_toc(self): + md = dedent( + """ + # Heading 1 + # Heading 2 + # Heading 3 + """ + ) + expected = dedent( + """ + Heading 1 - #heading-1 + Heading 2 - #heading-2 + Heading 3 - #heading-3 + """ + ) + toc = get_toc(get_markdown_toc(md)) + self.assertEqual(str(toc).strip(), expected) + self.assertEqual(len(toc), 3) + + def test_flat_h2_toc(self): + md = dedent( + """ + ## Heading 1 + ## Heading 2 + ## Heading 3 + """ + ) + expected = dedent( + """ + Heading 1 - #heading-1 + Heading 2 - #heading-2 + Heading 3 - #heading-3 + """ + ) + toc = get_toc(get_markdown_toc(md)) + self.assertEqual(str(toc).strip(), expected) + self.assertEqual(len(toc), 3) + + def test_mixed_toc(self): + md = dedent( + """ + # Heading 1 + ## Heading 2 + # Heading 3 + ### Heading 4 + ### Heading 5 + """ + ) + expected = dedent( + """ + Heading 1 - #heading-1 + Heading 2 - #heading-2 + Heading 3 - #heading-3 + Heading 4 - #heading-4 + Heading 5 - #heading-5 + """ + ) + toc = get_toc(get_markdown_toc(md)) + self.assertEqual(str(toc).strip(), expected) + self.assertEqual(len(toc), 2) + + def test_mixed_html(self): + md = dedent( + """ + # Heading 1 + ## Heading 2 + # Heading 3 + ### Heading 4 + ### Heading 5 + """ + ) + expected = dedent( + """ + Heading 1 - #heading-1 + Heading 2 - #heading-2 + Heading 3 - #heading-3 + Heading 4 - #heading-4 + Heading 5 - #heading-5 + """ + ) + toc = get_toc(get_markdown_toc(md)) + self.assertEqual(str(toc).strip(), expected) + self.assertEqual(len(toc), 2) + + def test_nested_anchor(self): + md = dedent( + """ + # Heading 1 + ## Heading 2 + # Heading 3 + ### Heading 4 + ### Heading 5 + """ + ) + expected = dedent( + """ + Heading 1 - #heading-1 + Heading 2 - #heading-2 + Heading 3 - #heading-3 + Heading 4 - #heading-4 + Heading 5 - #heading-5 + """ + ) + toc = get_toc(get_markdown_toc(md)) + self.assertEqual(str(toc).strip(), expected) + self.assertEqual(len(toc), 2) + + def test_entityref(self): + md = dedent( + """ + # Heading & 1 + ## Heading > 2 + ### Heading < 3 + """ + ) + expected = dedent( + """ + Heading & 1 - #heading-1 + Heading > 2 - #heading-2 + Heading < 3 - #heading-3 + """ + ) + toc = get_toc(get_markdown_toc(md)) + self.assertEqual(str(toc).strip(), expected) + self.assertEqual(len(toc), 1) + + def test_charref(self): + md = '# @Header' + expected = '@Header - #header' + toc = get_toc(get_markdown_toc(md)) + self.assertEqual(str(toc).strip(), expected) + self.assertEqual(len(toc), 1) + + def test_level(self): + md = dedent( + """ + # Heading 1 + ## Heading 1.1 + ### Heading 1.1.1 + ### Heading 1.1.2 + ## Heading 1.2 + """ + ) + toc = get_toc(get_markdown_toc(md)) + + def get_level_sequence(items): + for item in items: + yield item.level + yield from get_level_sequence(item.children) + + self.assertEqual(tuple(get_level_sequence(toc)), (1, 2, 3, 3, 2)) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/theme_tests.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/theme_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..4d123c68e5bef13040780ce58e44efc6e5732d5a --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/theme_tests.py @@ -0,0 +1,103 @@ +import os +import unittest +from unittest import mock + +import mkdocs +from mkdocs.localization import parse_locale +from mkdocs.tests.base import tempdir +from mkdocs.theme import Theme + +abs_path = os.path.abspath(os.path.dirname(__file__)) +mkdocs_dir = os.path.abspath(os.path.dirname(mkdocs.__file__)) +mkdocs_templates_dir = os.path.join(mkdocs_dir, 'templates') +theme_dir = os.path.abspath(os.path.join(mkdocs_dir, 'themes')) + + +class ThemeTests(unittest.TestCase): + def test_simple_theme(self): + theme = Theme(name='mkdocs') + self.assertEqual( + theme.dirs, + [os.path.join(theme_dir, 'mkdocs'), mkdocs_templates_dir], + ) + self.assertEqual(theme.static_templates, {'404.html', 'sitemap.xml'}) + self.assertEqual( + dict(theme), + { + 'name': 'mkdocs', + 'locale': parse_locale('en'), + 'include_search_page': False, + 'search_index_only': False, + 'analytics': {'gtag': None}, + 'highlightjs': True, + 'hljs_style': 'github', + 'hljs_languages': [], + 'navigation_depth': 2, + 'nav_style': 'primary', + 'shortcuts': {'help': 191, 'next': 78, 'previous': 80, 'search': 83}, + }, + ) + + @tempdir() + def test_custom_dir(self, custom): + theme = Theme(name='mkdocs', custom_dir=custom) + self.assertEqual( + theme.dirs, + [ + custom, + os.path.join(theme_dir, 'mkdocs'), + mkdocs_templates_dir, + ], + ) + + @tempdir() + def test_custom_dir_only(self, custom): + theme = Theme(name=None, custom_dir=custom) + self.assertEqual( + theme.dirs, + [custom, mkdocs_templates_dir], + ) + + def static_templates(self): + theme = Theme(name='mkdocs', static_templates='foo.html') + self.assertEqual( + theme.static_templates, + {'404.html', 'sitemap.xml', 'foo.html'}, + ) + + def test_vars(self): + theme = Theme(name='mkdocs', foo='bar', baz=True) + self.assertEqual(theme['foo'], 'bar') + self.assertEqual(theme['baz'], True) + self.assertTrue('new' not in theme) + with self.assertRaises(KeyError): + theme['new'] + theme['new'] = 42 + self.assertTrue('new' in theme) + self.assertEqual(theme['new'], 42) + + @mock.patch('mkdocs.utils.yaml_load', return_value={}) + def test_no_theme_config(self, m): + theme = Theme(name='mkdocs') + self.assertEqual(m.call_count, 1) + self.assertEqual(theme.static_templates, {'sitemap.xml'}) + + def test_inherited_theme(self): + m = mock.Mock( + side_effect=[ + {'extends': 'readthedocs', 'static_templates': ['child.html']}, + {'static_templates': ['parent.html']}, + ] + ) + with mock.patch('mkdocs.utils.yaml_load', m) as m: + theme = Theme(name='mkdocs') + self.assertEqual(m.call_count, 2) + self.assertEqual( + theme.dirs, + [ + os.path.join(theme_dir, 'mkdocs'), + os.path.join(theme_dir, 'readthedocs'), + mkdocs_templates_dir, + ], + ) + self.assertEqual(theme.static_templates, {'sitemap.xml', 'child.html', 'parent.html'}) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/utils/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/utils/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/utils/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..39db05328b2bbee0d2a237ef5959a925f4ec0fc6 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/utils/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/utils/__pycache__/babel_stub_tests.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/utils/__pycache__/babel_stub_tests.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..152616dffe315338eeccc01745738b1f6e8e62f7 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/utils/__pycache__/babel_stub_tests.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/utils/__pycache__/templates_tests.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/utils/__pycache__/templates_tests.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eea5238b87d1268cb04b1a57301447cb656c9cc1 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/utils/__pycache__/templates_tests.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/utils/__pycache__/utils_tests.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/utils/__pycache__/utils_tests.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..71dfb7a35a3fcc4277046fe726a2d8d2d949e98e Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/utils/__pycache__/utils_tests.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/utils/babel_stub_tests.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/utils/babel_stub_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..ec810471d8ebfaa68cdaac7f39329101b4e9a85c --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/utils/babel_stub_tests.py @@ -0,0 +1,55 @@ +import unittest + +from mkdocs.utils.babel_stub import Locale, UnknownLocaleError + + +class BabelStubTests(unittest.TestCase): + def test_locale_language_only(self): + locale = Locale('es') + self.assertEqual(locale.language, 'es') + self.assertEqual(locale.territory, '') + self.assertEqual(str(locale), 'es') + + def test_locale_language_territory(self): + locale = Locale('es', 'ES') + self.assertEqual(locale.language, 'es') + self.assertEqual(locale.territory, 'ES') + self.assertEqual(str(locale), 'es_ES') + + def test_parse_locale_language_only(self): + locale = Locale.parse('fr', '_') + self.assertEqual(locale.language, 'fr') + self.assertEqual(locale.territory, '') + self.assertEqual(str(locale), 'fr') + + def test_parse_locale_language_territory(self): + locale = Locale.parse('fr_FR', '_') + self.assertEqual(locale.language, 'fr') + self.assertEqual(locale.territory, 'FR') + self.assertEqual(str(locale), 'fr_FR') + + def test_parse_locale_language_territory_sep(self): + locale = Locale.parse('fr-FR', '-') + self.assertEqual(locale.language, 'fr') + self.assertEqual(locale.territory, 'FR') + self.assertEqual(str(locale), 'fr_FR') + + def test_parse_locale_bad_type(self): + with self.assertRaises(TypeError): + Locale.parse(['list'], '_') + + def test_parse_locale_invalid_characters(self): + with self.assertRaises(ValueError): + Locale.parse('42', '_') + + def test_parse_locale_bad_format(self): + with self.assertRaises(ValueError): + Locale.parse('en-GB', '_') + + def test_parse_locale_bad_format_sep(self): + with self.assertRaises(ValueError): + Locale.parse('en_GB', '-') + + def test_parse_locale_unknown_locale(self): + with self.assertRaises(UnknownLocaleError): + Locale.parse('foo', '_') diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/utils/templates_tests.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/utils/templates_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..c6a8daaab6ecebd93553b34c6f92afc030bed828 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/utils/templates_tests.py @@ -0,0 +1,49 @@ +import unittest +from textwrap import dedent + +import yaml + +from mkdocs.tests.base import load_config +from mkdocs.utils import templates + + +class UtilsTemplatesTests(unittest.TestCase): + def test_script_tag(self): + cfg_yaml = dedent( + ''' + extra_javascript: + - some_plain_javascript.js + - implicitly_as_module.mjs + - path: explicitly_as_module.mjs + type: module + - path: deferred_plain.js + defer: true + - path: scripts/async_module.mjs + type: module + async: true + - path: 'aaaaaa/"my script".mjs' + type: module + async: true + defer: true + - path: plain.mjs + ''' + ) + config = load_config(**yaml.safe_load(cfg_yaml)) + config.extra_javascript.append('plain_string.mjs') + + self.assertEqual( + [ + str(templates.script_tag_filter({'page': None, 'base_url': 'here'}, item)) + for item in config.extra_javascript + ], + [ + '', + '', + '', + '', + '', + '', + '', + '', + ], + ) diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/utils/utils_tests.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/utils/utils_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..a72044e2743b2c71906dd32b07be6b4ee11070af --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/tests/utils/utils_tests.py @@ -0,0 +1,597 @@ +#!/usr/bin/env python + +import dataclasses +import datetime +import logging +import os +import posixpath +import stat +import unittest +from unittest import mock + +from mkdocs import exceptions, utils +from mkdocs.tests.base import dedent, tempdir +from mkdocs.utils import meta + +BASEYML = """ +INHERIT: parent.yml +foo: bar +baz: + sub1: replaced + sub3: new +deep1: + deep2-1: + deep3-1: replaced +""" +PARENTYML = """ +foo: foo +baz: + sub1: 1 + sub2: 2 +deep1: + deep2-1: + deep3-1: foo + deep3-2: bar + deep2-2: baz +""" + + +class UtilsTests(unittest.TestCase): + def test_is_markdown_file(self): + expected_results = { + 'index.md': True, + 'index.markdown': True, + 'index.MARKDOWN': False, + 'index.txt': False, + 'indexmd': False, + } + for path, expected_result in expected_results.items(): + with self.subTest(path): + is_markdown = utils.is_markdown_file(path) + self.assertEqual(is_markdown, expected_result) + + def test_get_relative_url(self): + for case in [ + dict(url='foo/bar', other='foo', expected='bar'), + dict(url='foo/bar.txt', other='foo', expected='bar.txt'), + dict(url='foo', other='foo/bar', expected='..'), + dict(url='foo', other='foo/bar.txt', expected='.'), + dict(url='foo/../../bar', other='.', expected='bar'), + dict(url='foo/../../bar', other='foo', expected='../bar'), + dict(url='foo//./bar/baz', other='foo/bar/baz', expected='.'), + dict(url='a/b/.././../c', other='.', expected='c'), + dict(url='a/b/c/d/ee', other='a/b/c/d/e', expected='../ee'), + dict(url='a/b/c/d/ee', other='a/b/z/d/e', expected='../../../c/d/ee'), + dict(url='foo', other='bar.', expected='foo'), + dict(url='foo', other='bar./', expected='../foo'), + dict(url='foo', other='foo/bar./', expected='..'), + dict(url='foo', other='foo/bar./.', expected='..'), + dict(url='foo', other='foo/bar././', expected='..'), + dict(url='foo/', other='foo/bar././', expected='../'), + dict(url='foo', other='foo', expected='.'), + dict(url='.foo', other='.foo', expected='.foo'), + dict(url='.foo/', other='.foo', expected='.foo/'), + dict(url='.foo', other='.foo/', expected='.'), + dict(url='.foo/', other='.foo/', expected='./'), + dict(url='///', other='', expected='./'), + dict(url='a///', other='', expected='a/'), + dict(url='a///', other='a', expected='./'), + dict(url='.', other='here', expected='..'), + dict(url='..', other='here', expected='..'), + dict(url='../..', other='here', expected='..'), + dict(url='../../a', other='here', expected='../a'), + dict(url='..', other='here.txt', expected='.'), + dict(url='a', other='', expected='a'), + dict(url='a', other='..', expected='a'), + dict(url='a', other='b', expected='../a'), + # The dots are considered a file. Documenting a long-standing bug: + dict(url='a', other='b/..', expected='../a'), + dict(url='a', other='b/../..', expected='a'), + dict(url='a/..../b', other='a/../b', expected='../a/..../b'), + dict(url='a/я/b', other='a/я/c', expected='../b'), + dict(url='a/я/b', other='a/яя/c', expected='../../я/b'), + ]: + url, other, expected = case['url'], case['other'], case['expected'] + with self.subTest(url=url, other=other): + # Leading slash intentionally ignored + self.assertEqual(utils.get_relative_url(url, other), expected) + self.assertEqual(utils.get_relative_url('/' + url, other), expected) + self.assertEqual(utils.get_relative_url(url, '/' + other), expected) + self.assertEqual(utils.get_relative_url('/' + url, '/' + other), expected) + + def test_get_relative_url_empty(self): + for url in ['', '.', '/.']: + for other in ['', '.', '/', '/.']: + with self.subTest(url=url, other=other): + self.assertEqual(utils.get_relative_url(url, other), '.') + + self.assertEqual(utils.get_relative_url('/', ''), './') + self.assertEqual(utils.get_relative_url('/', '/'), './') + self.assertEqual(utils.get_relative_url('/', '.'), './') + self.assertEqual(utils.get_relative_url('/', '/.'), './') + + def test_normalize_url(self): + def test(path, base, expected): + self.assertEqual(utils.normalize_url(path, _Page(base)), expected) + + # Absolute paths and anchors are unaffected. + for base in 'about.html', 'foo/bar.html', 'index.html', '', 'about/', 'foo/bar/': + test('https://media.cdn.org/jq.js', base, 'https://media.cdn.org/jq.js') + test('http://media.cdn.org/jquery.js', base, 'http://media.cdn.org/jquery.js') + test('//media.cdn.org/jquery.js', base, '//media.cdn.org/jquery.js') + test('#some_id', base, '#some_id') + + path = 'media.cdn.org/jquery.js' + test(path, '', 'media.cdn.org/jquery.js') + test(path, 'index.html', 'media.cdn.org/jquery.js') + test(path, 'about.html', 'media.cdn.org/jquery.js') + test(path, 'about/', '../media.cdn.org/jquery.js') + test(path, 'foo/bar.html', '../media.cdn.org/jquery.js') + test(path, 'foo/bar/', '../../media.cdn.org/jquery.js') + + path = 'local/file/jquery.js' + test(path, '', 'local/file/jquery.js') + test(path, 'index.html', 'local/file/jquery.js') + test(path, 'about.html', 'local/file/jquery.js') + test(path, 'about/', '../local/file/jquery.js') + test(path, 'foo/bar.html', '../local/file/jquery.js') + test(path, 'foo/bar/', '../../local/file/jquery.js') + + path = '../../../../above/jquery.js' + test(path, '', '../../../../above/jquery.js') + test(path, 'index.html', '../../../../above/jquery.js') + test(path, 'about.html', '../../../../above/jquery.js') + test(path, 'about/', '../../../../../above/jquery.js') + test(path, 'foo/bar.html', '../../../../../above/jquery.js') + test(path, 'foo/bar/', '../../../../../../above/jquery.js') + + path = '../some/dir/' + test(path, '', '../some/dir/') + test(path, 'index.html', '../some/dir/') + test(path, 'about.html', '../some/dir/') + test(path, 'about/', '../../some/dir/') + test(path, 'foo/bar.html', '../../some/dir/') + test(path, 'foo/bar/', '../../../some/dir/') + + path = 'image.png' + test(path, '', 'image.png') + test(path, 'index.html', 'image.png') + test(path, 'about.html', 'image.png') + test(path, 'about/', '../image.png') + test(path, 'foo/bar.html', '../image.png') + test(path, 'foo/bar/', '../../image.png') + + path = 'style.css?v=20180308c' + test(path, '', 'style.css?v=20180308c') + test(path, 'index.html', 'style.css?v=20180308c') + test(path, 'about.html', 'style.css?v=20180308c') + test(path, 'about/', '../style.css?v=20180308c') + test(path, 'foo/bar.html', '../style.css?v=20180308c') + test(path, 'foo/bar/', '../../style.css?v=20180308c') + + # TODO: This shouldn't pass on Linux + # @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows") + def test_normalize_url_windows(self): + def test(path, base, expected): + self.assertEqual(utils.normalize_url(path, _Page(base)), expected) + + with self.assertLogs('mkdocs', level='WARNING'): + path = 'local\\windows\\file\\jquery.js' + test(path, '', 'local/windows/file/jquery.js') + test(path, 'about/', '../local/windows/file/jquery.js') + test(path, 'foo/bar/', '../../local/windows/file/jquery.js') + + def test_reduce_list(self): + self.assertEqual( + utils.reduce_list([1, 2, 3, 4, 5, 5, 2, 4, 6, 7, 8]), + [1, 2, 3, 4, 5, 6, 7, 8], + ) + + def test_insort(self): + a = [1, 2, 3] + utils.insort(a, 5) + self.assertEqual(a, [1, 2, 3, 5]) + utils.insort(a, -1) + self.assertEqual(a, [-1, 1, 2, 3, 5]) + utils.insort(a, 2) + self.assertEqual(a, [-1, 1, 2, 2, 3, 5]) + utils.insort(a, 4) + self.assertEqual(a, [-1, 1, 2, 2, 3, 4, 5]) + + def test_insort_key(self): + a = [(1, 'a'), (1, 'b'), (2, 'c')] + utils.insort(a, (1, 'a'), key=lambda v: v[0]) + self.assertEqual(a, [(1, 'a'), (1, 'b'), (1, 'a'), (2, 'c')]) + + def test_get_themes(self): + themes = utils.get_theme_names() + self.assertIn('mkdocs', themes) + self.assertIn('readthedocs', themes) + + @mock.patch('mkdocs.utils.entry_points', autospec=True) + def test_get_theme_dir(self, mock_iter): + path = 'some/path' + + theme = mock.Mock() + theme.name = 'mkdocs2' + theme.dist.name = 'mkdocs2' + theme.load().__file__ = os.path.join(path, '__init__.py') + + mock_iter.return_value = [theme] + + self.assertEqual(utils.get_theme_dir(theme.name), os.path.abspath(path)) + + def test_get_theme_dir_keyerror(self): + with self.assertRaises(KeyError): + utils.get_theme_dir('nonexistanttheme') + + @mock.patch('mkdocs.utils.entry_points', autospec=True) + def test_get_theme_dir_importerror(self, mock_iter): + theme = mock.Mock() + theme.name = 'mkdocs2' + theme.dist.name = 'mkdocs2' + theme.load.side_effect = ImportError() + + mock_iter.return_value = [theme] + + with self.assertRaises(ImportError): + utils.get_theme_dir(theme.name) + + @mock.patch('mkdocs.utils.entry_points', autospec=True) + def test_get_themes_warning(self, mock_iter): + theme1 = mock.Mock() + theme1.name = 'mkdocs2' + theme1.dist.name = 'mkdocs2' + theme1.load().__file__ = "some/path1" + + theme2 = mock.Mock() + theme2.name = 'mkdocs2' + theme2.dist.name = 'mkdocs3' + theme2.load().__file__ = "some/path2" + + mock_iter.return_value = [theme1, theme2] + + with self.assertLogs('mkdocs') as cm: + theme_names = utils.get_theme_names() + self.assertEqual( + '\n'.join(cm.output), + "WARNING:mkdocs.utils:A theme named 'mkdocs2' is provided by the Python " + "packages 'mkdocs3' and 'mkdocs2'. The one in 'mkdocs3' will be used.", + ) + self.assertCountEqual(theme_names, ['mkdocs2']) + + @mock.patch('mkdocs.utils.entry_points', autospec=True) + def test_get_themes_error(self, mock_iter): + theme1 = mock.Mock() + theme1.name = 'mkdocs' + theme1.dist.name = 'mkdocs' + theme1.load().__file__ = "some/path1" + + theme2 = mock.Mock() + theme2.name = 'mkdocs' + theme2.dist.name = 'mkdocs2' + theme2.load().__file__ = "some/path2" + + mock_iter.return_value = [theme1, theme2] + + with self.assertRaisesRegex( + exceptions.ConfigurationError, + "The theme 'mkdocs' is a builtin theme but the package 'mkdocs2' " + "attempts to provide a theme with the same name.", + ): + utils.get_theme_names() + + def test_nest_paths(self, j=posixpath.join): + result = utils.nest_paths( + [ + 'index.md', + j('user-guide', 'configuration.md'), + j('user-guide', 'styling-your-docs.md'), + j('user-guide', 'writing-your-docs.md'), + j('about', 'contributing.md'), + j('about', 'license.md'), + j('about', 'release-notes.md'), + ] + ) + + self.assertEqual( + result, + [ + 'index.md', + { + 'User guide': [ + j('user-guide', 'configuration.md'), + j('user-guide', 'styling-your-docs.md'), + j('user-guide', 'writing-your-docs.md'), + ] + }, + { + 'About': [ + j('about', 'contributing.md'), + j('about', 'license.md'), + j('about', 'release-notes.md'), + ] + }, + ], + ) + + def test_nest_paths_native(self): + self.test_nest_paths(os.path.join) + + def test_unicode_yaml(self): + yaml_src = dedent( + ''' + key: value + key2: + - value + ''' + ) + + config = utils.yaml_load(yaml_src) + self.assertTrue(isinstance(config['key'], str)) + self.assertTrue(isinstance(config['key2'][0], str)) + + @mock.patch.dict(os.environ, {'VARNAME': 'Hello, World!', 'BOOLVAR': 'false'}) + def test_env_var_in_yaml(self): + yaml_src = dedent( + ''' + key1: !ENV VARNAME + key2: !ENV UNDEFINED + key3: !ENV [UNDEFINED, default] + key4: !ENV [UNDEFINED, VARNAME, default] + key5: !ENV BOOLVAR + ''' + ) + config = utils.yaml_load(yaml_src) + self.assertEqual(config['key1'], 'Hello, World!') + self.assertIsNone(config['key2']) + self.assertEqual(config['key3'], 'default') + self.assertEqual(config['key4'], 'Hello, World!') + self.assertIs(config['key5'], False) + + @tempdir(files={'base.yml': BASEYML, 'parent.yml': PARENTYML}) + def test_yaml_inheritance(self, tdir): + expected = { + 'foo': 'bar', + 'baz': { + 'sub1': 'replaced', + 'sub2': 2, + 'sub3': 'new', + }, + 'deep1': { + 'deep2-1': { + 'deep3-1': 'replaced', + 'deep3-2': 'bar', + }, + 'deep2-2': 'baz', + }, + } + with open(os.path.join(tdir, 'base.yml')) as fd: + result = utils.yaml_load(fd) + self.assertEqual(result, expected) + + @tempdir(files={'base.yml': BASEYML}) + def test_yaml_inheritance_missing_parent(self, tdir): + with open(os.path.join(tdir, 'base.yml')) as fd: + with self.assertRaises(exceptions.ConfigurationError): + utils.yaml_load(fd) + + @tempdir() + @tempdir() + def test_copy_files(self, src_dir, dst_dir): + cases = [ + dict( + src_path='foo.txt', + dst_path='foo.txt', + expected='foo.txt', + ), + dict( + src_path='bar.txt', + dst_path='foo/', # ensure src filename is appended + expected='foo/bar.txt', + ), + dict( + src_path='baz.txt', + dst_path='foo/bar/baz.txt', # ensure missing dirs are created + expected='foo/bar/baz.txt', + ), + ] + + for case in cases: + src, dst, expected = case['src_path'], case['dst_path'], case['expected'] + with self.subTest(src): + src = os.path.join(src_dir, src) + with open(src, 'w') as f: + f.write('content') + dst = os.path.join(dst_dir, dst) + utils.copy_file(src, dst) + self.assertTrue(os.path.isfile(os.path.join(dst_dir, expected))) + + @tempdir() + @tempdir() + def test_copy_files_without_permissions(self, src_dir, dst_dir): + cases = [ + dict(src_path='foo.txt', expected='foo.txt'), + dict(src_path='bar.txt', expected='bar.txt'), + dict(src_path='baz.txt', expected='baz.txt'), + ] + + try: + for case in cases: + src, expected = case['src_path'], case['expected'] + with self.subTest(src): + src = os.path.join(src_dir, src) + with open(src, 'w') as f: + f.write('content') + # Set src file to read-only + os.chmod(src, stat.S_IRUSR) + utils.copy_file(src, dst_dir) + self.assertTrue(os.path.isfile(os.path.join(dst_dir, expected))) + self.assertNotEqual( + os.stat(src).st_mode, os.stat(os.path.join(dst_dir, expected)).st_mode + ) + # While src was read-only, dst must remain writable + self.assertTrue(os.access(os.path.join(dst_dir, expected), os.W_OK)) + finally: + for case in cases: + # Undo read-only so we can delete temp files + src = os.path.join(src_dir, case['src_path']) + if os.path.exists(src): + os.chmod(src, stat.S_IRUSR | stat.S_IWUSR) + + def test_mm_meta_data(self): + doc = dedent( + """ + Title: Foo Bar + Date: 2018-07-10 + Summary: Line one + Line two + Tags: foo + Tags: bar + + Doc body + """ + ) + self.assertEqual( + meta.get_data(doc), + ( + "Doc body", + { + 'title': 'Foo Bar', + 'date': '2018-07-10', + 'summary': 'Line one Line two', + 'tags': 'foo bar', + }, + ), + ) + + def test_mm_meta_data_blank_first_line(self): + doc = '\nfoo: bar\nDoc body' + self.assertEqual(meta.get_data(doc), (doc.lstrip(), {})) + + def test_yaml_meta_data(self): + doc = dedent( + """ + --- + Title: Foo Bar + Date: 2018-07-10 + Summary: Line one + Line two + Tags: + - foo + - bar + --- + Doc body + """ + ) + self.assertEqual( + meta.get_data(doc), + ( + "Doc body", + { + 'Title': 'Foo Bar', + 'Date': datetime.date(2018, 7, 10), + 'Summary': 'Line one Line two', + 'Tags': ['foo', 'bar'], + }, + ), + ) + + def test_yaml_meta_data_not_dict(self): + doc = dedent( + """ + --- + - List item + --- + Doc body + """ + ) + self.assertEqual(meta.get_data(doc), (doc, {})) + + def test_yaml_meta_data_invalid(self): + doc = dedent( + """ + --- + foo: bar: baz + --- + Doc body + """ + ) + self.assertEqual(meta.get_data(doc), (doc, {})) + + def test_no_meta_data(self): + doc = dedent( + """ + Doc body + """ + ) + self.assertEqual(meta.get_data(doc), (doc, {})) + + +class LogCounterTests(unittest.TestCase): + def setUp(self): + self.log = logging.getLogger('dummy') + self.log.propagate = False + self.log.setLevel(1) + self.counter = utils.CountHandler() + self.log.addHandler(self.counter) + + def tearDown(self): + self.log.removeHandler(self.counter) + + def test_default_values(self): + self.assertEqual(self.counter.get_counts(), []) + + def test_count_critical(self): + self.assertEqual(self.counter.get_counts(), []) + self.log.critical('msg') + self.assertEqual(self.counter.get_counts(), [('CRITICAL', 1)]) + + def test_count_error(self): + self.assertEqual(self.counter.get_counts(), []) + self.log.error('msg') + self.assertEqual(self.counter.get_counts(), [('ERROR', 1)]) + + def test_count_warning(self): + self.assertEqual(self.counter.get_counts(), []) + self.log.warning('msg') + self.assertEqual(self.counter.get_counts(), [('WARNING', 1)]) + + def test_count_info(self): + self.assertEqual(self.counter.get_counts(), []) + self.log.info('msg') + self.assertEqual(self.counter.get_counts(), [('INFO', 1)]) + + def test_count_debug(self): + self.assertEqual(self.counter.get_counts(), []) + self.log.debug('msg') + self.assertEqual(self.counter.get_counts(), [('DEBUG', 1)]) + + def test_count_multiple(self): + self.assertEqual(self.counter.get_counts(), []) + self.log.warning('msg 1') + self.assertEqual(self.counter.get_counts(), [('WARNING', 1)]) + self.log.warning('msg 2') + self.assertEqual(self.counter.get_counts(), [('WARNING', 2)]) + self.log.debug('msg 3') + self.assertEqual(self.counter.get_counts(), [('WARNING', 2), ('DEBUG', 1)]) + self.log.error('mdg 4') + self.assertEqual(self.counter.get_counts(), [('ERROR', 1), ('WARNING', 2), ('DEBUG', 1)]) + + def test_log_level(self): + self.assertEqual(self.counter.get_counts(), []) + self.counter.setLevel(logging.ERROR) + self.log.error('counted') + self.log.warning('not counted') + self.log.info('not counted') + self.assertEqual(self.counter.get_counts(), [('ERROR', 1)]) + self.counter.setLevel(logging.WARNING) + self.log.error('counted') + self.log.warning('counted') + self.log.info('not counted') + self.assertEqual(self.counter.get_counts(), [('ERROR', 2), ('WARNING', 1)]) + + +@dataclasses.dataclass +class _Page: + url: str diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a8cb1837648cc07ca81d308f1f6dfaf545fa5bb5 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/404.html b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/404.html new file mode 100644 index 0000000000000000000000000000000000000000..c0503d746908777b3cde698eec33d71e0c3e745b --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/404.html @@ -0,0 +1,12 @@ +{% extends "base.html" %} + +{% block content %} + +
+
+

404

+

{% trans %}Page not found{% endtrans %}

+
+
+ +{% endblock %} diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/__init__.py b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/__pycache__/__init__.cpython-312.pyc b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4f7443a4ef8168886a89efcfcdcb720b68edc45a Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/base.html b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/base.html new file mode 100644 index 0000000000000000000000000000000000000000..2b077bd0164fdd109a79a3decda242a5725f1f0a --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/base.html @@ -0,0 +1,214 @@ + + + + {%- block site_meta %} + + + + {% if page and page.is_homepage %}{% endif %} + {% if config.site_author %}{% endif %} + {% if page and page.canonical_url %}{% endif %} + {% if config.site_favicon %} + {% else %}{% endif %} + {%- endblock %} + + {%- block htmltitle %} + {% if page and page.title and not page.is_homepage %}{{ page.title }} - {% endif %}{{ config.site_name }} + {%- endblock %} + + {%- block styles %} + + + + {%- if config.theme.highlightjs %} + + {%- endif %} + {%- for path in config.extra_css %} + + {%- endfor %} + {%- endblock %} + + {%- block libs %} + {%- if config.theme.highlightjs %} + + {%- for lang in config.theme.hljs_languages %} + + {%- endfor %} + + {%- endif %} + {%- endblock %} + + {%- block analytics %} + {%- if config.theme.analytics.gtag %} + + + {%- elif config.google_analytics %} + + {%- endif %} + {%- endblock %} + + {%- block extrahead %} {% endblock %} + + + + + +
+
+ {%- block content %} +
{% include "toc.html" %}
+
{% include "content.html" %}
+ {%- endblock %} +
+
+ +
+ {%- block footer %} +
+ {%- if config.copyright %} +

{{ config.copyright }}

+ {%- endif %} +

{% trans mkdocs_link='MkDocs' %}Documentation built with {{ mkdocs_link }}.{% endtrans %}

+ {%- endblock %} +
+ + {%- block scripts %} + + + + + {%- for script in config.extra_javascript %} + {{ script|script_tag }} + {%- endfor %} + {%- endblock %} + + {% if 'search' in config.plugins %}{%- include "search-modal.html" %}{% endif %} + {%- include "keyboard-modal.html" %} + + + +{% if page and page.is_homepage %} + +{% endif %} diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/content.html b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/content.html new file mode 100644 index 0000000000000000000000000000000000000000..ecf0a37e5f6566ca0551d2d48f7cdb6218f812ea --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/content.html @@ -0,0 +1,9 @@ +{% if page.meta.source %} + +{% endif %} + +{{ page.content }} diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/css/base.css b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/css/base.css new file mode 100644 index 0000000000000000000000000000000000000000..26103413ab0fe7fbc39a7585449bf0765da561bb --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/css/base.css @@ -0,0 +1,325 @@ +html { + /* csslint ignore:start */ + /* The nav header is 3.5rem high, plus 20px for the margin-top of the + main container. */ + scroll-padding-top: calc(3.5rem + 20px); + /* csslint ignore:end */ +} + +/* Replacement for `body { background-attachment: fixed; }`, which has + performance issues when scrolling on large displays. See #1394. */ +body::before { + content: ' '; + position: fixed; + width: 100%; + height: 100%; + top: 0; + left: 0; + background-color: #f8f8f8; + background: url(../img/grid.png) repeat-x; + will-change: transform; + z-index: -1; +} + +body > .container { + margin-top: 20px; + min-height: 400px; +} + +.navbar.fixed-top { /* csslint allow: adjoining-classes */ + /* csslint ignore:start */ + position: -webkit-sticky; + position: sticky; + /* csslint ignore:end */ +} + +.source-links { + float: right; +} + +.col-md-9 img { + max-width: 100%; + display: inline-block; + padding: 4px; + line-height: 1.428571429; + background-color: #fff; + border: 1px solid #ddd; + border-radius: 4px; + margin: 20px auto 30px auto; +} + +h1 { + color: #444; + font-weight: 400; + font-size: 42px; +} + +h2, h3, h4, h5, h6 { + color: #444; + font-weight: 300; +} + +hr { + border-top: 1px solid #aaa; +} + +pre, .rst-content tt { + max-width: 100%; + background: #fff; + border: solid 1px #e1e4e5; + color: #333; + overflow-x: auto; +} + +code.code-large, .rst-content tt.code-large { + font-size: 90%; +} + +code { + padding: 2px 5px; + background: #fff; + border: solid 1px #e1e4e5; + color: #333; + white-space: pre-wrap; + word-wrap: break-word; +} + +pre code { + display: block; + background: transparent; + border: none; + white-space: pre; + word-wrap: normal; + font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; + font-size: 12px; +} + +kbd { + padding: 2px 4px; + font-size: 90%; + color: #fff; + background-color: #333; + border-radius: 3px; + -webkit-box-shadow: inset 0 -1px 0 rgba(0,0,0,.25); + box-shadow: inset 0 -1px 0 rgba(0,0,0,.25); +} + +a code { + color: #2FA4E7; +} + +a:hover code, a:focus code { + color: #157AB5; +} + +footer { + margin-top: 30px; + margin-bottom: 10px; + text-align: center; + font-weight: 200; +} + +.modal-dialog { + margin-top: 60px; +} + +/* + * Side navigation + * + * Scrollspy and affixed enhanced navigation to highlight sections and secondary + * sections of docs content. + */ + +.bs-sidebar.affix { /* csslint allow: adjoining-classes */ + /* csslint ignore:start */ + position: -webkit-sticky; + position: sticky; + /* csslint ignore:end */ + /* The nav header is 3.5rem high, plus 20px for the margin-top of the + main container. */ + top: calc(3.5rem + 20px); +} + +.bs-sidebar.card { /* csslint allow: adjoining-classes */ + padding: 0; + max-height: 90%; + overflow-y: auto; +} + +/* Toggle (vertically flip) sidebar collapse icon */ +.bs-sidebar .navbar-toggler span { + -moz-transform: scale(1, -1); + -webkit-transform: scale(1, -1); + -o-transform: scale(1, -1); + -ms-transform: scale(1, -1); + transform: scale(1, -1); +} + +.bs-sidebar .navbar-toggler.collapsed span { /* csslint allow: adjoining-classes */ + -moz-transform: scale(1, 1); + -webkit-transform: scale(1, 1); + -o-transform: scale(1, 1); + -ms-transform: scale(1, 1); + transform: scale(1, 1); +} + +/* First level of nav */ +.bs-sidebar > .navbar-collapse > .nav { + padding-top: 10px; + padding-bottom: 10px; + border-radius: 5px; + width: 100%; +} + +/* All levels of nav */ +.bs-sidebar .nav > li > a { + display: block; + padding: 5px 20px; + z-index: 1; +} +.bs-sidebar .nav > li > a:hover, +.bs-sidebar .nav > li > a:focus { + text-decoration: none; + border-right: 1px solid; +} +.bs-sidebar .nav > li > a.active, +.bs-sidebar .nav > li > a.active:hover, +.bs-sidebar .nav > li > a.active:focus { + font-weight: bold; + background-color: transparent; + border-right: 1px solid; +} + +.bs-sidebar .nav .nav .nav { + margin-left: 1em; +} + +.bs-sidebar .nav > li > a { + font-weight: bold; +} + +.bs-sidebar .nav .nav > li > a { + font-weight: normal; +} + +.headerlink { + font-family: FontAwesome; + font-size: 14px; + display: none; + padding-left: .5em; +} + +h1:hover .headerlink, h2:hover .headerlink, h3:hover .headerlink, h4:hover .headerlink, h5:hover .headerlink, h6:hover .headerlink { + display:inline-block; +} + +blockquote { + padding-left: 10px; + border-left: 4px solid #e6e6e6; +} + +.admonition, details { + padding: 15px; + margin-bottom: 20px; + border: 1px solid transparent; + border-radius: 4px; + text-align: left; +} + +.admonition.note, details.note { /* csslint allow: adjoining-classes */ + color: #2e6b89; + background-color: #e2f0f7; + border-color: #bce8f1; +} + +.admonition.warning, details.warning { /* csslint allow: adjoining-classes */ + color: #7a6032; + background-color: #fffae5; + border-color: #fbeed5; +} + +.admonition.danger, details.danger { /* csslint allow: adjoining-classes */ + color: #7f3130; + background-color: #fde3e3; + border-color: #eed3d7; +} + +.admonition-title, summary { + font-weight: bold; + text-align: left; +} + +.admonition>p:last-child, details>p:last-child { + margin-bottom: 0; +} + +@media (max-width: 991.98px) { + .navbar-collapse.show { /* csslint allow: adjoining-classes */ + overflow-y: auto; + max-height: calc(100vh - 3.5rem); + } +} + +.dropdown-item.open { /* csslint allow: adjoining-classes */ + color: #fff; + background-color: #2FA4E7; +} + +.dropdown-submenu > .dropdown-menu { + margin: 0 0 0 1.5rem; + padding: 0; + border-width: 0; +} + +.dropdown-submenu > a::after { + display: block; + content: " "; + float: right; + width: 0; + height: 0; + border-color: transparent; + border-style: solid; + border-width: 5px 0 5px 5px; + border-left-color: #ccc; + margin-top: 5px; + margin-right: -10px; +} + +.dropdown-submenu:hover > a::after { + border-left-color: #fff; +} + +@media (min-width: 992px) { + .dropdown-menu { + overflow-y: auto; + max-height: calc(100vh - 3.5rem); + } + + .dropdown-submenu { + position: relative; + } + + .dropdown-submenu > .dropdown-menu { + /* csslint ignore:start */ + position: fixed !important; + /* csslint ignore:end */ + margin-top: -9px; + margin-left: -2px; + border-width: 1px; + padding: 0.5rem 0; + } + + .dropdown-submenu.pull-left { /* csslint allow: adjoining-classes */ + float: none; + } + + .dropdown-submenu.pull-left > .dropdown-menu { /* csslint allow: adjoining-classes */ + left: -100%; + margin-left: 10px; + } +} + +@media print { + /* Remove sidebar when print */ + .col-md-3 { display: none; } +} diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/css/bootstrap.min.css b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/css/bootstrap.min.css new file mode 100644 index 0000000000000000000000000000000000000000..4ce503d7fd245faf1101936e41f6ef7c39a4ca6c --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/css/bootstrap.min.css @@ -0,0 +1,12 @@ +/*! + * Bootswatch v4.1.3 + * Homepage: https://bootswatch.com + * Copyright 2012-2018 Thomas Park + * Licensed under MIT + * Based on Bootstrap +*//*! + * Bootstrap v4.1.3 (https://getbootstrap.com/) + * Copyright 2011-2018 The Bootstrap Authors + * Copyright 2011-2018 Twitter, Inc. + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) + */:root{--blue:#033C73;--indigo:#6610f2;--purple:#6f42c1;--pink:#e83e8c;--red:#C71C22;--orange:#fd7e14;--yellow:#DD5600;--green:#73A839;--teal:#20c997;--cyan:#2FA4E7;--white:#fff;--gray:#868e96;--gray-dark:#343a40;--primary:#2FA4E7;--secondary:#e9ecef;--success:#73A839;--info:#033C73;--warning:#DD5600;--danger:#C71C22;--light:#f8f9fa;--dark:#343a40;--breakpoint-xs:0;--breakpoint-sm:576px;--breakpoint-md:768px;--breakpoint-lg:992px;--breakpoint-xl:1200px;--font-family-sans-serif:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";--font-family-monospace:SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace}*,*::before,*::after{-webkit-box-sizing:border-box;box-sizing:border-box}html{font-family:sans-serif;line-height:1.15;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%;-ms-overflow-style:scrollbar;-webkit-tap-highlight-color:transparent}@-ms-viewport{width:device-width}article,aside,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}body{margin:0;font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";font-size:1rem;font-weight:400;line-height:1.5;color:#495057;text-align:left;background-color:#fff}[tabindex="-1"]:focus{outline:0 !important}hr{-webkit-box-sizing:content-box;box-sizing:content-box;height:0;overflow:visible}h1,h2,h3,h4,h5,h6{margin-top:0;margin-bottom:0.5rem}p{margin-top:0;margin-bottom:1rem}abbr[title],abbr[data-original-title]{text-decoration:underline;-webkit-text-decoration:underline dotted;text-decoration:underline dotted;cursor:help;border-bottom:0}address{margin-bottom:1rem;font-style:normal;line-height:inherit}ol,ul,dl{margin-top:0;margin-bottom:1rem}ol ol,ul ul,ol ul,ul ol{margin-bottom:0}dt{font-weight:700}dd{margin-bottom:.5rem;margin-left:0}blockquote{margin:0 0 1rem}dfn{font-style:italic}b,strong{font-weight:bolder}small{font-size:80%}sub,sup{position:relative;font-size:75%;line-height:0;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}a{color:#2FA4E7;text-decoration:none;background-color:transparent;-webkit-text-decoration-skip:objects}a:hover{color:#157ab5;text-decoration:underline}a:not([href]):not([tabindex]){color:inherit;text-decoration:none}a:not([href]):not([tabindex]):hover,a:not([href]):not([tabindex]):focus{color:inherit;text-decoration:none}a:not([href]):not([tabindex]):focus{outline:0}pre,code,kbd,samp{font-family:SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;font-size:1em}pre{margin-top:0;margin-bottom:1rem;overflow:auto;-ms-overflow-style:scrollbar}figure{margin:0 0 1rem}img{vertical-align:middle;border-style:none}svg{overflow:hidden;vertical-align:middle}table{border-collapse:collapse}caption{padding-top:0.75rem;padding-bottom:0.75rem;color:#868e96;text-align:left;caption-side:bottom}th{text-align:inherit}label{display:inline-block;margin-bottom:0.5rem}button{border-radius:0}button:focus{outline:1px dotted;outline:5px auto -webkit-focus-ring-color}input,button,select,optgroup,textarea{margin:0;font-family:inherit;font-size:inherit;line-height:inherit}button,input{overflow:visible}button,select{text-transform:none}button,html [type="button"],[type="reset"],[type="submit"]{-webkit-appearance:button}button::-moz-focus-inner,[type="button"]::-moz-focus-inner,[type="reset"]::-moz-focus-inner,[type="submit"]::-moz-focus-inner{padding:0;border-style:none}input[type="radio"],input[type="checkbox"]{-webkit-box-sizing:border-box;box-sizing:border-box;padding:0}input[type="date"],input[type="time"],input[type="datetime-local"],input[type="month"]{-webkit-appearance:listbox}textarea{overflow:auto;resize:vertical}fieldset{min-width:0;padding:0;margin:0;border:0}legend{display:block;width:100%;max-width:100%;padding:0;margin-bottom:.5rem;font-size:1.5rem;line-height:inherit;color:inherit;white-space:normal}progress{vertical-align:baseline}[type="number"]::-webkit-inner-spin-button,[type="number"]::-webkit-outer-spin-button{height:auto}[type="search"]{outline-offset:-2px;-webkit-appearance:none}[type="search"]::-webkit-search-cancel-button,[type="search"]::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{font:inherit;-webkit-appearance:button}output{display:inline-block}summary{display:list-item;cursor:pointer}template{display:none}[hidden]{display:none !important}h1,h2,h3,h4,h5,h6,.h1,.h2,.h3,.h4,.h5,.h6{margin-bottom:0.5rem;font-family:inherit;font-weight:500;line-height:1.2;color:#2FA4E7}h1,.h1{font-size:2.5rem}h2,.h2{font-size:2rem}h3,.h3{font-size:1.75rem}h4,.h4{font-size:1.5rem}h5,.h5{font-size:1.25rem}h6,.h6{font-size:1rem}.lead{font-size:1.25rem;font-weight:300}.display-1{font-size:6rem;font-weight:300;line-height:1.2}.display-2{font-size:5.5rem;font-weight:300;line-height:1.2}.display-3{font-size:4.5rem;font-weight:300;line-height:1.2}.display-4{font-size:3.5rem;font-weight:300;line-height:1.2}hr{margin-top:1rem;margin-bottom:1rem;border:0;border-top:1px solid rgba(0,0,0,0.1)}small,.small{font-size:80%;font-weight:400}mark,.mark{padding:0.2em;background-color:#fcf8e3}.list-unstyled{padding-left:0;list-style:none}.list-inline{padding-left:0;list-style:none}.list-inline-item{display:inline-block}.list-inline-item:not(:last-child){margin-right:0.5rem}.initialism{font-size:90%;text-transform:uppercase}.blockquote{margin-bottom:1rem;font-size:1.25rem}.blockquote-footer{display:block;font-size:80%;color:#868e96}.blockquote-footer::before{content:"\2014 \00A0"}.img-fluid{max-width:100%;height:auto}.img-thumbnail{padding:0.25rem;background-color:#fff;border:1px solid #dee2e6;border-radius:0.25rem;max-width:100%;height:auto}.figure{display:inline-block}.figure-img{margin-bottom:0.5rem;line-height:1}.figure-caption{font-size:90%;color:#868e96}code{font-size:87.5%;color:#e83e8c;word-break:break-word}a>code{color:inherit}kbd{padding:0.2rem 0.4rem;font-size:87.5%;color:#fff;background-color:#212529;border-radius:0.2rem}kbd kbd{padding:0;font-size:100%;font-weight:700}pre{display:block;font-size:87.5%;color:#212529}pre code{font-size:inherit;color:inherit;word-break:normal}.pre-scrollable{max-height:340px;overflow-y:scroll}.container{width:100%;padding-right:15px;padding-left:15px;margin-right:auto;margin-left:auto}@media (min-width: 576px){.container{max-width:540px}}@media (min-width: 768px){.container{max-width:720px}}@media (min-width: 992px){.container{max-width:960px}}@media (min-width: 1200px){.container{max-width:1140px}}.container-fluid{width:100%;padding-right:15px;padding-left:15px;margin-right:auto;margin-left:auto}.row{display:-webkit-box;display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;margin-right:-15px;margin-left:-15px}.no-gutters{margin-right:0;margin-left:0}.no-gutters>.col,.no-gutters>[class*="col-"]{padding-right:0;padding-left:0}.col-1,.col-2,.col-3,.col-4,.col-5,.col-6,.col-7,.col-8,.col-9,.col-10,.col-11,.col-12,.col,.col-auto,.col-sm-1,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9,.col-sm-10,.col-sm-11,.col-sm-12,.col-sm,.col-sm-auto,.col-md-1,.col-md-2,.col-md-3,.col-md-4,.col-md-5,.col-md-6,.col-md-7,.col-md-8,.col-md-9,.col-md-10,.col-md-11,.col-md-12,.col-md,.col-md-auto,.col-lg-1,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9,.col-lg-10,.col-lg-11,.col-lg-12,.col-lg,.col-lg-auto,.col-xl-1,.col-xl-2,.col-xl-3,.col-xl-4,.col-xl-5,.col-xl-6,.col-xl-7,.col-xl-8,.col-xl-9,.col-xl-10,.col-xl-11,.col-xl-12,.col-xl,.col-xl-auto{position:relative;width:100%;min-height:1px;padding-right:15px;padding-left:15px}.col{-ms-flex-preferred-size:0;flex-basis:0;-webkit-box-flex:1;-ms-flex-positive:1;flex-grow:1;max-width:100%}.col-auto{-webkit-box-flex:0;-ms-flex:0 0 auto;flex:0 0 auto;width:auto;max-width:none}.col-1{-webkit-box-flex:0;-ms-flex:0 0 8.3333333333%;flex:0 0 8.3333333333%;max-width:8.3333333333%}.col-2{-webkit-box-flex:0;-ms-flex:0 0 16.6666666667%;flex:0 0 16.6666666667%;max-width:16.6666666667%}.col-3{-webkit-box-flex:0;-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.col-4{-webkit-box-flex:0;-ms-flex:0 0 33.3333333333%;flex:0 0 33.3333333333%;max-width:33.3333333333%}.col-5{-webkit-box-flex:0;-ms-flex:0 0 41.6666666667%;flex:0 0 41.6666666667%;max-width:41.6666666667%}.col-6{-webkit-box-flex:0;-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.col-7{-webkit-box-flex:0;-ms-flex:0 0 58.3333333333%;flex:0 0 58.3333333333%;max-width:58.3333333333%}.col-8{-webkit-box-flex:0;-ms-flex:0 0 66.6666666667%;flex:0 0 66.6666666667%;max-width:66.6666666667%}.col-9{-webkit-box-flex:0;-ms-flex:0 0 75%;flex:0 0 75%;max-width:75%}.col-10{-webkit-box-flex:0;-ms-flex:0 0 83.3333333333%;flex:0 0 83.3333333333%;max-width:83.3333333333%}.col-11{-webkit-box-flex:0;-ms-flex:0 0 91.6666666667%;flex:0 0 91.6666666667%;max-width:91.6666666667%}.col-12{-webkit-box-flex:0;-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.order-first{-webkit-box-ordinal-group:0;-ms-flex-order:-1;order:-1}.order-last{-webkit-box-ordinal-group:14;-ms-flex-order:13;order:13}.order-0{-webkit-box-ordinal-group:1;-ms-flex-order:0;order:0}.order-1{-webkit-box-ordinal-group:2;-ms-flex-order:1;order:1}.order-2{-webkit-box-ordinal-group:3;-ms-flex-order:2;order:2}.order-3{-webkit-box-ordinal-group:4;-ms-flex-order:3;order:3}.order-4{-webkit-box-ordinal-group:5;-ms-flex-order:4;order:4}.order-5{-webkit-box-ordinal-group:6;-ms-flex-order:5;order:5}.order-6{-webkit-box-ordinal-group:7;-ms-flex-order:6;order:6}.order-7{-webkit-box-ordinal-group:8;-ms-flex-order:7;order:7}.order-8{-webkit-box-ordinal-group:9;-ms-flex-order:8;order:8}.order-9{-webkit-box-ordinal-group:10;-ms-flex-order:9;order:9}.order-10{-webkit-box-ordinal-group:11;-ms-flex-order:10;order:10}.order-11{-webkit-box-ordinal-group:12;-ms-flex-order:11;order:11}.order-12{-webkit-box-ordinal-group:13;-ms-flex-order:12;order:12}.offset-1{margin-left:8.3333333333%}.offset-2{margin-left:16.6666666667%}.offset-3{margin-left:25%}.offset-4{margin-left:33.3333333333%}.offset-5{margin-left:41.6666666667%}.offset-6{margin-left:50%}.offset-7{margin-left:58.3333333333%}.offset-8{margin-left:66.6666666667%}.offset-9{margin-left:75%}.offset-10{margin-left:83.3333333333%}.offset-11{margin-left:91.6666666667%}@media (min-width: 576px){.col-sm{-ms-flex-preferred-size:0;flex-basis:0;-webkit-box-flex:1;-ms-flex-positive:1;flex-grow:1;max-width:100%}.col-sm-auto{-webkit-box-flex:0;-ms-flex:0 0 auto;flex:0 0 auto;width:auto;max-width:none}.col-sm-1{-webkit-box-flex:0;-ms-flex:0 0 8.3333333333%;flex:0 0 8.3333333333%;max-width:8.3333333333%}.col-sm-2{-webkit-box-flex:0;-ms-flex:0 0 16.6666666667%;flex:0 0 16.6666666667%;max-width:16.6666666667%}.col-sm-3{-webkit-box-flex:0;-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.col-sm-4{-webkit-box-flex:0;-ms-flex:0 0 33.3333333333%;flex:0 0 33.3333333333%;max-width:33.3333333333%}.col-sm-5{-webkit-box-flex:0;-ms-flex:0 0 41.6666666667%;flex:0 0 41.6666666667%;max-width:41.6666666667%}.col-sm-6{-webkit-box-flex:0;-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.col-sm-7{-webkit-box-flex:0;-ms-flex:0 0 58.3333333333%;flex:0 0 58.3333333333%;max-width:58.3333333333%}.col-sm-8{-webkit-box-flex:0;-ms-flex:0 0 66.6666666667%;flex:0 0 66.6666666667%;max-width:66.6666666667%}.col-sm-9{-webkit-box-flex:0;-ms-flex:0 0 75%;flex:0 0 75%;max-width:75%}.col-sm-10{-webkit-box-flex:0;-ms-flex:0 0 83.3333333333%;flex:0 0 83.3333333333%;max-width:83.3333333333%}.col-sm-11{-webkit-box-flex:0;-ms-flex:0 0 91.6666666667%;flex:0 0 91.6666666667%;max-width:91.6666666667%}.col-sm-12{-webkit-box-flex:0;-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.order-sm-first{-webkit-box-ordinal-group:0;-ms-flex-order:-1;order:-1}.order-sm-last{-webkit-box-ordinal-group:14;-ms-flex-order:13;order:13}.order-sm-0{-webkit-box-ordinal-group:1;-ms-flex-order:0;order:0}.order-sm-1{-webkit-box-ordinal-group:2;-ms-flex-order:1;order:1}.order-sm-2{-webkit-box-ordinal-group:3;-ms-flex-order:2;order:2}.order-sm-3{-webkit-box-ordinal-group:4;-ms-flex-order:3;order:3}.order-sm-4{-webkit-box-ordinal-group:5;-ms-flex-order:4;order:4}.order-sm-5{-webkit-box-ordinal-group:6;-ms-flex-order:5;order:5}.order-sm-6{-webkit-box-ordinal-group:7;-ms-flex-order:6;order:6}.order-sm-7{-webkit-box-ordinal-group:8;-ms-flex-order:7;order:7}.order-sm-8{-webkit-box-ordinal-group:9;-ms-flex-order:8;order:8}.order-sm-9{-webkit-box-ordinal-group:10;-ms-flex-order:9;order:9}.order-sm-10{-webkit-box-ordinal-group:11;-ms-flex-order:10;order:10}.order-sm-11{-webkit-box-ordinal-group:12;-ms-flex-order:11;order:11}.order-sm-12{-webkit-box-ordinal-group:13;-ms-flex-order:12;order:12}.offset-sm-0{margin-left:0}.offset-sm-1{margin-left:8.3333333333%}.offset-sm-2{margin-left:16.6666666667%}.offset-sm-3{margin-left:25%}.offset-sm-4{margin-left:33.3333333333%}.offset-sm-5{margin-left:41.6666666667%}.offset-sm-6{margin-left:50%}.offset-sm-7{margin-left:58.3333333333%}.offset-sm-8{margin-left:66.6666666667%}.offset-sm-9{margin-left:75%}.offset-sm-10{margin-left:83.3333333333%}.offset-sm-11{margin-left:91.6666666667%}}@media (min-width: 768px){.col-md{-ms-flex-preferred-size:0;flex-basis:0;-webkit-box-flex:1;-ms-flex-positive:1;flex-grow:1;max-width:100%}.col-md-auto{-webkit-box-flex:0;-ms-flex:0 0 auto;flex:0 0 auto;width:auto;max-width:none}.col-md-1{-webkit-box-flex:0;-ms-flex:0 0 8.3333333333%;flex:0 0 8.3333333333%;max-width:8.3333333333%}.col-md-2{-webkit-box-flex:0;-ms-flex:0 0 16.6666666667%;flex:0 0 16.6666666667%;max-width:16.6666666667%}.col-md-3{-webkit-box-flex:0;-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.col-md-4{-webkit-box-flex:0;-ms-flex:0 0 33.3333333333%;flex:0 0 33.3333333333%;max-width:33.3333333333%}.col-md-5{-webkit-box-flex:0;-ms-flex:0 0 41.6666666667%;flex:0 0 41.6666666667%;max-width:41.6666666667%}.col-md-6{-webkit-box-flex:0;-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.col-md-7{-webkit-box-flex:0;-ms-flex:0 0 58.3333333333%;flex:0 0 58.3333333333%;max-width:58.3333333333%}.col-md-8{-webkit-box-flex:0;-ms-flex:0 0 66.6666666667%;flex:0 0 66.6666666667%;max-width:66.6666666667%}.col-md-9{-webkit-box-flex:0;-ms-flex:0 0 75%;flex:0 0 75%;max-width:75%}.col-md-10{-webkit-box-flex:0;-ms-flex:0 0 83.3333333333%;flex:0 0 83.3333333333%;max-width:83.3333333333%}.col-md-11{-webkit-box-flex:0;-ms-flex:0 0 91.6666666667%;flex:0 0 91.6666666667%;max-width:91.6666666667%}.col-md-12{-webkit-box-flex:0;-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.order-md-first{-webkit-box-ordinal-group:0;-ms-flex-order:-1;order:-1}.order-md-last{-webkit-box-ordinal-group:14;-ms-flex-order:13;order:13}.order-md-0{-webkit-box-ordinal-group:1;-ms-flex-order:0;order:0}.order-md-1{-webkit-box-ordinal-group:2;-ms-flex-order:1;order:1}.order-md-2{-webkit-box-ordinal-group:3;-ms-flex-order:2;order:2}.order-md-3{-webkit-box-ordinal-group:4;-ms-flex-order:3;order:3}.order-md-4{-webkit-box-ordinal-group:5;-ms-flex-order:4;order:4}.order-md-5{-webkit-box-ordinal-group:6;-ms-flex-order:5;order:5}.order-md-6{-webkit-box-ordinal-group:7;-ms-flex-order:6;order:6}.order-md-7{-webkit-box-ordinal-group:8;-ms-flex-order:7;order:7}.order-md-8{-webkit-box-ordinal-group:9;-ms-flex-order:8;order:8}.order-md-9{-webkit-box-ordinal-group:10;-ms-flex-order:9;order:9}.order-md-10{-webkit-box-ordinal-group:11;-ms-flex-order:10;order:10}.order-md-11{-webkit-box-ordinal-group:12;-ms-flex-order:11;order:11}.order-md-12{-webkit-box-ordinal-group:13;-ms-flex-order:12;order:12}.offset-md-0{margin-left:0}.offset-md-1{margin-left:8.3333333333%}.offset-md-2{margin-left:16.6666666667%}.offset-md-3{margin-left:25%}.offset-md-4{margin-left:33.3333333333%}.offset-md-5{margin-left:41.6666666667%}.offset-md-6{margin-left:50%}.offset-md-7{margin-left:58.3333333333%}.offset-md-8{margin-left:66.6666666667%}.offset-md-9{margin-left:75%}.offset-md-10{margin-left:83.3333333333%}.offset-md-11{margin-left:91.6666666667%}}@media (min-width: 992px){.col-lg{-ms-flex-preferred-size:0;flex-basis:0;-webkit-box-flex:1;-ms-flex-positive:1;flex-grow:1;max-width:100%}.col-lg-auto{-webkit-box-flex:0;-ms-flex:0 0 auto;flex:0 0 auto;width:auto;max-width:none}.col-lg-1{-webkit-box-flex:0;-ms-flex:0 0 8.3333333333%;flex:0 0 8.3333333333%;max-width:8.3333333333%}.col-lg-2{-webkit-box-flex:0;-ms-flex:0 0 16.6666666667%;flex:0 0 16.6666666667%;max-width:16.6666666667%}.col-lg-3{-webkit-box-flex:0;-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.col-lg-4{-webkit-box-flex:0;-ms-flex:0 0 33.3333333333%;flex:0 0 33.3333333333%;max-width:33.3333333333%}.col-lg-5{-webkit-box-flex:0;-ms-flex:0 0 41.6666666667%;flex:0 0 41.6666666667%;max-width:41.6666666667%}.col-lg-6{-webkit-box-flex:0;-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.col-lg-7{-webkit-box-flex:0;-ms-flex:0 0 58.3333333333%;flex:0 0 58.3333333333%;max-width:58.3333333333%}.col-lg-8{-webkit-box-flex:0;-ms-flex:0 0 66.6666666667%;flex:0 0 66.6666666667%;max-width:66.6666666667%}.col-lg-9{-webkit-box-flex:0;-ms-flex:0 0 75%;flex:0 0 75%;max-width:75%}.col-lg-10{-webkit-box-flex:0;-ms-flex:0 0 83.3333333333%;flex:0 0 83.3333333333%;max-width:83.3333333333%}.col-lg-11{-webkit-box-flex:0;-ms-flex:0 0 91.6666666667%;flex:0 0 91.6666666667%;max-width:91.6666666667%}.col-lg-12{-webkit-box-flex:0;-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.order-lg-first{-webkit-box-ordinal-group:0;-ms-flex-order:-1;order:-1}.order-lg-last{-webkit-box-ordinal-group:14;-ms-flex-order:13;order:13}.order-lg-0{-webkit-box-ordinal-group:1;-ms-flex-order:0;order:0}.order-lg-1{-webkit-box-ordinal-group:2;-ms-flex-order:1;order:1}.order-lg-2{-webkit-box-ordinal-group:3;-ms-flex-order:2;order:2}.order-lg-3{-webkit-box-ordinal-group:4;-ms-flex-order:3;order:3}.order-lg-4{-webkit-box-ordinal-group:5;-ms-flex-order:4;order:4}.order-lg-5{-webkit-box-ordinal-group:6;-ms-flex-order:5;order:5}.order-lg-6{-webkit-box-ordinal-group:7;-ms-flex-order:6;order:6}.order-lg-7{-webkit-box-ordinal-group:8;-ms-flex-order:7;order:7}.order-lg-8{-webkit-box-ordinal-group:9;-ms-flex-order:8;order:8}.order-lg-9{-webkit-box-ordinal-group:10;-ms-flex-order:9;order:9}.order-lg-10{-webkit-box-ordinal-group:11;-ms-flex-order:10;order:10}.order-lg-11{-webkit-box-ordinal-group:12;-ms-flex-order:11;order:11}.order-lg-12{-webkit-box-ordinal-group:13;-ms-flex-order:12;order:12}.offset-lg-0{margin-left:0}.offset-lg-1{margin-left:8.3333333333%}.offset-lg-2{margin-left:16.6666666667%}.offset-lg-3{margin-left:25%}.offset-lg-4{margin-left:33.3333333333%}.offset-lg-5{margin-left:41.6666666667%}.offset-lg-6{margin-left:50%}.offset-lg-7{margin-left:58.3333333333%}.offset-lg-8{margin-left:66.6666666667%}.offset-lg-9{margin-left:75%}.offset-lg-10{margin-left:83.3333333333%}.offset-lg-11{margin-left:91.6666666667%}}@media (min-width: 1200px){.col-xl{-ms-flex-preferred-size:0;flex-basis:0;-webkit-box-flex:1;-ms-flex-positive:1;flex-grow:1;max-width:100%}.col-xl-auto{-webkit-box-flex:0;-ms-flex:0 0 auto;flex:0 0 auto;width:auto;max-width:none}.col-xl-1{-webkit-box-flex:0;-ms-flex:0 0 8.3333333333%;flex:0 0 8.3333333333%;max-width:8.3333333333%}.col-xl-2{-webkit-box-flex:0;-ms-flex:0 0 16.6666666667%;flex:0 0 16.6666666667%;max-width:16.6666666667%}.col-xl-3{-webkit-box-flex:0;-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.col-xl-4{-webkit-box-flex:0;-ms-flex:0 0 33.3333333333%;flex:0 0 33.3333333333%;max-width:33.3333333333%}.col-xl-5{-webkit-box-flex:0;-ms-flex:0 0 41.6666666667%;flex:0 0 41.6666666667%;max-width:41.6666666667%}.col-xl-6{-webkit-box-flex:0;-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.col-xl-7{-webkit-box-flex:0;-ms-flex:0 0 58.3333333333%;flex:0 0 58.3333333333%;max-width:58.3333333333%}.col-xl-8{-webkit-box-flex:0;-ms-flex:0 0 66.6666666667%;flex:0 0 66.6666666667%;max-width:66.6666666667%}.col-xl-9{-webkit-box-flex:0;-ms-flex:0 0 75%;flex:0 0 75%;max-width:75%}.col-xl-10{-webkit-box-flex:0;-ms-flex:0 0 83.3333333333%;flex:0 0 83.3333333333%;max-width:83.3333333333%}.col-xl-11{-webkit-box-flex:0;-ms-flex:0 0 91.6666666667%;flex:0 0 91.6666666667%;max-width:91.6666666667%}.col-xl-12{-webkit-box-flex:0;-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.order-xl-first{-webkit-box-ordinal-group:0;-ms-flex-order:-1;order:-1}.order-xl-last{-webkit-box-ordinal-group:14;-ms-flex-order:13;order:13}.order-xl-0{-webkit-box-ordinal-group:1;-ms-flex-order:0;order:0}.order-xl-1{-webkit-box-ordinal-group:2;-ms-flex-order:1;order:1}.order-xl-2{-webkit-box-ordinal-group:3;-ms-flex-order:2;order:2}.order-xl-3{-webkit-box-ordinal-group:4;-ms-flex-order:3;order:3}.order-xl-4{-webkit-box-ordinal-group:5;-ms-flex-order:4;order:4}.order-xl-5{-webkit-box-ordinal-group:6;-ms-flex-order:5;order:5}.order-xl-6{-webkit-box-ordinal-group:7;-ms-flex-order:6;order:6}.order-xl-7{-webkit-box-ordinal-group:8;-ms-flex-order:7;order:7}.order-xl-8{-webkit-box-ordinal-group:9;-ms-flex-order:8;order:8}.order-xl-9{-webkit-box-ordinal-group:10;-ms-flex-order:9;order:9}.order-xl-10{-webkit-box-ordinal-group:11;-ms-flex-order:10;order:10}.order-xl-11{-webkit-box-ordinal-group:12;-ms-flex-order:11;order:11}.order-xl-12{-webkit-box-ordinal-group:13;-ms-flex-order:12;order:12}.offset-xl-0{margin-left:0}.offset-xl-1{margin-left:8.3333333333%}.offset-xl-2{margin-left:16.6666666667%}.offset-xl-3{margin-left:25%}.offset-xl-4{margin-left:33.3333333333%}.offset-xl-5{margin-left:41.6666666667%}.offset-xl-6{margin-left:50%}.offset-xl-7{margin-left:58.3333333333%}.offset-xl-8{margin-left:66.6666666667%}.offset-xl-9{margin-left:75%}.offset-xl-10{margin-left:83.3333333333%}.offset-xl-11{margin-left:91.6666666667%}}.table{width:100%;margin-bottom:1rem;background-color:transparent}.table th,.table td{padding:0.75rem;vertical-align:top;border-top:1px solid #dee2e6}.table thead th{vertical-align:bottom;border-bottom:2px solid #dee2e6}.table tbody+tbody{border-top:2px solid #dee2e6}.table .table{background-color:#fff}.table-sm th,.table-sm td{padding:0.3rem}.table-bordered{border:1px solid #dee2e6}.table-bordered th,.table-bordered td{border:1px solid #dee2e6}.table-bordered thead th,.table-bordered thead td{border-bottom-width:2px}.table-borderless th,.table-borderless td,.table-borderless thead th,.table-borderless tbody+tbody{border:0}.table-striped tbody tr:nth-of-type(odd){background-color:rgba(0,0,0,0.05)}.table-hover tbody tr:hover{background-color:rgba(0,0,0,0.075)}.table-primary,.table-primary>th,.table-primary>td{background-color:#c5e6f8}.table-hover .table-primary:hover{background-color:#aedcf5}.table-hover .table-primary:hover>td,.table-hover .table-primary:hover>th{background-color:#aedcf5}.table-secondary,.table-secondary>th,.table-secondary>td{background-color:#f9fafb}.table-hover .table-secondary:hover{background-color:#eaedf1}.table-hover .table-secondary:hover>td,.table-hover .table-secondary:hover>th{background-color:#eaedf1}.table-success,.table-success>th,.table-success>td{background-color:#d8e7c8}.table-hover .table-success:hover{background-color:#cbdfb6}.table-hover .table-success:hover>td,.table-hover .table-success:hover>th{background-color:#cbdfb6}.table-info,.table-info>th,.table-info>td{background-color:#b8c8d8}.table-hover .table-info:hover{background-color:#a8bbcf}.table-hover .table-info:hover>td,.table-hover .table-info:hover>th{background-color:#a8bbcf}.table-warning,.table-warning>th,.table-warning>td{background-color:#f5d0b8}.table-hover .table-warning:hover{background-color:#f2c1a2}.table-hover .table-warning:hover>td,.table-hover .table-warning:hover>th{background-color:#f2c1a2}.table-danger,.table-danger>th,.table-danger>td{background-color:#efbfc1}.table-hover .table-danger:hover{background-color:#eaabad}.table-hover .table-danger:hover>td,.table-hover .table-danger:hover>th{background-color:#eaabad}.table-light,.table-light>th,.table-light>td{background-color:#fdfdfe}.table-hover .table-light:hover{background-color:#ececf6}.table-hover .table-light:hover>td,.table-hover .table-light:hover>th{background-color:#ececf6}.table-dark,.table-dark>th,.table-dark>td{background-color:#c6c8ca}.table-hover .table-dark:hover{background-color:#b9bbbe}.table-hover .table-dark:hover>td,.table-hover .table-dark:hover>th{background-color:#b9bbbe}.table-active,.table-active>th,.table-active>td{background-color:rgba(0,0,0,0.075)}.table-hover .table-active:hover{background-color:rgba(0,0,0,0.075)}.table-hover .table-active:hover>td,.table-hover .table-active:hover>th{background-color:rgba(0,0,0,0.075)}.table .thead-dark th{color:#fff;background-color:#212529;border-color:#32383e}.table .thead-light th{color:#495057;background-color:#e9ecef;border-color:#dee2e6}.table-dark{color:#fff;background-color:#212529}.table-dark th,.table-dark td,.table-dark thead th{border-color:#32383e}.table-dark.table-bordered{border:0}.table-dark.table-striped tbody tr:nth-of-type(odd){background-color:rgba(255,255,255,0.05)}.table-dark.table-hover tbody tr:hover{background-color:rgba(255,255,255,0.075)}@media (max-width: 575.98px){.table-responsive-sm{display:block;width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch;-ms-overflow-style:-ms-autohiding-scrollbar}.table-responsive-sm>.table-bordered{border:0}}@media (max-width: 767.98px){.table-responsive-md{display:block;width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch;-ms-overflow-style:-ms-autohiding-scrollbar}.table-responsive-md>.table-bordered{border:0}}@media (max-width: 991.98px){.table-responsive-lg{display:block;width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch;-ms-overflow-style:-ms-autohiding-scrollbar}.table-responsive-lg>.table-bordered{border:0}}@media (max-width: 1199.98px){.table-responsive-xl{display:block;width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch;-ms-overflow-style:-ms-autohiding-scrollbar}.table-responsive-xl>.table-bordered{border:0}}.table-responsive{display:block;width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch;-ms-overflow-style:-ms-autohiding-scrollbar}.table-responsive>.table-bordered{border:0}.form-control{display:block;width:100%;height:calc(2.25rem + 2px);padding:0.375rem 0.75rem;font-size:1rem;line-height:1.5;color:#495057;background-color:#fff;background-clip:padding-box;border:1px solid #ced4da;border-radius:0.25rem;-webkit-transition:border-color 0.15s ease-in-out, -webkit-box-shadow 0.15s ease-in-out;transition:border-color 0.15s ease-in-out, -webkit-box-shadow 0.15s ease-in-out;transition:border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;transition:border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out, -webkit-box-shadow 0.15s ease-in-out}@media screen and (prefers-reduced-motion: reduce){.form-control{-webkit-transition:none;transition:none}}.form-control::-ms-expand{background-color:transparent;border:0}.form-control:focus{color:#495057;background-color:#fff;border-color:#a1d6f4;outline:0;-webkit-box-shadow:0 0 0 0.2rem rgba(47,164,231,0.25);box-shadow:0 0 0 0.2rem rgba(47,164,231,0.25)}.form-control::-webkit-input-placeholder{color:#868e96;opacity:1}.form-control:-ms-input-placeholder{color:#868e96;opacity:1}.form-control::-ms-input-placeholder{color:#868e96;opacity:1}.form-control::placeholder{color:#868e96;opacity:1}.form-control:disabled,.form-control[readonly]{background-color:#e9ecef;opacity:1}select.form-control:focus::-ms-value{color:#495057;background-color:#fff}.form-control-file,.form-control-range{display:block;width:100%}.col-form-label{padding-top:calc(0.375rem + 1px);padding-bottom:calc(0.375rem + 1px);margin-bottom:0;font-size:inherit;line-height:1.5}.col-form-label-lg{padding-top:calc(0.5rem + 1px);padding-bottom:calc(0.5rem + 1px);font-size:1.25rem;line-height:1.5}.col-form-label-sm{padding-top:calc(0.25rem + 1px);padding-bottom:calc(0.25rem + 1px);font-size:0.875rem;line-height:1.5}.form-control-plaintext{display:block;width:100%;padding-top:0.375rem;padding-bottom:0.375rem;margin-bottom:0;line-height:1.5;color:#495057;background-color:transparent;border:solid transparent;border-width:1px 0}.form-control-plaintext.form-control-sm,.form-control-plaintext.form-control-lg{padding-right:0;padding-left:0}.form-control-sm{height:calc(1.8125rem + 2px);padding:0.25rem 0.5rem;font-size:0.875rem;line-height:1.5;border-radius:0.2rem}.form-control-lg{height:calc(2.875rem + 2px);padding:0.5rem 1rem;font-size:1.25rem;line-height:1.5;border-radius:0.3rem}select.form-control[size],select.form-control[multiple]{height:auto}textarea.form-control{height:auto}.form-group{margin-bottom:1rem}.form-text{display:block;margin-top:0.25rem}.form-row{display:-webkit-box;display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;margin-right:-5px;margin-left:-5px}.form-row>.col,.form-row>[class*="col-"]{padding-right:5px;padding-left:5px}.form-check{position:relative;display:block;padding-left:1.25rem}.form-check-input{position:absolute;margin-top:0.3rem;margin-left:-1.25rem}.form-check-input:disabled ~ .form-check-label{color:#868e96}.form-check-label{margin-bottom:0}.form-check-inline{display:-webkit-inline-box;display:-ms-inline-flexbox;display:inline-flex;-webkit-box-align:center;-ms-flex-align:center;align-items:center;padding-left:0;margin-right:0.75rem}.form-check-inline .form-check-input{position:static;margin-top:0;margin-right:0.3125rem;margin-left:0}.valid-feedback{display:none;width:100%;margin-top:0.25rem;font-size:80%;color:#73A839}.valid-tooltip{position:absolute;top:100%;z-index:5;display:none;max-width:100%;padding:0.25rem 0.5rem;margin-top:.1rem;font-size:0.875rem;line-height:1.5;color:#fff;background-color:rgba(115,168,57,0.9);border-radius:0.25rem}.was-validated .form-control:valid,.form-control.is-valid,.was-validated .custom-select:valid,.custom-select.is-valid{border-color:#73A839}.was-validated .form-control:valid:focus,.form-control.is-valid:focus,.was-validated .custom-select:valid:focus,.custom-select.is-valid:focus{border-color:#73A839;-webkit-box-shadow:0 0 0 0.2rem rgba(115,168,57,0.25);box-shadow:0 0 0 0.2rem rgba(115,168,57,0.25)}.was-validated .form-control:valid ~ .valid-feedback,.was-validated .form-control:valid ~ .valid-tooltip,.form-control.is-valid ~ .valid-feedback,.form-control.is-valid ~ .valid-tooltip,.was-validated .custom-select:valid ~ .valid-feedback,.was-validated .custom-select:valid ~ .valid-tooltip,.custom-select.is-valid ~ .valid-feedback,.custom-select.is-valid ~ .valid-tooltip{display:block}.was-validated .form-control-file:valid ~ .valid-feedback,.was-validated .form-control-file:valid ~ .valid-tooltip,.form-control-file.is-valid ~ .valid-feedback,.form-control-file.is-valid ~ .valid-tooltip{display:block}.was-validated .form-check-input:valid ~ .form-check-label,.form-check-input.is-valid ~ .form-check-label{color:#73A839}.was-validated .form-check-input:valid ~ .valid-feedback,.was-validated .form-check-input:valid ~ .valid-tooltip,.form-check-input.is-valid ~ .valid-feedback,.form-check-input.is-valid ~ .valid-tooltip{display:block}.was-validated .custom-control-input:valid ~ .custom-control-label,.custom-control-input.is-valid ~ .custom-control-label{color:#73A839}.was-validated .custom-control-input:valid ~ .custom-control-label::before,.custom-control-input.is-valid ~ .custom-control-label::before{background-color:#b2d789}.was-validated .custom-control-input:valid ~ .valid-feedback,.was-validated .custom-control-input:valid ~ .valid-tooltip,.custom-control-input.is-valid ~ .valid-feedback,.custom-control-input.is-valid ~ .valid-tooltip{display:block}.was-validated .custom-control-input:valid:checked ~ .custom-control-label::before,.custom-control-input.is-valid:checked ~ .custom-control-label::before{background-color:#8dc450}.was-validated .custom-control-input:valid:focus ~ .custom-control-label::before,.custom-control-input.is-valid:focus ~ .custom-control-label::before{-webkit-box-shadow:0 0 0 1px #fff,0 0 0 0.2rem rgba(115,168,57,0.25);box-shadow:0 0 0 1px #fff,0 0 0 0.2rem rgba(115,168,57,0.25)}.was-validated .custom-file-input:valid ~ .custom-file-label,.custom-file-input.is-valid ~ .custom-file-label{border-color:#73A839}.was-validated .custom-file-input:valid ~ .custom-file-label::after,.custom-file-input.is-valid ~ .custom-file-label::after{border-color:inherit}.was-validated .custom-file-input:valid ~ .valid-feedback,.was-validated .custom-file-input:valid ~ .valid-tooltip,.custom-file-input.is-valid ~ .valid-feedback,.custom-file-input.is-valid ~ .valid-tooltip{display:block}.was-validated .custom-file-input:valid:focus ~ .custom-file-label,.custom-file-input.is-valid:focus ~ .custom-file-label{-webkit-box-shadow:0 0 0 0.2rem rgba(115,168,57,0.25);box-shadow:0 0 0 0.2rem rgba(115,168,57,0.25)}.invalid-feedback{display:none;width:100%;margin-top:0.25rem;font-size:80%;color:#C71C22}.invalid-tooltip{position:absolute;top:100%;z-index:5;display:none;max-width:100%;padding:0.25rem 0.5rem;margin-top:.1rem;font-size:0.875rem;line-height:1.5;color:#fff;background-color:rgba(199,28,34,0.9);border-radius:0.25rem}.was-validated .form-control:invalid,.form-control.is-invalid,.was-validated .custom-select:invalid,.custom-select.is-invalid{border-color:#C71C22}.was-validated .form-control:invalid:focus,.form-control.is-invalid:focus,.was-validated .custom-select:invalid:focus,.custom-select.is-invalid:focus{border-color:#C71C22;-webkit-box-shadow:0 0 0 0.2rem rgba(199,28,34,0.25);box-shadow:0 0 0 0.2rem rgba(199,28,34,0.25)}.was-validated .form-control:invalid ~ .invalid-feedback,.was-validated .form-control:invalid ~ .invalid-tooltip,.form-control.is-invalid ~ .invalid-feedback,.form-control.is-invalid ~ .invalid-tooltip,.was-validated .custom-select:invalid ~ .invalid-feedback,.was-validated .custom-select:invalid ~ .invalid-tooltip,.custom-select.is-invalid ~ .invalid-feedback,.custom-select.is-invalid ~ .invalid-tooltip{display:block}.was-validated .form-control-file:invalid ~ .invalid-feedback,.was-validated .form-control-file:invalid ~ .invalid-tooltip,.form-control-file.is-invalid ~ .invalid-feedback,.form-control-file.is-invalid ~ .invalid-tooltip{display:block}.was-validated .form-check-input:invalid ~ .form-check-label,.form-check-input.is-invalid ~ .form-check-label{color:#C71C22}.was-validated .form-check-input:invalid ~ .invalid-feedback,.was-validated .form-check-input:invalid ~ .invalid-tooltip,.form-check-input.is-invalid ~ .invalid-feedback,.form-check-input.is-invalid ~ .invalid-tooltip{display:block}.was-validated .custom-control-input:invalid ~ .custom-control-label,.custom-control-input.is-invalid ~ .custom-control-label{color:#C71C22}.was-validated .custom-control-input:invalid ~ .custom-control-label::before,.custom-control-input.is-invalid ~ .custom-control-label::before{background-color:#ec777b}.was-validated .custom-control-input:invalid ~ .invalid-feedback,.was-validated .custom-control-input:invalid ~ .invalid-tooltip,.custom-control-input.is-invalid ~ .invalid-feedback,.custom-control-input.is-invalid ~ .invalid-tooltip{display:block}.was-validated .custom-control-input:invalid:checked ~ .custom-control-label::before,.custom-control-input.is-invalid:checked ~ .custom-control-label::before{background-color:#e2343a}.was-validated .custom-control-input:invalid:focus ~ .custom-control-label::before,.custom-control-input.is-invalid:focus ~ .custom-control-label::before{-webkit-box-shadow:0 0 0 1px #fff,0 0 0 0.2rem rgba(199,28,34,0.25);box-shadow:0 0 0 1px #fff,0 0 0 0.2rem rgba(199,28,34,0.25)}.was-validated .custom-file-input:invalid ~ .custom-file-label,.custom-file-input.is-invalid ~ .custom-file-label{border-color:#C71C22}.was-validated .custom-file-input:invalid ~ .custom-file-label::after,.custom-file-input.is-invalid ~ .custom-file-label::after{border-color:inherit}.was-validated .custom-file-input:invalid ~ .invalid-feedback,.was-validated .custom-file-input:invalid ~ .invalid-tooltip,.custom-file-input.is-invalid ~ .invalid-feedback,.custom-file-input.is-invalid ~ .invalid-tooltip{display:block}.was-validated .custom-file-input:invalid:focus ~ .custom-file-label,.custom-file-input.is-invalid:focus ~ .custom-file-label{-webkit-box-shadow:0 0 0 0.2rem rgba(199,28,34,0.25);box-shadow:0 0 0 0.2rem rgba(199,28,34,0.25)}.form-inline{display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-orient:horizontal;-webkit-box-direction:normal;-ms-flex-flow:row wrap;flex-flow:row wrap;-webkit-box-align:center;-ms-flex-align:center;align-items:center}.form-inline .form-check{width:100%}@media (min-width: 576px){.form-inline label{display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-align:center;-ms-flex-align:center;align-items:center;-webkit-box-pack:center;-ms-flex-pack:center;justify-content:center;margin-bottom:0}.form-inline .form-group{display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-flex:0;-ms-flex:0 0 auto;flex:0 0 auto;-webkit-box-orient:horizontal;-webkit-box-direction:normal;-ms-flex-flow:row wrap;flex-flow:row wrap;-webkit-box-align:center;-ms-flex-align:center;align-items:center;margin-bottom:0}.form-inline .form-control{display:inline-block;width:auto;vertical-align:middle}.form-inline .form-control-plaintext{display:inline-block}.form-inline .input-group,.form-inline .custom-select{width:auto}.form-inline .form-check{display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-align:center;-ms-flex-align:center;align-items:center;-webkit-box-pack:center;-ms-flex-pack:center;justify-content:center;width:auto;padding-left:0}.form-inline .form-check-input{position:relative;margin-top:0;margin-right:0.25rem;margin-left:0}.form-inline .custom-control{-webkit-box-align:center;-ms-flex-align:center;align-items:center;-webkit-box-pack:center;-ms-flex-pack:center;justify-content:center}.form-inline .custom-control-label{margin-bottom:0}}.btn{display:inline-block;font-weight:400;text-align:center;white-space:nowrap;vertical-align:middle;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;border:1px solid transparent;padding:0.375rem 0.75rem;font-size:1rem;line-height:1.5;border-radius:0.25rem;-webkit-transition:color 0.15s ease-in-out, background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, -webkit-box-shadow 0.15s ease-in-out;transition:color 0.15s ease-in-out, background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, -webkit-box-shadow 0.15s ease-in-out;transition:color 0.15s ease-in-out, background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;transition:color 0.15s ease-in-out, background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out, -webkit-box-shadow 0.15s ease-in-out}@media screen and (prefers-reduced-motion: reduce){.btn{-webkit-transition:none;transition:none}}.btn:hover,.btn:focus{text-decoration:none}.btn:focus,.btn.focus{outline:0;-webkit-box-shadow:0 0 0 0.2rem rgba(47,164,231,0.25);box-shadow:0 0 0 0.2rem rgba(47,164,231,0.25)}.btn.disabled,.btn:disabled{opacity:0.65}.btn:not(:disabled):not(.disabled){cursor:pointer}a.btn.disabled,fieldset:disabled a.btn{pointer-events:none}.btn-primary{color:#fff;background-color:#2FA4E7;border-color:#2FA4E7}.btn-primary:hover{color:#fff;background-color:#1992d7;border-color:#178acc}.btn-primary:focus,.btn-primary.focus{-webkit-box-shadow:0 0 0 0.2rem rgba(47,164,231,0.5);box-shadow:0 0 0 0.2rem rgba(47,164,231,0.5)}.btn-primary.disabled,.btn-primary:disabled{color:#fff;background-color:#2FA4E7;border-color:#2FA4E7}.btn-primary:not(:disabled):not(.disabled):active,.btn-primary:not(:disabled):not(.disabled).active,.show>.btn-primary.dropdown-toggle{color:#fff;background-color:#178acc;border-color:#1682c0}.btn-primary:not(:disabled):not(.disabled):active:focus,.btn-primary:not(:disabled):not(.disabled).active:focus,.show>.btn-primary.dropdown-toggle:focus{-webkit-box-shadow:0 0 0 0.2rem rgba(47,164,231,0.5);box-shadow:0 0 0 0.2rem rgba(47,164,231,0.5)}.btn-secondary{color:#212529;background-color:#e9ecef;border-color:#e9ecef}.btn-secondary:hover{color:#212529;background-color:#d3d9df;border-color:#cbd3da}.btn-secondary:focus,.btn-secondary.focus{-webkit-box-shadow:0 0 0 0.2rem rgba(233,236,239,0.5);box-shadow:0 0 0 0.2rem rgba(233,236,239,0.5)}.btn-secondary.disabled,.btn-secondary:disabled{color:#212529;background-color:#e9ecef;border-color:#e9ecef}.btn-secondary:not(:disabled):not(.disabled):active,.btn-secondary:not(:disabled):not(.disabled).active,.show>.btn-secondary.dropdown-toggle{color:#212529;background-color:#cbd3da;border-color:#c4ccd4}.btn-secondary:not(:disabled):not(.disabled):active:focus,.btn-secondary:not(:disabled):not(.disabled).active:focus,.show>.btn-secondary.dropdown-toggle:focus{-webkit-box-shadow:0 0 0 0.2rem rgba(233,236,239,0.5);box-shadow:0 0 0 0.2rem rgba(233,236,239,0.5)}.btn-success{color:#fff;background-color:#73A839;border-color:#73A839}.btn-success:hover{color:#fff;background-color:#5f8b2f;border-color:#59822c}.btn-success:focus,.btn-success.focus{-webkit-box-shadow:0 0 0 0.2rem rgba(115,168,57,0.5);box-shadow:0 0 0 0.2rem rgba(115,168,57,0.5)}.btn-success.disabled,.btn-success:disabled{color:#fff;background-color:#73A839;border-color:#73A839}.btn-success:not(:disabled):not(.disabled):active,.btn-success:not(:disabled):not(.disabled).active,.show>.btn-success.dropdown-toggle{color:#fff;background-color:#59822c;border-color:#527829}.btn-success:not(:disabled):not(.disabled):active:focus,.btn-success:not(:disabled):not(.disabled).active:focus,.show>.btn-success.dropdown-toggle:focus{-webkit-box-shadow:0 0 0 0.2rem rgba(115,168,57,0.5);box-shadow:0 0 0 0.2rem rgba(115,168,57,0.5)}.btn-info{color:#fff;background-color:#033C73;border-color:#033C73}.btn-info:hover{color:#fff;background-color:#02294e;border-color:#022241}.btn-info:focus,.btn-info.focus{-webkit-box-shadow:0 0 0 0.2rem rgba(3,60,115,0.5);box-shadow:0 0 0 0.2rem rgba(3,60,115,0.5)}.btn-info.disabled,.btn-info:disabled{color:#fff;background-color:#033C73;border-color:#033C73}.btn-info:not(:disabled):not(.disabled):active,.btn-info:not(:disabled):not(.disabled).active,.show>.btn-info.dropdown-toggle{color:#fff;background-color:#022241;border-color:#011c35}.btn-info:not(:disabled):not(.disabled):active:focus,.btn-info:not(:disabled):not(.disabled).active:focus,.show>.btn-info.dropdown-toggle:focus{-webkit-box-shadow:0 0 0 0.2rem rgba(3,60,115,0.5);box-shadow:0 0 0 0.2rem rgba(3,60,115,0.5)}.btn-warning{color:#fff;background-color:#DD5600;border-color:#DD5600}.btn-warning:hover{color:#fff;background-color:#b74700;border-color:#aa4200}.btn-warning:focus,.btn-warning.focus{-webkit-box-shadow:0 0 0 0.2rem rgba(221,86,0,0.5);box-shadow:0 0 0 0.2rem rgba(221,86,0,0.5)}.btn-warning.disabled,.btn-warning:disabled{color:#fff;background-color:#DD5600;border-color:#DD5600}.btn-warning:not(:disabled):not(.disabled):active,.btn-warning:not(:disabled):not(.disabled).active,.show>.btn-warning.dropdown-toggle{color:#fff;background-color:#aa4200;border-color:#9d3d00}.btn-warning:not(:disabled):not(.disabled):active:focus,.btn-warning:not(:disabled):not(.disabled).active:focus,.show>.btn-warning.dropdown-toggle:focus{-webkit-box-shadow:0 0 0 0.2rem rgba(221,86,0,0.5);box-shadow:0 0 0 0.2rem rgba(221,86,0,0.5)}.btn-danger{color:#fff;background-color:#C71C22;border-color:#C71C22}.btn-danger:hover{color:#fff;background-color:#a5171c;border-color:#9a161a}.btn-danger:focus,.btn-danger.focus{-webkit-box-shadow:0 0 0 0.2rem rgba(199,28,34,0.5);box-shadow:0 0 0 0.2rem rgba(199,28,34,0.5)}.btn-danger.disabled,.btn-danger:disabled{color:#fff;background-color:#C71C22;border-color:#C71C22}.btn-danger:not(:disabled):not(.disabled):active,.btn-danger:not(:disabled):not(.disabled).active,.show>.btn-danger.dropdown-toggle{color:#fff;background-color:#9a161a;border-color:#8f1418}.btn-danger:not(:disabled):not(.disabled):active:focus,.btn-danger:not(:disabled):not(.disabled).active:focus,.show>.btn-danger.dropdown-toggle:focus{-webkit-box-shadow:0 0 0 0.2rem rgba(199,28,34,0.5);box-shadow:0 0 0 0.2rem rgba(199,28,34,0.5)}.btn-light{color:#212529;background-color:#f8f9fa;border-color:#f8f9fa}.btn-light:hover{color:#212529;background-color:#e2e6ea;border-color:#dae0e5}.btn-light:focus,.btn-light.focus{-webkit-box-shadow:0 0 0 0.2rem rgba(248,249,250,0.5);box-shadow:0 0 0 0.2rem rgba(248,249,250,0.5)}.btn-light.disabled,.btn-light:disabled{color:#212529;background-color:#f8f9fa;border-color:#f8f9fa}.btn-light:not(:disabled):not(.disabled):active,.btn-light:not(:disabled):not(.disabled).active,.show>.btn-light.dropdown-toggle{color:#212529;background-color:#dae0e5;border-color:#d3d9df}.btn-light:not(:disabled):not(.disabled):active:focus,.btn-light:not(:disabled):not(.disabled).active:focus,.show>.btn-light.dropdown-toggle:focus{-webkit-box-shadow:0 0 0 0.2rem rgba(248,249,250,0.5);box-shadow:0 0 0 0.2rem rgba(248,249,250,0.5)}.btn-dark{color:#fff;background-color:#343a40;border-color:#343a40}.btn-dark:hover{color:#fff;background-color:#23272b;border-color:#1d2124}.btn-dark:focus,.btn-dark.focus{-webkit-box-shadow:0 0 0 0.2rem rgba(52,58,64,0.5);box-shadow:0 0 0 0.2rem rgba(52,58,64,0.5)}.btn-dark.disabled,.btn-dark:disabled{color:#fff;background-color:#343a40;border-color:#343a40}.btn-dark:not(:disabled):not(.disabled):active,.btn-dark:not(:disabled):not(.disabled).active,.show>.btn-dark.dropdown-toggle{color:#fff;background-color:#1d2124;border-color:#171a1d}.btn-dark:not(:disabled):not(.disabled):active:focus,.btn-dark:not(:disabled):not(.disabled).active:focus,.show>.btn-dark.dropdown-toggle:focus{-webkit-box-shadow:0 0 0 0.2rem rgba(52,58,64,0.5);box-shadow:0 0 0 0.2rem rgba(52,58,64,0.5)}.btn-outline-primary{color:#2FA4E7;background-color:transparent;background-image:none;border-color:#2FA4E7}.btn-outline-primary:hover{color:#fff;background-color:#2FA4E7;border-color:#2FA4E7}.btn-outline-primary:focus,.btn-outline-primary.focus{-webkit-box-shadow:0 0 0 0.2rem rgba(47,164,231,0.5);box-shadow:0 0 0 0.2rem rgba(47,164,231,0.5)}.btn-outline-primary.disabled,.btn-outline-primary:disabled{color:#2FA4E7;background-color:transparent}.btn-outline-primary:not(:disabled):not(.disabled):active,.btn-outline-primary:not(:disabled):not(.disabled).active,.show>.btn-outline-primary.dropdown-toggle{color:#fff;background-color:#2FA4E7;border-color:#2FA4E7}.btn-outline-primary:not(:disabled):not(.disabled):active:focus,.btn-outline-primary:not(:disabled):not(.disabled).active:focus,.show>.btn-outline-primary.dropdown-toggle:focus{-webkit-box-shadow:0 0 0 0.2rem rgba(47,164,231,0.5);box-shadow:0 0 0 0.2rem rgba(47,164,231,0.5)}.btn-outline-secondary{color:#e9ecef;background-color:transparent;background-image:none;border-color:#e9ecef}.btn-outline-secondary:hover{color:#212529;background-color:#e9ecef;border-color:#e9ecef}.btn-outline-secondary:focus,.btn-outline-secondary.focus{-webkit-box-shadow:0 0 0 0.2rem rgba(233,236,239,0.5);box-shadow:0 0 0 0.2rem rgba(233,236,239,0.5)}.btn-outline-secondary.disabled,.btn-outline-secondary:disabled{color:#e9ecef;background-color:transparent}.btn-outline-secondary:not(:disabled):not(.disabled):active,.btn-outline-secondary:not(:disabled):not(.disabled).active,.show>.btn-outline-secondary.dropdown-toggle{color:#212529;background-color:#e9ecef;border-color:#e9ecef}.btn-outline-secondary:not(:disabled):not(.disabled):active:focus,.btn-outline-secondary:not(:disabled):not(.disabled).active:focus,.show>.btn-outline-secondary.dropdown-toggle:focus{-webkit-box-shadow:0 0 0 0.2rem rgba(233,236,239,0.5);box-shadow:0 0 0 0.2rem rgba(233,236,239,0.5)}.btn-outline-success{color:#73A839;background-color:transparent;background-image:none;border-color:#73A839}.btn-outline-success:hover{color:#fff;background-color:#73A839;border-color:#73A839}.btn-outline-success:focus,.btn-outline-success.focus{-webkit-box-shadow:0 0 0 0.2rem rgba(115,168,57,0.5);box-shadow:0 0 0 0.2rem rgba(115,168,57,0.5)}.btn-outline-success.disabled,.btn-outline-success:disabled{color:#73A839;background-color:transparent}.btn-outline-success:not(:disabled):not(.disabled):active,.btn-outline-success:not(:disabled):not(.disabled).active,.show>.btn-outline-success.dropdown-toggle{color:#fff;background-color:#73A839;border-color:#73A839}.btn-outline-success:not(:disabled):not(.disabled):active:focus,.btn-outline-success:not(:disabled):not(.disabled).active:focus,.show>.btn-outline-success.dropdown-toggle:focus{-webkit-box-shadow:0 0 0 0.2rem rgba(115,168,57,0.5);box-shadow:0 0 0 0.2rem rgba(115,168,57,0.5)}.btn-outline-info{color:#033C73;background-color:transparent;background-image:none;border-color:#033C73}.btn-outline-info:hover{color:#fff;background-color:#033C73;border-color:#033C73}.btn-outline-info:focus,.btn-outline-info.focus{-webkit-box-shadow:0 0 0 0.2rem rgba(3,60,115,0.5);box-shadow:0 0 0 0.2rem rgba(3,60,115,0.5)}.btn-outline-info.disabled,.btn-outline-info:disabled{color:#033C73;background-color:transparent}.btn-outline-info:not(:disabled):not(.disabled):active,.btn-outline-info:not(:disabled):not(.disabled).active,.show>.btn-outline-info.dropdown-toggle{color:#fff;background-color:#033C73;border-color:#033C73}.btn-outline-info:not(:disabled):not(.disabled):active:focus,.btn-outline-info:not(:disabled):not(.disabled).active:focus,.show>.btn-outline-info.dropdown-toggle:focus{-webkit-box-shadow:0 0 0 0.2rem rgba(3,60,115,0.5);box-shadow:0 0 0 0.2rem rgba(3,60,115,0.5)}.btn-outline-warning{color:#DD5600;background-color:transparent;background-image:none;border-color:#DD5600}.btn-outline-warning:hover{color:#fff;background-color:#DD5600;border-color:#DD5600}.btn-outline-warning:focus,.btn-outline-warning.focus{-webkit-box-shadow:0 0 0 0.2rem rgba(221,86,0,0.5);box-shadow:0 0 0 0.2rem rgba(221,86,0,0.5)}.btn-outline-warning.disabled,.btn-outline-warning:disabled{color:#DD5600;background-color:transparent}.btn-outline-warning:not(:disabled):not(.disabled):active,.btn-outline-warning:not(:disabled):not(.disabled).active,.show>.btn-outline-warning.dropdown-toggle{color:#fff;background-color:#DD5600;border-color:#DD5600}.btn-outline-warning:not(:disabled):not(.disabled):active:focus,.btn-outline-warning:not(:disabled):not(.disabled).active:focus,.show>.btn-outline-warning.dropdown-toggle:focus{-webkit-box-shadow:0 0 0 0.2rem rgba(221,86,0,0.5);box-shadow:0 0 0 0.2rem rgba(221,86,0,0.5)}.btn-outline-danger{color:#C71C22;background-color:transparent;background-image:none;border-color:#C71C22}.btn-outline-danger:hover{color:#fff;background-color:#C71C22;border-color:#C71C22}.btn-outline-danger:focus,.btn-outline-danger.focus{-webkit-box-shadow:0 0 0 0.2rem rgba(199,28,34,0.5);box-shadow:0 0 0 0.2rem rgba(199,28,34,0.5)}.btn-outline-danger.disabled,.btn-outline-danger:disabled{color:#C71C22;background-color:transparent}.btn-outline-danger:not(:disabled):not(.disabled):active,.btn-outline-danger:not(:disabled):not(.disabled).active,.show>.btn-outline-danger.dropdown-toggle{color:#fff;background-color:#C71C22;border-color:#C71C22}.btn-outline-danger:not(:disabled):not(.disabled):active:focus,.btn-outline-danger:not(:disabled):not(.disabled).active:focus,.show>.btn-outline-danger.dropdown-toggle:focus{-webkit-box-shadow:0 0 0 0.2rem rgba(199,28,34,0.5);box-shadow:0 0 0 0.2rem rgba(199,28,34,0.5)}.btn-outline-light{color:#f8f9fa;background-color:transparent;background-image:none;border-color:#f8f9fa}.btn-outline-light:hover{color:#212529;background-color:#f8f9fa;border-color:#f8f9fa}.btn-outline-light:focus,.btn-outline-light.focus{-webkit-box-shadow:0 0 0 0.2rem rgba(248,249,250,0.5);box-shadow:0 0 0 0.2rem rgba(248,249,250,0.5)}.btn-outline-light.disabled,.btn-outline-light:disabled{color:#f8f9fa;background-color:transparent}.btn-outline-light:not(:disabled):not(.disabled):active,.btn-outline-light:not(:disabled):not(.disabled).active,.show>.btn-outline-light.dropdown-toggle{color:#212529;background-color:#f8f9fa;border-color:#f8f9fa}.btn-outline-light:not(:disabled):not(.disabled):active:focus,.btn-outline-light:not(:disabled):not(.disabled).active:focus,.show>.btn-outline-light.dropdown-toggle:focus{-webkit-box-shadow:0 0 0 0.2rem rgba(248,249,250,0.5);box-shadow:0 0 0 0.2rem rgba(248,249,250,0.5)}.btn-outline-dark{color:#343a40;background-color:transparent;background-image:none;border-color:#343a40}.btn-outline-dark:hover{color:#fff;background-color:#343a40;border-color:#343a40}.btn-outline-dark:focus,.btn-outline-dark.focus{-webkit-box-shadow:0 0 0 0.2rem rgba(52,58,64,0.5);box-shadow:0 0 0 0.2rem rgba(52,58,64,0.5)}.btn-outline-dark.disabled,.btn-outline-dark:disabled{color:#343a40;background-color:transparent}.btn-outline-dark:not(:disabled):not(.disabled):active,.btn-outline-dark:not(:disabled):not(.disabled).active,.show>.btn-outline-dark.dropdown-toggle{color:#fff;background-color:#343a40;border-color:#343a40}.btn-outline-dark:not(:disabled):not(.disabled):active:focus,.btn-outline-dark:not(:disabled):not(.disabled).active:focus,.show>.btn-outline-dark.dropdown-toggle:focus{-webkit-box-shadow:0 0 0 0.2rem rgba(52,58,64,0.5);box-shadow:0 0 0 0.2rem rgba(52,58,64,0.5)}.btn-link{font-weight:400;color:#2FA4E7;background-color:transparent}.btn-link:hover{color:#157ab5;text-decoration:underline;background-color:transparent;border-color:transparent}.btn-link:focus,.btn-link.focus{text-decoration:underline;border-color:transparent;-webkit-box-shadow:none;box-shadow:none}.btn-link:disabled,.btn-link.disabled{color:#868e96;pointer-events:none}.btn-lg,.btn-group-lg>.btn{padding:0.5rem 1rem;font-size:1.25rem;line-height:1.5;border-radius:0.3rem}.btn-sm,.btn-group-sm>.btn{padding:0.25rem 0.5rem;font-size:0.875rem;line-height:1.5;border-radius:0.2rem}.btn-block{display:block;width:100%}.btn-block+.btn-block{margin-top:0.5rem}input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block{width:100%}.fade{-webkit-transition:opacity 0.15s linear;transition:opacity 0.15s linear}@media screen and (prefers-reduced-motion: reduce){.fade{-webkit-transition:none;transition:none}}.fade:not(.show){opacity:0}.collapse:not(.show){display:none}.collapsing{position:relative;height:0;overflow:hidden;-webkit-transition:height 0.35s ease;transition:height 0.35s ease}@media screen and (prefers-reduced-motion: reduce){.collapsing{-webkit-transition:none;transition:none}}.dropup,.dropright,.dropdown,.dropleft{position:relative}.dropdown-toggle::after{display:inline-block;width:0;height:0;margin-left:0.255em;vertical-align:0.255em;content:"";border-top:0.3em solid;border-right:0.3em solid transparent;border-bottom:0;border-left:0.3em solid transparent}.dropdown-toggle:empty::after{margin-left:0}.dropdown-menu{position:absolute;top:100%;left:0;z-index:1000;display:none;float:left;min-width:10rem;padding:0.5rem 0;margin:0.125rem 0 0;font-size:1rem;color:#495057;text-align:left;list-style:none;background-color:#fff;background-clip:padding-box;border:1px solid rgba(0,0,0,0.15);border-radius:0.25rem}.dropdown-menu-right{right:0;left:auto}.dropup .dropdown-menu{top:auto;bottom:100%;margin-top:0;margin-bottom:0.125rem}.dropup .dropdown-toggle::after{display:inline-block;width:0;height:0;margin-left:0.255em;vertical-align:0.255em;content:"";border-top:0;border-right:0.3em solid transparent;border-bottom:0.3em solid;border-left:0.3em solid transparent}.dropup .dropdown-toggle:empty::after{margin-left:0}.dropright .dropdown-menu{top:0;right:auto;left:100%;margin-top:0;margin-left:0.125rem}.dropright .dropdown-toggle::after{display:inline-block;width:0;height:0;margin-left:0.255em;vertical-align:0.255em;content:"";border-top:0.3em solid transparent;border-right:0;border-bottom:0.3em solid transparent;border-left:0.3em solid}.dropright .dropdown-toggle:empty::after{margin-left:0}.dropright .dropdown-toggle::after{vertical-align:0}.dropleft .dropdown-menu{top:0;right:100%;left:auto;margin-top:0;margin-right:0.125rem}.dropleft .dropdown-toggle::after{display:inline-block;width:0;height:0;margin-left:0.255em;vertical-align:0.255em;content:""}.dropleft .dropdown-toggle::after{display:none}.dropleft .dropdown-toggle::before{display:inline-block;width:0;height:0;margin-right:0.255em;vertical-align:0.255em;content:"";border-top:0.3em solid transparent;border-right:0.3em solid;border-bottom:0.3em solid transparent}.dropleft .dropdown-toggle:empty::after{margin-left:0}.dropleft .dropdown-toggle::before{vertical-align:0}.dropdown-menu[x-placement^="top"],.dropdown-menu[x-placement^="right"],.dropdown-menu[x-placement^="bottom"],.dropdown-menu[x-placement^="left"]{right:auto;bottom:auto}.dropdown-divider{height:0;margin:0.5rem 0;overflow:hidden;border-top:1px solid #e9ecef}.dropdown-item{display:block;width:100%;padding:0.25rem 1.5rem;clear:both;font-weight:400;color:#495057;text-align:inherit;white-space:nowrap;background-color:transparent;border:0}.dropdown-item:hover,.dropdown-item:focus{color:#fff;text-decoration:none;background-color:#2FA4E7}.dropdown-item.active,.dropdown-item:active{color:#fff;text-decoration:none;background-color:#2FA4E7}.dropdown-item.disabled,.dropdown-item:disabled{color:#868e96;background-color:transparent}.dropdown-menu.show{display:block}.dropdown-header{display:block;padding:0.5rem 1.5rem;margin-bottom:0;font-size:0.875rem;color:#868e96;white-space:nowrap}.dropdown-item-text{display:block;padding:0.25rem 1.5rem;color:#495057}.btn-group,.btn-group-vertical{position:relative;display:-webkit-inline-box;display:-ms-inline-flexbox;display:inline-flex;vertical-align:middle}.btn-group>.btn,.btn-group-vertical>.btn{position:relative;-webkit-box-flex:0;-ms-flex:0 1 auto;flex:0 1 auto}.btn-group>.btn:hover,.btn-group-vertical>.btn:hover{z-index:1}.btn-group>.btn:focus,.btn-group>.btn:active,.btn-group>.btn.active,.btn-group-vertical>.btn:focus,.btn-group-vertical>.btn:active,.btn-group-vertical>.btn.active{z-index:1}.btn-group .btn+.btn,.btn-group .btn+.btn-group,.btn-group .btn-group+.btn,.btn-group .btn-group+.btn-group,.btn-group-vertical .btn+.btn,.btn-group-vertical .btn+.btn-group,.btn-group-vertical .btn-group+.btn,.btn-group-vertical .btn-group+.btn-group{margin-left:-1px}.btn-toolbar{display:-webkit-box;display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;-webkit-box-pack:start;-ms-flex-pack:start;justify-content:flex-start}.btn-toolbar .input-group{width:auto}.btn-group>.btn:first-child{margin-left:0}.btn-group>.btn:not(:last-child):not(.dropdown-toggle),.btn-group>.btn-group:not(:last-child)>.btn{border-top-right-radius:0;border-bottom-right-radius:0}.btn-group>.btn:not(:first-child),.btn-group>.btn-group:not(:first-child)>.btn{border-top-left-radius:0;border-bottom-left-radius:0}.dropdown-toggle-split{padding-right:0.5625rem;padding-left:0.5625rem}.dropdown-toggle-split::after,.dropup .dropdown-toggle-split::after,.dropright .dropdown-toggle-split::after{margin-left:0}.dropleft .dropdown-toggle-split::before{margin-right:0}.btn-sm+.dropdown-toggle-split,.btn-group-sm>.btn+.dropdown-toggle-split{padding-right:0.375rem;padding-left:0.375rem}.btn-lg+.dropdown-toggle-split,.btn-group-lg>.btn+.dropdown-toggle-split{padding-right:0.75rem;padding-left:0.75rem}.btn-group-vertical{-webkit-box-orient:vertical;-webkit-box-direction:normal;-ms-flex-direction:column;flex-direction:column;-webkit-box-align:start;-ms-flex-align:start;align-items:flex-start;-webkit-box-pack:center;-ms-flex-pack:center;justify-content:center}.btn-group-vertical .btn,.btn-group-vertical .btn-group{width:100%}.btn-group-vertical>.btn+.btn,.btn-group-vertical>.btn+.btn-group,.btn-group-vertical>.btn-group+.btn,.btn-group-vertical>.btn-group+.btn-group{margin-top:-1px;margin-left:0}.btn-group-vertical>.btn:not(:last-child):not(.dropdown-toggle),.btn-group-vertical>.btn-group:not(:last-child)>.btn{border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical>.btn:not(:first-child),.btn-group-vertical>.btn-group:not(:first-child)>.btn{border-top-left-radius:0;border-top-right-radius:0}.btn-group-toggle>.btn,.btn-group-toggle>.btn-group>.btn{margin-bottom:0}.btn-group-toggle>.btn input[type="radio"],.btn-group-toggle>.btn input[type="checkbox"],.btn-group-toggle>.btn-group>.btn input[type="radio"],.btn-group-toggle>.btn-group>.btn input[type="checkbox"]{position:absolute;clip:rect(0, 0, 0, 0);pointer-events:none}.input-group{position:relative;display:-webkit-box;display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;-webkit-box-align:stretch;-ms-flex-align:stretch;align-items:stretch;width:100%}.input-group>.form-control,.input-group>.custom-select,.input-group>.custom-file{position:relative;-webkit-box-flex:1;-ms-flex:1 1 auto;flex:1 1 auto;width:1%;margin-bottom:0}.input-group>.form-control+.form-control,.input-group>.form-control+.custom-select,.input-group>.form-control+.custom-file,.input-group>.custom-select+.form-control,.input-group>.custom-select+.custom-select,.input-group>.custom-select+.custom-file,.input-group>.custom-file+.form-control,.input-group>.custom-file+.custom-select,.input-group>.custom-file+.custom-file{margin-left:-1px}.input-group>.form-control:focus,.input-group>.custom-select:focus,.input-group>.custom-file .custom-file-input:focus ~ .custom-file-label{z-index:3}.input-group>.custom-file .custom-file-input:focus{z-index:4}.input-group>.form-control:not(:last-child),.input-group>.custom-select:not(:last-child){border-top-right-radius:0;border-bottom-right-radius:0}.input-group>.form-control:not(:first-child),.input-group>.custom-select:not(:first-child){border-top-left-radius:0;border-bottom-left-radius:0}.input-group>.custom-file{display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-align:center;-ms-flex-align:center;align-items:center}.input-group>.custom-file:not(:last-child) .custom-file-label,.input-group>.custom-file:not(:last-child) .custom-file-label::after{border-top-right-radius:0;border-bottom-right-radius:0}.input-group>.custom-file:not(:first-child) .custom-file-label{border-top-left-radius:0;border-bottom-left-radius:0}.input-group-prepend,.input-group-append{display:-webkit-box;display:-ms-flexbox;display:flex}.input-group-prepend .btn,.input-group-append .btn{position:relative;z-index:2}.input-group-prepend .btn+.btn,.input-group-prepend .btn+.input-group-text,.input-group-prepend .input-group-text+.input-group-text,.input-group-prepend .input-group-text+.btn,.input-group-append .btn+.btn,.input-group-append .btn+.input-group-text,.input-group-append .input-group-text+.input-group-text,.input-group-append .input-group-text+.btn{margin-left:-1px}.input-group-prepend{margin-right:-1px}.input-group-append{margin-left:-1px}.input-group-text{display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-align:center;-ms-flex-align:center;align-items:center;padding:0.375rem 0.75rem;margin-bottom:0;font-size:1rem;font-weight:400;line-height:1.5;color:#495057;text-align:center;white-space:nowrap;background-color:#e9ecef;border:1px solid #ced4da;border-radius:0.25rem}.input-group-text input[type="radio"],.input-group-text input[type="checkbox"]{margin-top:0}.input-group-lg>.form-control,.input-group-lg>.input-group-prepend>.input-group-text,.input-group-lg>.input-group-append>.input-group-text,.input-group-lg>.input-group-prepend>.btn,.input-group-lg>.input-group-append>.btn{height:calc(2.875rem + 2px);padding:0.5rem 1rem;font-size:1.25rem;line-height:1.5;border-radius:0.3rem}.input-group-sm>.form-control,.input-group-sm>.input-group-prepend>.input-group-text,.input-group-sm>.input-group-append>.input-group-text,.input-group-sm>.input-group-prepend>.btn,.input-group-sm>.input-group-append>.btn{height:calc(1.8125rem + 2px);padding:0.25rem 0.5rem;font-size:0.875rem;line-height:1.5;border-radius:0.2rem}.input-group>.input-group-prepend>.btn,.input-group>.input-group-prepend>.input-group-text,.input-group>.input-group-append:not(:last-child)>.btn,.input-group>.input-group-append:not(:last-child)>.input-group-text,.input-group>.input-group-append:last-child>.btn:not(:last-child):not(.dropdown-toggle),.input-group>.input-group-append:last-child>.input-group-text:not(:last-child){border-top-right-radius:0;border-bottom-right-radius:0}.input-group>.input-group-append>.btn,.input-group>.input-group-append>.input-group-text,.input-group>.input-group-prepend:not(:first-child)>.btn,.input-group>.input-group-prepend:not(:first-child)>.input-group-text,.input-group>.input-group-prepend:first-child>.btn:not(:first-child),.input-group>.input-group-prepend:first-child>.input-group-text:not(:first-child){border-top-left-radius:0;border-bottom-left-radius:0}.custom-control{position:relative;display:block;min-height:1.5rem;padding-left:1.5rem}.custom-control-inline{display:-webkit-inline-box;display:-ms-inline-flexbox;display:inline-flex;margin-right:1rem}.custom-control-input{position:absolute;z-index:-1;opacity:0}.custom-control-input:checked ~ .custom-control-label::before{color:#fff;background-color:#2FA4E7}.custom-control-input:focus ~ .custom-control-label::before{-webkit-box-shadow:0 0 0 1px #fff,0 0 0 0.2rem rgba(47,164,231,0.25);box-shadow:0 0 0 1px #fff,0 0 0 0.2rem rgba(47,164,231,0.25)}.custom-control-input:active ~ .custom-control-label::before{color:#fff;background-color:#cfeaf9}.custom-control-input:disabled ~ .custom-control-label{color:#868e96}.custom-control-input:disabled ~ .custom-control-label::before{background-color:#e9ecef}.custom-control-label{position:relative;margin-bottom:0}.custom-control-label::before{position:absolute;top:0.25rem;left:-1.5rem;display:block;width:1rem;height:1rem;pointer-events:none;content:"";-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;background-color:#dee2e6}.custom-control-label::after{position:absolute;top:0.25rem;left:-1.5rem;display:block;width:1rem;height:1rem;content:"";background-repeat:no-repeat;background-position:center center;background-size:50% 50%}.custom-checkbox .custom-control-label::before{border-radius:0.25rem}.custom-checkbox .custom-control-input:checked ~ .custom-control-label::before{background-color:#2FA4E7}.custom-checkbox .custom-control-input:checked ~ .custom-control-label::after{background-image:url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'%3E%3Cpath fill='%23fff' d='M6.564.75l-3.59 3.612-1.538-1.55L0 4.26 2.974 7.25 8 2.193z'/%3E%3C/svg%3E")}.custom-checkbox .custom-control-input:indeterminate ~ .custom-control-label::before{background-color:#2FA4E7}.custom-checkbox .custom-control-input:indeterminate ~ .custom-control-label::after{background-image:url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 4'%3E%3Cpath stroke='%23fff' d='M0 2h4'/%3E%3C/svg%3E")}.custom-checkbox .custom-control-input:disabled:checked ~ .custom-control-label::before{background-color:rgba(47,164,231,0.5)}.custom-checkbox .custom-control-input:disabled:indeterminate ~ .custom-control-label::before{background-color:rgba(47,164,231,0.5)}.custom-radio .custom-control-label::before{border-radius:50%}.custom-radio .custom-control-input:checked ~ .custom-control-label::before{background-color:#2FA4E7}.custom-radio .custom-control-input:checked ~ .custom-control-label::after{background-image:url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='-4 -4 8 8'%3E%3Ccircle r='3' fill='%23fff'/%3E%3C/svg%3E")}.custom-radio .custom-control-input:disabled:checked ~ .custom-control-label::before{background-color:rgba(47,164,231,0.5)}.custom-select{display:inline-block;width:100%;height:calc(2.25rem + 2px);padding:0.375rem 1.75rem 0.375rem 0.75rem;line-height:1.5;color:#495057;vertical-align:middle;background:#fff url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 5'%3E%3Cpath fill='%23343a40' d='M2 0L0 2h4zm0 5L0 3h4z'/%3E%3C/svg%3E") no-repeat right 0.75rem center;background-size:8px 10px;border:1px solid #ced4da;border-radius:0.25rem;-webkit-appearance:none;-moz-appearance:none;appearance:none}.custom-select:focus{border-color:#a1d6f4;outline:0;-webkit-box-shadow:0 0 0 0.2rem rgba(161,214,244,0.5);box-shadow:0 0 0 0.2rem rgba(161,214,244,0.5)}.custom-select:focus::-ms-value{color:#495057;background-color:#fff}.custom-select[multiple],.custom-select[size]:not([size="1"]){height:auto;padding-right:0.75rem;background-image:none}.custom-select:disabled{color:#868e96;background-color:#e9ecef}.custom-select::-ms-expand{opacity:0}.custom-select-sm{height:calc(1.8125rem + 2px);padding-top:0.375rem;padding-bottom:0.375rem;font-size:75%}.custom-select-lg{height:calc(2.875rem + 2px);padding-top:0.375rem;padding-bottom:0.375rem;font-size:125%}.custom-file{position:relative;display:inline-block;width:100%;height:calc(2.25rem + 2px);margin-bottom:0}.custom-file-input{position:relative;z-index:2;width:100%;height:calc(2.25rem + 2px);margin:0;opacity:0}.custom-file-input:focus ~ .custom-file-label{border-color:#a1d6f4;-webkit-box-shadow:0 0 0 0.2rem rgba(47,164,231,0.25);box-shadow:0 0 0 0.2rem rgba(47,164,231,0.25)}.custom-file-input:focus ~ .custom-file-label::after{border-color:#a1d6f4}.custom-file-input:disabled ~ .custom-file-label{background-color:#e9ecef}.custom-file-input:lang(en) ~ .custom-file-label::after{content:"Browse"}.custom-file-label{position:absolute;top:0;right:0;left:0;z-index:1;height:calc(2.25rem + 2px);padding:0.375rem 0.75rem;line-height:1.5;color:#495057;background-color:#fff;border:1px solid #ced4da;border-radius:0.25rem}.custom-file-label::after{position:absolute;top:0;right:0;bottom:0;z-index:3;display:block;height:2.25rem;padding:0.375rem 0.75rem;line-height:1.5;color:#495057;content:"Browse";background-color:#e9ecef;border-left:1px solid #ced4da;border-radius:0 0.25rem 0.25rem 0}.custom-range{width:100%;padding-left:0;background-color:transparent;-webkit-appearance:none;-moz-appearance:none;appearance:none}.custom-range:focus{outline:none}.custom-range:focus::-webkit-slider-thumb{-webkit-box-shadow:0 0 0 1px #fff,0 0 0 0.2rem rgba(47,164,231,0.25);box-shadow:0 0 0 1px #fff,0 0 0 0.2rem rgba(47,164,231,0.25)}.custom-range:focus::-moz-range-thumb{box-shadow:0 0 0 1px #fff,0 0 0 0.2rem rgba(47,164,231,0.25)}.custom-range:focus::-ms-thumb{box-shadow:0 0 0 1px #fff,0 0 0 0.2rem rgba(47,164,231,0.25)}.custom-range::-moz-focus-outer{border:0}.custom-range::-webkit-slider-thumb{width:1rem;height:1rem;margin-top:-0.25rem;background-color:#2FA4E7;border:0;border-radius:1rem;-webkit-transition:background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, -webkit-box-shadow 0.15s ease-in-out;transition:background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, -webkit-box-shadow 0.15s ease-in-out;transition:background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;transition:background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out, -webkit-box-shadow 0.15s ease-in-out;-webkit-appearance:none;appearance:none}@media screen and (prefers-reduced-motion: reduce){.custom-range::-webkit-slider-thumb{-webkit-transition:none;transition:none}}.custom-range::-webkit-slider-thumb:active{background-color:#cfeaf9}.custom-range::-webkit-slider-runnable-track{width:100%;height:0.5rem;color:transparent;cursor:pointer;background-color:#dee2e6;border-color:transparent;border-radius:1rem}.custom-range::-moz-range-thumb{width:1rem;height:1rem;background-color:#2FA4E7;border:0;border-radius:1rem;-webkit-transition:background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, -webkit-box-shadow 0.15s ease-in-out;transition:background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, -webkit-box-shadow 0.15s ease-in-out;transition:background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;transition:background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out, -webkit-box-shadow 0.15s ease-in-out;-moz-appearance:none;appearance:none}@media screen and (prefers-reduced-motion: reduce){.custom-range::-moz-range-thumb{-webkit-transition:none;transition:none}}.custom-range::-moz-range-thumb:active{background-color:#cfeaf9}.custom-range::-moz-range-track{width:100%;height:0.5rem;color:transparent;cursor:pointer;background-color:#dee2e6;border-color:transparent;border-radius:1rem}.custom-range::-ms-thumb{width:1rem;height:1rem;margin-top:0;margin-right:0.2rem;margin-left:0.2rem;background-color:#2FA4E7;border:0;border-radius:1rem;-webkit-transition:background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, -webkit-box-shadow 0.15s ease-in-out;transition:background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, -webkit-box-shadow 0.15s ease-in-out;transition:background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;transition:background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out, -webkit-box-shadow 0.15s ease-in-out;appearance:none}@media screen and (prefers-reduced-motion: reduce){.custom-range::-ms-thumb{-webkit-transition:none;transition:none}}.custom-range::-ms-thumb:active{background-color:#cfeaf9}.custom-range::-ms-track{width:100%;height:0.5rem;color:transparent;cursor:pointer;background-color:transparent;border-color:transparent;border-width:0.5rem}.custom-range::-ms-fill-lower{background-color:#dee2e6;border-radius:1rem}.custom-range::-ms-fill-upper{margin-right:15px;background-color:#dee2e6;border-radius:1rem}.custom-control-label::before,.custom-file-label,.custom-select{-webkit-transition:background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, -webkit-box-shadow 0.15s ease-in-out;transition:background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, -webkit-box-shadow 0.15s ease-in-out;transition:background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;transition:background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out, -webkit-box-shadow 0.15s ease-in-out}@media screen and (prefers-reduced-motion: reduce){.custom-control-label::before,.custom-file-label,.custom-select{-webkit-transition:none;transition:none}}.nav{display:-webkit-box;display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;padding-left:0;margin-bottom:0;list-style:none}.nav-link{display:block;padding:0.5rem 1rem}.nav-link:hover,.nav-link:focus{text-decoration:none}.nav-link.disabled{color:#868e96}.nav-tabs{border-bottom:1px solid #dee2e6}.nav-tabs .nav-item{margin-bottom:-1px}.nav-tabs .nav-link{border:1px solid transparent;border-top-left-radius:0.25rem;border-top-right-radius:0.25rem}.nav-tabs .nav-link:hover,.nav-tabs .nav-link:focus{border-color:#e9ecef #e9ecef #dee2e6}.nav-tabs .nav-link.disabled{color:#868e96;background-color:transparent;border-color:transparent}.nav-tabs .nav-link.active,.nav-tabs .nav-item.show .nav-link{color:#495057;background-color:#fff;border-color:#dee2e6 #dee2e6 #fff}.nav-tabs .dropdown-menu{margin-top:-1px;border-top-left-radius:0;border-top-right-radius:0}.nav-pills .nav-link{border-radius:0.25rem}.nav-pills .nav-link.active,.nav-pills .show>.nav-link{color:#fff;background-color:#2FA4E7}.nav-fill .nav-item{-webkit-box-flex:1;-ms-flex:1 1 auto;flex:1 1 auto;text-align:center}.nav-justified .nav-item{-ms-flex-preferred-size:0;flex-basis:0;-webkit-box-flex:1;-ms-flex-positive:1;flex-grow:1;text-align:center}.tab-content>.tab-pane{display:none}.tab-content>.active{display:block}.navbar{position:relative;display:-webkit-box;display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;-webkit-box-align:center;-ms-flex-align:center;align-items:center;-webkit-box-pack:justify;-ms-flex-pack:justify;justify-content:space-between;padding:0.5rem 1rem}.navbar>.container,.navbar>.container-fluid{display:-webkit-box;display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;-webkit-box-align:center;-ms-flex-align:center;align-items:center;-webkit-box-pack:justify;-ms-flex-pack:justify;justify-content:space-between}.navbar-brand{display:inline-block;padding-top:0.3125rem;padding-bottom:0.3125rem;margin-right:1rem;font-size:1.25rem;line-height:inherit;white-space:nowrap}.navbar-brand:hover,.navbar-brand:focus{text-decoration:none}.navbar-nav{display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-orient:vertical;-webkit-box-direction:normal;-ms-flex-direction:column;flex-direction:column;padding-left:0;margin-bottom:0;list-style:none}.navbar-nav .nav-link{padding-right:0;padding-left:0}.navbar-nav .dropdown-menu{position:static;float:none}.navbar-text{display:inline-block;padding-top:0.5rem;padding-bottom:0.5rem}.navbar-collapse{-ms-flex-preferred-size:100%;flex-basis:100%;-webkit-box-flex:1;-ms-flex-positive:1;flex-grow:1;-webkit-box-align:center;-ms-flex-align:center;align-items:center}.navbar-toggler{padding:0.25rem 0.75rem;font-size:1.25rem;line-height:1;background-color:transparent;border:1px solid transparent;border-radius:0.25rem}.navbar-toggler:hover,.navbar-toggler:focus{text-decoration:none}.navbar-toggler:not(:disabled):not(.disabled){cursor:pointer}.navbar-toggler-icon{display:inline-block;width:1.5em;height:1.5em;vertical-align:middle;content:"";background:no-repeat center center;background-size:100% 100%}@media (max-width: 575.98px){.navbar-expand-sm>.container,.navbar-expand-sm>.container-fluid{padding-right:0;padding-left:0}}@media (min-width: 576px){.navbar-expand-sm{-webkit-box-orient:horizontal;-webkit-box-direction:normal;-ms-flex-flow:row nowrap;flex-flow:row nowrap;-webkit-box-pack:start;-ms-flex-pack:start;justify-content:flex-start}.navbar-expand-sm .navbar-nav{-webkit-box-orient:horizontal;-webkit-box-direction:normal;-ms-flex-direction:row;flex-direction:row}.navbar-expand-sm .navbar-nav .dropdown-menu{position:absolute}.navbar-expand-sm .navbar-nav .nav-link{padding-right:0.5rem;padding-left:0.5rem}.navbar-expand-sm>.container,.navbar-expand-sm>.container-fluid{-ms-flex-wrap:nowrap;flex-wrap:nowrap}.navbar-expand-sm .navbar-collapse{display:-webkit-box !important;display:-ms-flexbox !important;display:flex !important;-ms-flex-preferred-size:auto;flex-basis:auto}.navbar-expand-sm .navbar-toggler{display:none}}@media (max-width: 767.98px){.navbar-expand-md>.container,.navbar-expand-md>.container-fluid{padding-right:0;padding-left:0}}@media (min-width: 768px){.navbar-expand-md{-webkit-box-orient:horizontal;-webkit-box-direction:normal;-ms-flex-flow:row nowrap;flex-flow:row nowrap;-webkit-box-pack:start;-ms-flex-pack:start;justify-content:flex-start}.navbar-expand-md .navbar-nav{-webkit-box-orient:horizontal;-webkit-box-direction:normal;-ms-flex-direction:row;flex-direction:row}.navbar-expand-md .navbar-nav .dropdown-menu{position:absolute}.navbar-expand-md .navbar-nav .nav-link{padding-right:0.5rem;padding-left:0.5rem}.navbar-expand-md>.container,.navbar-expand-md>.container-fluid{-ms-flex-wrap:nowrap;flex-wrap:nowrap}.navbar-expand-md .navbar-collapse{display:-webkit-box !important;display:-ms-flexbox !important;display:flex !important;-ms-flex-preferred-size:auto;flex-basis:auto}.navbar-expand-md .navbar-toggler{display:none}}@media (max-width: 991.98px){.navbar-expand-lg>.container,.navbar-expand-lg>.container-fluid{padding-right:0;padding-left:0}}@media (min-width: 992px){.navbar-expand-lg{-webkit-box-orient:horizontal;-webkit-box-direction:normal;-ms-flex-flow:row nowrap;flex-flow:row nowrap;-webkit-box-pack:start;-ms-flex-pack:start;justify-content:flex-start}.navbar-expand-lg .navbar-nav{-webkit-box-orient:horizontal;-webkit-box-direction:normal;-ms-flex-direction:row;flex-direction:row}.navbar-expand-lg .navbar-nav .dropdown-menu{position:absolute}.navbar-expand-lg .navbar-nav .nav-link{padding-right:0.5rem;padding-left:0.5rem}.navbar-expand-lg>.container,.navbar-expand-lg>.container-fluid{-ms-flex-wrap:nowrap;flex-wrap:nowrap}.navbar-expand-lg .navbar-collapse{display:-webkit-box !important;display:-ms-flexbox !important;display:flex !important;-ms-flex-preferred-size:auto;flex-basis:auto}.navbar-expand-lg .navbar-toggler{display:none}}@media (max-width: 1199.98px){.navbar-expand-xl>.container,.navbar-expand-xl>.container-fluid{padding-right:0;padding-left:0}}@media (min-width: 1200px){.navbar-expand-xl{-webkit-box-orient:horizontal;-webkit-box-direction:normal;-ms-flex-flow:row nowrap;flex-flow:row nowrap;-webkit-box-pack:start;-ms-flex-pack:start;justify-content:flex-start}.navbar-expand-xl .navbar-nav{-webkit-box-orient:horizontal;-webkit-box-direction:normal;-ms-flex-direction:row;flex-direction:row}.navbar-expand-xl .navbar-nav .dropdown-menu{position:absolute}.navbar-expand-xl .navbar-nav .nav-link{padding-right:0.5rem;padding-left:0.5rem}.navbar-expand-xl>.container,.navbar-expand-xl>.container-fluid{-ms-flex-wrap:nowrap;flex-wrap:nowrap}.navbar-expand-xl .navbar-collapse{display:-webkit-box !important;display:-ms-flexbox !important;display:flex !important;-ms-flex-preferred-size:auto;flex-basis:auto}.navbar-expand-xl .navbar-toggler{display:none}}.navbar-expand{-webkit-box-orient:horizontal;-webkit-box-direction:normal;-ms-flex-flow:row nowrap;flex-flow:row nowrap;-webkit-box-pack:start;-ms-flex-pack:start;justify-content:flex-start}.navbar-expand>.container,.navbar-expand>.container-fluid{padding-right:0;padding-left:0}.navbar-expand .navbar-nav{-webkit-box-orient:horizontal;-webkit-box-direction:normal;-ms-flex-direction:row;flex-direction:row}.navbar-expand .navbar-nav .dropdown-menu{position:absolute}.navbar-expand .navbar-nav .nav-link{padding-right:0.5rem;padding-left:0.5rem}.navbar-expand>.container,.navbar-expand>.container-fluid{-ms-flex-wrap:nowrap;flex-wrap:nowrap}.navbar-expand .navbar-collapse{display:-webkit-box !important;display:-ms-flexbox !important;display:flex !important;-ms-flex-preferred-size:auto;flex-basis:auto}.navbar-expand .navbar-toggler{display:none}.navbar-light .navbar-brand{color:rgba(0,0,0,0.9)}.navbar-light .navbar-brand:hover,.navbar-light .navbar-brand:focus{color:rgba(0,0,0,0.9)}.navbar-light .navbar-nav .nav-link{color:rgba(0,0,0,0.5)}.navbar-light .navbar-nav .nav-link:hover,.navbar-light .navbar-nav .nav-link:focus{color:rgba(0,0,0,0.7)}.navbar-light .navbar-nav .nav-link.disabled{color:rgba(0,0,0,0.3)}.navbar-light .navbar-nav .show>.nav-link,.navbar-light .navbar-nav .active>.nav-link,.navbar-light .navbar-nav .nav-link.show,.navbar-light .navbar-nav .nav-link.active{color:rgba(0,0,0,0.9)}.navbar-light .navbar-toggler{color:rgba(0,0,0,0.5);border-color:rgba(0,0,0,0.1)}.navbar-light .navbar-toggler-icon{background-image:url("data:image/svg+xml;charset=utf8,%3Csvg viewBox='0 0 30 30' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath stroke='rgba(0, 0, 0, 0.5)' stroke-width='2' stroke-linecap='round' stroke-miterlimit='10' d='M4 7h22M4 15h22M4 23h22'/%3E%3C/svg%3E")}.navbar-light .navbar-text{color:rgba(0,0,0,0.5)}.navbar-light .navbar-text a{color:rgba(0,0,0,0.9)}.navbar-light .navbar-text a:hover,.navbar-light .navbar-text a:focus{color:rgba(0,0,0,0.9)}.navbar-dark .navbar-brand{color:#fff}.navbar-dark .navbar-brand:hover,.navbar-dark .navbar-brand:focus{color:#fff}.navbar-dark .navbar-nav .nav-link{color:rgba(255,255,255,0.8)}.navbar-dark .navbar-nav .nav-link:hover,.navbar-dark .navbar-nav .nav-link:focus{color:#fff}.navbar-dark .navbar-nav .nav-link.disabled{color:rgba(255,255,255,0.25)}.navbar-dark .navbar-nav .show>.nav-link,.navbar-dark .navbar-nav .active>.nav-link,.navbar-dark .navbar-nav .nav-link.show,.navbar-dark .navbar-nav .nav-link.active{color:#fff}.navbar-dark .navbar-toggler{color:rgba(255,255,255,0.8);border-color:rgba(255,255,255,0.1)}.navbar-dark .navbar-toggler-icon{background-image:url("data:image/svg+xml;charset=utf8,%3Csvg viewBox='0 0 30 30' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath stroke='rgba(255, 255, 255, 0.8)' stroke-width='2' stroke-linecap='round' stroke-miterlimit='10' d='M4 7h22M4 15h22M4 23h22'/%3E%3C/svg%3E")}.navbar-dark .navbar-text{color:rgba(255,255,255,0.8)}.navbar-dark .navbar-text a{color:#fff}.navbar-dark .navbar-text a:hover,.navbar-dark .navbar-text a:focus{color:#fff}.card{position:relative;display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-orient:vertical;-webkit-box-direction:normal;-ms-flex-direction:column;flex-direction:column;min-width:0;word-wrap:break-word;background-color:#fff;background-clip:border-box;border:1px solid rgba(0,0,0,0.125);border-radius:0.25rem}.card>hr{margin-right:0;margin-left:0}.card>.list-group:first-child .list-group-item:first-child{border-top-left-radius:0.25rem;border-top-right-radius:0.25rem}.card>.list-group:last-child .list-group-item:last-child{border-bottom-right-radius:0.25rem;border-bottom-left-radius:0.25rem}.card-body{-webkit-box-flex:1;-ms-flex:1 1 auto;flex:1 1 auto;padding:1.25rem}.card-title{margin-bottom:0.75rem}.card-subtitle{margin-top:-0.375rem;margin-bottom:0}.card-text:last-child{margin-bottom:0}.card-link:hover{text-decoration:none}.card-link+.card-link{margin-left:1.25rem}.card-header{padding:0.75rem 1.25rem;margin-bottom:0;background-color:rgba(0,0,0,0.03);border-bottom:1px solid rgba(0,0,0,0.125)}.card-header:first-child{border-radius:calc(0.25rem - 1px) calc(0.25rem - 1px) 0 0}.card-header+.list-group .list-group-item:first-child{border-top:0}.card-footer{padding:0.75rem 1.25rem;background-color:rgba(0,0,0,0.03);border-top:1px solid rgba(0,0,0,0.125)}.card-footer:last-child{border-radius:0 0 calc(0.25rem - 1px) calc(0.25rem - 1px)}.card-header-tabs{margin-right:-0.625rem;margin-bottom:-0.75rem;margin-left:-0.625rem;border-bottom:0}.card-header-pills{margin-right:-0.625rem;margin-left:-0.625rem}.card-img-overlay{position:absolute;top:0;right:0;bottom:0;left:0;padding:1.25rem}.card-img{width:100%;border-radius:calc(0.25rem - 1px)}.card-img-top{width:100%;border-top-left-radius:calc(0.25rem - 1px);border-top-right-radius:calc(0.25rem - 1px)}.card-img-bottom{width:100%;border-bottom-right-radius:calc(0.25rem - 1px);border-bottom-left-radius:calc(0.25rem - 1px)}.card-deck{display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-orient:vertical;-webkit-box-direction:normal;-ms-flex-direction:column;flex-direction:column}.card-deck .card{margin-bottom:15px}@media (min-width: 576px){.card-deck{-webkit-box-orient:horizontal;-webkit-box-direction:normal;-ms-flex-flow:row wrap;flex-flow:row wrap;margin-right:-15px;margin-left:-15px}.card-deck .card{display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-flex:1;-ms-flex:1 0 0%;flex:1 0 0%;-webkit-box-orient:vertical;-webkit-box-direction:normal;-ms-flex-direction:column;flex-direction:column;margin-right:15px;margin-bottom:0;margin-left:15px}}.card-group{display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-orient:vertical;-webkit-box-direction:normal;-ms-flex-direction:column;flex-direction:column}.card-group>.card{margin-bottom:15px}@media (min-width: 576px){.card-group{-webkit-box-orient:horizontal;-webkit-box-direction:normal;-ms-flex-flow:row wrap;flex-flow:row wrap}.card-group>.card{-webkit-box-flex:1;-ms-flex:1 0 0%;flex:1 0 0%;margin-bottom:0}.card-group>.card+.card{margin-left:0;border-left:0}.card-group>.card:first-child{border-top-right-radius:0;border-bottom-right-radius:0}.card-group>.card:first-child .card-img-top,.card-group>.card:first-child .card-header{border-top-right-radius:0}.card-group>.card:first-child .card-img-bottom,.card-group>.card:first-child .card-footer{border-bottom-right-radius:0}.card-group>.card:last-child{border-top-left-radius:0;border-bottom-left-radius:0}.card-group>.card:last-child .card-img-top,.card-group>.card:last-child .card-header{border-top-left-radius:0}.card-group>.card:last-child .card-img-bottom,.card-group>.card:last-child .card-footer{border-bottom-left-radius:0}.card-group>.card:only-child{border-radius:0.25rem}.card-group>.card:only-child .card-img-top,.card-group>.card:only-child .card-header{border-top-left-radius:0.25rem;border-top-right-radius:0.25rem}.card-group>.card:only-child .card-img-bottom,.card-group>.card:only-child .card-footer{border-bottom-right-radius:0.25rem;border-bottom-left-radius:0.25rem}.card-group>.card:not(:first-child):not(:last-child):not(:only-child){border-radius:0}.card-group>.card:not(:first-child):not(:last-child):not(:only-child) .card-img-top,.card-group>.card:not(:first-child):not(:last-child):not(:only-child) .card-img-bottom,.card-group>.card:not(:first-child):not(:last-child):not(:only-child) .card-header,.card-group>.card:not(:first-child):not(:last-child):not(:only-child) .card-footer{border-radius:0}}.card-columns .card{margin-bottom:0.75rem}@media (min-width: 576px){.card-columns{-webkit-column-count:3;column-count:3;-webkit-column-gap:1.25rem;column-gap:1.25rem;orphans:1;widows:1}.card-columns .card{display:inline-block;width:100%}}.accordion .card:not(:first-of-type):not(:last-of-type){border-bottom:0;border-radius:0}.accordion .card:not(:first-of-type) .card-header:first-child{border-radius:0}.accordion .card:first-of-type{border-bottom:0;border-bottom-right-radius:0;border-bottom-left-radius:0}.accordion .card:last-of-type{border-top-left-radius:0;border-top-right-radius:0}.breadcrumb{display:-webkit-box;display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;padding:0.75rem 1rem;margin-bottom:1rem;list-style:none;background-color:#e9ecef;border-radius:0.25rem}.breadcrumb-item+.breadcrumb-item{padding-left:0.5rem}.breadcrumb-item+.breadcrumb-item::before{display:inline-block;padding-right:0.5rem;color:#868e96;content:"/"}.breadcrumb-item+.breadcrumb-item:hover::before{text-decoration:underline}.breadcrumb-item+.breadcrumb-item:hover::before{text-decoration:none}.breadcrumb-item.active{color:#868e96}.pagination{display:-webkit-box;display:-ms-flexbox;display:flex;padding-left:0;list-style:none;border-radius:0.25rem}.page-link{position:relative;display:block;padding:0.5rem 0.75rem;margin-left:-1px;line-height:1.25;color:#2FA4E7;background-color:#fff;border:1px solid #dee2e6}.page-link:hover{z-index:2;color:#157ab5;text-decoration:none;background-color:#e9ecef;border-color:#dee2e6}.page-link:focus{z-index:2;outline:0;-webkit-box-shadow:0 0 0 0.2rem rgba(47,164,231,0.25);box-shadow:0 0 0 0.2rem rgba(47,164,231,0.25)}.page-link:not(:disabled):not(.disabled){cursor:pointer}.page-item:first-child .page-link{margin-left:0;border-top-left-radius:0.25rem;border-bottom-left-radius:0.25rem}.page-item:last-child .page-link{border-top-right-radius:0.25rem;border-bottom-right-radius:0.25rem}.page-item.active .page-link{z-index:1;color:#fff;background-color:#2FA4E7;border-color:#2FA4E7}.page-item.disabled .page-link{color:#868e96;pointer-events:none;cursor:auto;background-color:#fff;border-color:#dee2e6}.pagination-lg .page-link{padding:0.75rem 1.5rem;font-size:1.25rem;line-height:1.5}.pagination-lg .page-item:first-child .page-link{border-top-left-radius:0.3rem;border-bottom-left-radius:0.3rem}.pagination-lg .page-item:last-child .page-link{border-top-right-radius:0.3rem;border-bottom-right-radius:0.3rem}.pagination-sm .page-link{padding:0.25rem 0.5rem;font-size:0.875rem;line-height:1.5}.pagination-sm .page-item:first-child .page-link{border-top-left-radius:0.2rem;border-bottom-left-radius:0.2rem}.pagination-sm .page-item:last-child .page-link{border-top-right-radius:0.2rem;border-bottom-right-radius:0.2rem}.badge{display:inline-block;padding:0.25em 0.4em;font-size:75%;font-weight:700;line-height:1;text-align:center;white-space:nowrap;vertical-align:baseline;border-radius:0.25rem}.badge:empty{display:none}.btn .badge{position:relative;top:-1px}.badge-pill{padding-right:0.6em;padding-left:0.6em;border-radius:10rem}.badge-primary{color:#fff;background-color:#2FA4E7}.badge-primary[href]:hover,.badge-primary[href]:focus{color:#fff;text-decoration:none;background-color:#178acc}.badge-secondary{color:#212529;background-color:#e9ecef}.badge-secondary[href]:hover,.badge-secondary[href]:focus{color:#212529;text-decoration:none;background-color:#cbd3da}.badge-success{color:#fff;background-color:#73A839}.badge-success[href]:hover,.badge-success[href]:focus{color:#fff;text-decoration:none;background-color:#59822c}.badge-info{color:#fff;background-color:#033C73}.badge-info[href]:hover,.badge-info[href]:focus{color:#fff;text-decoration:none;background-color:#022241}.badge-warning{color:#fff;background-color:#DD5600}.badge-warning[href]:hover,.badge-warning[href]:focus{color:#fff;text-decoration:none;background-color:#aa4200}.badge-danger{color:#fff;background-color:#C71C22}.badge-danger[href]:hover,.badge-danger[href]:focus{color:#fff;text-decoration:none;background-color:#9a161a}.badge-light{color:#212529;background-color:#f8f9fa}.badge-light[href]:hover,.badge-light[href]:focus{color:#212529;text-decoration:none;background-color:#dae0e5}.badge-dark{color:#fff;background-color:#343a40}.badge-dark[href]:hover,.badge-dark[href]:focus{color:#fff;text-decoration:none;background-color:#1d2124}.jumbotron{padding:2rem 1rem;margin-bottom:2rem;background-color:#e9ecef;border-radius:0.3rem}@media (min-width: 576px){.jumbotron{padding:4rem 2rem}}.jumbotron-fluid{padding-right:0;padding-left:0;border-radius:0}.alert{position:relative;padding:0.75rem 1.25rem;margin-bottom:1rem;border:1px solid transparent;border-radius:0.25rem}.alert-heading{color:inherit}.alert-link{font-weight:700}.alert-dismissible{padding-right:4rem}.alert-dismissible .close{position:absolute;top:0;right:0;padding:0.75rem 1.25rem;color:inherit}.alert-primary{color:#185578;background-color:#d5edfa;border-color:#c5e6f8}.alert-primary hr{border-top-color:#aedcf5}.alert-primary .alert-link{color:#10374e}.alert-secondary{color:#797b7c;background-color:#fbfbfc;border-color:#f9fafb}.alert-secondary hr{border-top-color:#eaedf1}.alert-secondary .alert-link{color:#606162}.alert-success{color:#3c571e;background-color:#e3eed7;border-color:#d8e7c8}.alert-success hr{border-top-color:#cbdfb6}.alert-success .alert-link{color:#223111}.alert-info{color:#021f3c;background-color:#cdd8e3;border-color:#b8c8d8}.alert-info hr{border-top-color:#a8bbcf}.alert-info .alert-link{color:#00060b}.alert-warning{color:#732d00;background-color:#f8ddcc;border-color:#f5d0b8}.alert-warning hr{border-top-color:#f2c1a2}.alert-warning .alert-link{color:#401900}.alert-danger{color:#670f12;background-color:#f4d2d3;border-color:#efbfc1}.alert-danger hr{border-top-color:#eaabad}.alert-danger .alert-link{color:#3a090a}.alert-light{color:#818182;background-color:#fefefe;border-color:#fdfdfe}.alert-light hr{border-top-color:#ececf6}.alert-light .alert-link{color:#686868}.alert-dark{color:#1b1e21;background-color:#d6d8d9;border-color:#c6c8ca}.alert-dark hr{border-top-color:#b9bbbe}.alert-dark .alert-link{color:#040505}@-webkit-keyframes progress-bar-stripes{from{background-position:1rem 0}to{background-position:0 0}}@keyframes progress-bar-stripes{from{background-position:1rem 0}to{background-position:0 0}}.progress{display:-webkit-box;display:-ms-flexbox;display:flex;height:1rem;overflow:hidden;font-size:0.75rem;background-color:#e9ecef;border-radius:0.25rem}.progress-bar{display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-orient:vertical;-webkit-box-direction:normal;-ms-flex-direction:column;flex-direction:column;-webkit-box-pack:center;-ms-flex-pack:center;justify-content:center;color:#fff;text-align:center;white-space:nowrap;background-color:#2FA4E7;-webkit-transition:width 0.6s ease;transition:width 0.6s ease}@media screen and (prefers-reduced-motion: reduce){.progress-bar{-webkit-transition:none;transition:none}}.progress-bar-striped{background-image:linear-gradient(45deg, rgba(255,255,255,0.15) 25%, transparent 25%, transparent 50%, rgba(255,255,255,0.15) 50%, rgba(255,255,255,0.15) 75%, transparent 75%, transparent);background-size:1rem 1rem}.progress-bar-animated{-webkit-animation:progress-bar-stripes 1s linear infinite;animation:progress-bar-stripes 1s linear infinite}.media{display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-align:start;-ms-flex-align:start;align-items:flex-start}.media-body{-webkit-box-flex:1;-ms-flex:1;flex:1}.list-group{display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-orient:vertical;-webkit-box-direction:normal;-ms-flex-direction:column;flex-direction:column;padding-left:0;margin-bottom:0}.list-group-item-action{width:100%;color:#495057;text-align:inherit}.list-group-item-action:hover,.list-group-item-action:focus{color:#495057;text-decoration:none;background-color:#f8f9fa}.list-group-item-action:active{color:#495057;background-color:#e9ecef}.list-group-item{position:relative;display:block;padding:0.75rem 1.25rem;margin-bottom:-1px;background-color:#fff;border:1px solid rgba(0,0,0,0.125)}.list-group-item:first-child{border-top-left-radius:0.25rem;border-top-right-radius:0.25rem}.list-group-item:last-child{margin-bottom:0;border-bottom-right-radius:0.25rem;border-bottom-left-radius:0.25rem}.list-group-item:hover,.list-group-item:focus{z-index:1;text-decoration:none}.list-group-item.disabled,.list-group-item:disabled{color:#868e96;background-color:#fff}.list-group-item.active{z-index:2;color:#fff;background-color:#2FA4E7;border-color:#2FA4E7}.list-group-flush .list-group-item{border-right:0;border-left:0;border-radius:0}.list-group-flush:first-child .list-group-item:first-child{border-top:0}.list-group-flush:last-child .list-group-item:last-child{border-bottom:0}.list-group-item-primary{color:#185578;background-color:#c5e6f8}.list-group-item-primary.list-group-item-action:hover,.list-group-item-primary.list-group-item-action:focus{color:#185578;background-color:#aedcf5}.list-group-item-primary.list-group-item-action.active{color:#fff;background-color:#185578;border-color:#185578}.list-group-item-secondary{color:#797b7c;background-color:#f9fafb}.list-group-item-secondary.list-group-item-action:hover,.list-group-item-secondary.list-group-item-action:focus{color:#797b7c;background-color:#eaedf1}.list-group-item-secondary.list-group-item-action.active{color:#fff;background-color:#797b7c;border-color:#797b7c}.list-group-item-success{color:#3c571e;background-color:#d8e7c8}.list-group-item-success.list-group-item-action:hover,.list-group-item-success.list-group-item-action:focus{color:#3c571e;background-color:#cbdfb6}.list-group-item-success.list-group-item-action.active{color:#fff;background-color:#3c571e;border-color:#3c571e}.list-group-item-info{color:#021f3c;background-color:#b8c8d8}.list-group-item-info.list-group-item-action:hover,.list-group-item-info.list-group-item-action:focus{color:#021f3c;background-color:#a8bbcf}.list-group-item-info.list-group-item-action.active{color:#fff;background-color:#021f3c;border-color:#021f3c}.list-group-item-warning{color:#732d00;background-color:#f5d0b8}.list-group-item-warning.list-group-item-action:hover,.list-group-item-warning.list-group-item-action:focus{color:#732d00;background-color:#f2c1a2}.list-group-item-warning.list-group-item-action.active{color:#fff;background-color:#732d00;border-color:#732d00}.list-group-item-danger{color:#670f12;background-color:#efbfc1}.list-group-item-danger.list-group-item-action:hover,.list-group-item-danger.list-group-item-action:focus{color:#670f12;background-color:#eaabad}.list-group-item-danger.list-group-item-action.active{color:#fff;background-color:#670f12;border-color:#670f12}.list-group-item-light{color:#818182;background-color:#fdfdfe}.list-group-item-light.list-group-item-action:hover,.list-group-item-light.list-group-item-action:focus{color:#818182;background-color:#ececf6}.list-group-item-light.list-group-item-action.active{color:#fff;background-color:#818182;border-color:#818182}.list-group-item-dark{color:#1b1e21;background-color:#c6c8ca}.list-group-item-dark.list-group-item-action:hover,.list-group-item-dark.list-group-item-action:focus{color:#1b1e21;background-color:#b9bbbe}.list-group-item-dark.list-group-item-action.active{color:#fff;background-color:#1b1e21;border-color:#1b1e21}.close{float:right;font-size:1.5rem;font-weight:700;line-height:1;color:#000;text-shadow:0 1px 0 #fff;opacity:.5}.close:not(:disabled):not(.disabled){cursor:pointer}.close:not(:disabled):not(.disabled):hover,.close:not(:disabled):not(.disabled):focus{color:#000;text-decoration:none;opacity:.75}button.close{padding:0;background-color:transparent;border:0;-webkit-appearance:none}.modal-open{overflow:hidden}.modal-open .modal{overflow-x:hidden;overflow-y:auto}.modal{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1050;display:none;overflow:hidden;outline:0}.modal-dialog{position:relative;width:auto;margin:0.5rem;pointer-events:none}.modal.fade .modal-dialog{-webkit-transition:-webkit-transform 0.3s ease-out;transition:-webkit-transform 0.3s ease-out;transition:transform 0.3s ease-out;transition:transform 0.3s ease-out, -webkit-transform 0.3s ease-out;-webkit-transform:translate(0, -25%);transform:translate(0, -25%)}@media screen and (prefers-reduced-motion: reduce){.modal.fade .modal-dialog{-webkit-transition:none;transition:none}}.modal.show .modal-dialog{-webkit-transform:translate(0, 0);transform:translate(0, 0)}.modal-dialog-centered{display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-align:center;-ms-flex-align:center;align-items:center;min-height:calc(100% - (0.5rem * 2))}.modal-dialog-centered::before{display:block;height:calc(100vh - (0.5rem * 2));content:""}.modal-content{position:relative;display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-orient:vertical;-webkit-box-direction:normal;-ms-flex-direction:column;flex-direction:column;width:100%;pointer-events:auto;background-color:#fff;background-clip:padding-box;border:1px solid rgba(0,0,0,0.2);border-radius:0.3rem;outline:0}.modal-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1040;background-color:#000}.modal-backdrop.fade{opacity:0}.modal-backdrop.show{opacity:0.5}.modal-header{display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-align:start;-ms-flex-align:start;align-items:flex-start;-webkit-box-pack:justify;-ms-flex-pack:justify;justify-content:space-between;padding:1rem;border-bottom:1px solid #e9ecef;border-top-left-radius:0.3rem;border-top-right-radius:0.3rem}.modal-header .close{padding:1rem;margin:-1rem -1rem -1rem auto}.modal-title{margin-bottom:0;line-height:1.5}.modal-body{position:relative;-webkit-box-flex:1;-ms-flex:1 1 auto;flex:1 1 auto;padding:1rem}.modal-footer{display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-align:center;-ms-flex-align:center;align-items:center;-webkit-box-pack:end;-ms-flex-pack:end;justify-content:flex-end;padding:1rem;border-top:1px solid #e9ecef}.modal-footer>:not(:first-child){margin-left:.25rem}.modal-footer>:not(:last-child){margin-right:.25rem}.modal-scrollbar-measure{position:absolute;top:-9999px;width:50px;height:50px;overflow:scroll}@media (min-width: 576px){.modal-dialog{max-width:500px;margin:1.75rem auto}.modal-dialog-centered{min-height:calc(100% - (1.75rem * 2))}.modal-dialog-centered::before{height:calc(100vh - (1.75rem * 2))}.modal-sm{max-width:300px}}@media (min-width: 992px){.modal-lg{max-width:800px}}.tooltip{position:absolute;z-index:1070;display:block;margin:0;font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";font-style:normal;font-weight:400;line-height:1.5;text-align:left;text-align:start;text-decoration:none;text-shadow:none;text-transform:none;letter-spacing:normal;word-break:normal;word-spacing:normal;white-space:normal;line-break:auto;font-size:0.875rem;word-wrap:break-word;opacity:0}.tooltip.show{opacity:0.9}.tooltip .arrow{position:absolute;display:block;width:0.8rem;height:0.4rem}.tooltip .arrow::before{position:absolute;content:"";border-color:transparent;border-style:solid}.bs-tooltip-top,.bs-tooltip-auto[x-placement^="top"]{padding:0.4rem 0}.bs-tooltip-top .arrow,.bs-tooltip-auto[x-placement^="top"] .arrow{bottom:0}.bs-tooltip-top .arrow::before,.bs-tooltip-auto[x-placement^="top"] .arrow::before{top:0;border-width:0.4rem 0.4rem 0;border-top-color:#000}.bs-tooltip-right,.bs-tooltip-auto[x-placement^="right"]{padding:0 0.4rem}.bs-tooltip-right .arrow,.bs-tooltip-auto[x-placement^="right"] .arrow{left:0;width:0.4rem;height:0.8rem}.bs-tooltip-right .arrow::before,.bs-tooltip-auto[x-placement^="right"] .arrow::before{right:0;border-width:0.4rem 0.4rem 0.4rem 0;border-right-color:#000}.bs-tooltip-bottom,.bs-tooltip-auto[x-placement^="bottom"]{padding:0.4rem 0}.bs-tooltip-bottom .arrow,.bs-tooltip-auto[x-placement^="bottom"] .arrow{top:0}.bs-tooltip-bottom .arrow::before,.bs-tooltip-auto[x-placement^="bottom"] .arrow::before{bottom:0;border-width:0 0.4rem 0.4rem;border-bottom-color:#000}.bs-tooltip-left,.bs-tooltip-auto[x-placement^="left"]{padding:0 0.4rem}.bs-tooltip-left .arrow,.bs-tooltip-auto[x-placement^="left"] .arrow{right:0;width:0.4rem;height:0.8rem}.bs-tooltip-left .arrow::before,.bs-tooltip-auto[x-placement^="left"] .arrow::before{left:0;border-width:0.4rem 0 0.4rem 0.4rem;border-left-color:#000}.tooltip-inner{max-width:200px;padding:0.25rem 0.5rem;color:#fff;text-align:center;background-color:#000;border-radius:0.25rem}.popover{position:absolute;top:0;left:0;z-index:1060;display:block;max-width:276px;font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";font-style:normal;font-weight:400;line-height:1.5;text-align:left;text-align:start;text-decoration:none;text-shadow:none;text-transform:none;letter-spacing:normal;word-break:normal;word-spacing:normal;white-space:normal;line-break:auto;font-size:0.875rem;word-wrap:break-word;background-color:#fff;background-clip:padding-box;border:1px solid rgba(0,0,0,0.2);border-radius:0.3rem}.popover .arrow{position:absolute;display:block;width:1rem;height:0.5rem;margin:0 0.3rem}.popover .arrow::before,.popover .arrow::after{position:absolute;display:block;content:"";border-color:transparent;border-style:solid}.bs-popover-top,.bs-popover-auto[x-placement^="top"]{margin-bottom:0.5rem}.bs-popover-top .arrow,.bs-popover-auto[x-placement^="top"] .arrow{bottom:calc((0.5rem + 1px) * -1)}.bs-popover-top .arrow::before,.bs-popover-auto[x-placement^="top"] .arrow::before,.bs-popover-top .arrow::after,.bs-popover-auto[x-placement^="top"] .arrow::after{border-width:0.5rem 0.5rem 0}.bs-popover-top .arrow::before,.bs-popover-auto[x-placement^="top"] .arrow::before{bottom:0;border-top-color:rgba(0,0,0,0.25)}.bs-popover-top .arrow::after,.bs-popover-auto[x-placement^="top"] .arrow::after{bottom:1px;border-top-color:#fff}.bs-popover-right,.bs-popover-auto[x-placement^="right"]{margin-left:0.5rem}.bs-popover-right .arrow,.bs-popover-auto[x-placement^="right"] .arrow{left:calc((0.5rem + 1px) * -1);width:0.5rem;height:1rem;margin:0.3rem 0}.bs-popover-right .arrow::before,.bs-popover-auto[x-placement^="right"] .arrow::before,.bs-popover-right .arrow::after,.bs-popover-auto[x-placement^="right"] .arrow::after{border-width:0.5rem 0.5rem 0.5rem 0}.bs-popover-right .arrow::before,.bs-popover-auto[x-placement^="right"] .arrow::before{left:0;border-right-color:rgba(0,0,0,0.25)}.bs-popover-right .arrow::after,.bs-popover-auto[x-placement^="right"] .arrow::after{left:1px;border-right-color:#fff}.bs-popover-bottom,.bs-popover-auto[x-placement^="bottom"]{margin-top:0.5rem}.bs-popover-bottom .arrow,.bs-popover-auto[x-placement^="bottom"] .arrow{top:calc((0.5rem + 1px) * -1)}.bs-popover-bottom .arrow::before,.bs-popover-auto[x-placement^="bottom"] .arrow::before,.bs-popover-bottom .arrow::after,.bs-popover-auto[x-placement^="bottom"] .arrow::after{border-width:0 0.5rem 0.5rem 0.5rem}.bs-popover-bottom .arrow::before,.bs-popover-auto[x-placement^="bottom"] .arrow::before{top:0;border-bottom-color:rgba(0,0,0,0.25)}.bs-popover-bottom .arrow::after,.bs-popover-auto[x-placement^="bottom"] .arrow::after{top:1px;border-bottom-color:#fff}.bs-popover-bottom .popover-header::before,.bs-popover-auto[x-placement^="bottom"] .popover-header::before{position:absolute;top:0;left:50%;display:block;width:1rem;margin-left:-0.5rem;content:"";border-bottom:1px solid #f7f7f7}.bs-popover-left,.bs-popover-auto[x-placement^="left"]{margin-right:0.5rem}.bs-popover-left .arrow,.bs-popover-auto[x-placement^="left"] .arrow{right:calc((0.5rem + 1px) * -1);width:0.5rem;height:1rem;margin:0.3rem 0}.bs-popover-left .arrow::before,.bs-popover-auto[x-placement^="left"] .arrow::before,.bs-popover-left .arrow::after,.bs-popover-auto[x-placement^="left"] .arrow::after{border-width:0.5rem 0 0.5rem 0.5rem}.bs-popover-left .arrow::before,.bs-popover-auto[x-placement^="left"] .arrow::before{right:0;border-left-color:rgba(0,0,0,0.25)}.bs-popover-left .arrow::after,.bs-popover-auto[x-placement^="left"] .arrow::after{right:1px;border-left-color:#fff}.popover-header{padding:0.5rem 0.75rem;margin-bottom:0;font-size:1rem;color:#2FA4E7;background-color:#f7f7f7;border-bottom:1px solid #ebebeb;border-top-left-radius:calc(0.3rem - 1px);border-top-right-radius:calc(0.3rem - 1px)}.popover-header:empty{display:none}.popover-body{padding:0.5rem 0.75rem;color:#495057}.carousel{position:relative}.carousel-inner{position:relative;width:100%;overflow:hidden}.carousel-item{position:relative;display:none;-webkit-box-align:center;-ms-flex-align:center;align-items:center;width:100%;-webkit-backface-visibility:hidden;backface-visibility:hidden;-webkit-perspective:1000px;perspective:1000px}.carousel-item.active,.carousel-item-next,.carousel-item-prev{display:block;-webkit-transition:-webkit-transform 0.6s ease;transition:-webkit-transform 0.6s ease;transition:transform 0.6s ease;transition:transform 0.6s ease, -webkit-transform 0.6s ease}@media screen and (prefers-reduced-motion: reduce){.carousel-item.active,.carousel-item-next,.carousel-item-prev{-webkit-transition:none;transition:none}}.carousel-item-next,.carousel-item-prev{position:absolute;top:0}.carousel-item-next.carousel-item-left,.carousel-item-prev.carousel-item-right{-webkit-transform:translateX(0);transform:translateX(0)}@supports (-webkit-transform-style: preserve-3d) or (transform-style: preserve-3d){.carousel-item-next.carousel-item-left,.carousel-item-prev.carousel-item-right{-webkit-transform:translate3d(0, 0, 0);transform:translate3d(0, 0, 0)}}.carousel-item-next,.active.carousel-item-right{-webkit-transform:translateX(100%);transform:translateX(100%)}@supports (-webkit-transform-style: preserve-3d) or (transform-style: preserve-3d){.carousel-item-next,.active.carousel-item-right{-webkit-transform:translate3d(100%, 0, 0);transform:translate3d(100%, 0, 0)}}.carousel-item-prev,.active.carousel-item-left{-webkit-transform:translateX(-100%);transform:translateX(-100%)}@supports (-webkit-transform-style: preserve-3d) or (transform-style: preserve-3d){.carousel-item-prev,.active.carousel-item-left{-webkit-transform:translate3d(-100%, 0, 0);transform:translate3d(-100%, 0, 0)}}.carousel-fade .carousel-item{opacity:0;-webkit-transition-duration:.6s;transition-duration:.6s;-webkit-transition-property:opacity;transition-property:opacity}.carousel-fade .carousel-item.active,.carousel-fade .carousel-item-next.carousel-item-left,.carousel-fade .carousel-item-prev.carousel-item-right{opacity:1}.carousel-fade .active.carousel-item-left,.carousel-fade .active.carousel-item-right{opacity:0}.carousel-fade .carousel-item-next,.carousel-fade .carousel-item-prev,.carousel-fade .carousel-item.active,.carousel-fade .active.carousel-item-left,.carousel-fade .active.carousel-item-prev{-webkit-transform:translateX(0);transform:translateX(0)}@supports (-webkit-transform-style: preserve-3d) or (transform-style: preserve-3d){.carousel-fade .carousel-item-next,.carousel-fade .carousel-item-prev,.carousel-fade .carousel-item.active,.carousel-fade .active.carousel-item-left,.carousel-fade .active.carousel-item-prev{-webkit-transform:translate3d(0, 0, 0);transform:translate3d(0, 0, 0)}}.carousel-control-prev,.carousel-control-next{position:absolute;top:0;bottom:0;display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-align:center;-ms-flex-align:center;align-items:center;-webkit-box-pack:center;-ms-flex-pack:center;justify-content:center;width:15%;color:#fff;text-align:center;opacity:0.5}.carousel-control-prev:hover,.carousel-control-prev:focus,.carousel-control-next:hover,.carousel-control-next:focus{color:#fff;text-decoration:none;outline:0;opacity:.9}.carousel-control-prev{left:0}.carousel-control-next{right:0}.carousel-control-prev-icon,.carousel-control-next-icon{display:inline-block;width:20px;height:20px;background:transparent no-repeat center center;background-size:100% 100%}.carousel-control-prev-icon{background-image:url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='%23fff' viewBox='0 0 8 8'%3E%3Cpath d='M5.25 0l-4 4 4 4 1.5-1.5-2.5-2.5 2.5-2.5-1.5-1.5z'/%3E%3C/svg%3E")}.carousel-control-next-icon{background-image:url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='%23fff' viewBox='0 0 8 8'%3E%3Cpath d='M2.75 0l-1.5 1.5 2.5 2.5-2.5 2.5 1.5 1.5 4-4-4-4z'/%3E%3C/svg%3E")}.carousel-indicators{position:absolute;right:0;bottom:10px;left:0;z-index:15;display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-pack:center;-ms-flex-pack:center;justify-content:center;padding-left:0;margin-right:15%;margin-left:15%;list-style:none}.carousel-indicators li{position:relative;-webkit-box-flex:0;-ms-flex:0 1 auto;flex:0 1 auto;width:30px;height:3px;margin-right:3px;margin-left:3px;text-indent:-999px;cursor:pointer;background-color:rgba(255,255,255,0.5)}.carousel-indicators li::before{position:absolute;top:-10px;left:0;display:inline-block;width:100%;height:10px;content:""}.carousel-indicators li::after{position:absolute;bottom:-10px;left:0;display:inline-block;width:100%;height:10px;content:""}.carousel-indicators .active{background-color:#fff}.carousel-caption{position:absolute;right:15%;bottom:20px;left:15%;z-index:10;padding-top:20px;padding-bottom:20px;color:#fff;text-align:center}.align-baseline{vertical-align:baseline !important}.align-top{vertical-align:top !important}.align-middle{vertical-align:middle !important}.align-bottom{vertical-align:bottom !important}.align-text-bottom{vertical-align:text-bottom !important}.align-text-top{vertical-align:text-top !important}.bg-primary{background-color:#2FA4E7 !important}a.bg-primary:hover,a.bg-primary:focus,button.bg-primary:hover,button.bg-primary:focus{background-color:#178acc !important}.bg-secondary{background-color:#e9ecef !important}a.bg-secondary:hover,a.bg-secondary:focus,button.bg-secondary:hover,button.bg-secondary:focus{background-color:#cbd3da !important}.bg-success{background-color:#73A839 !important}a.bg-success:hover,a.bg-success:focus,button.bg-success:hover,button.bg-success:focus{background-color:#59822c !important}.bg-info{background-color:#033C73 !important}a.bg-info:hover,a.bg-info:focus,button.bg-info:hover,button.bg-info:focus{background-color:#022241 !important}.bg-warning{background-color:#DD5600 !important}a.bg-warning:hover,a.bg-warning:focus,button.bg-warning:hover,button.bg-warning:focus{background-color:#aa4200 !important}.bg-danger{background-color:#C71C22 !important}a.bg-danger:hover,a.bg-danger:focus,button.bg-danger:hover,button.bg-danger:focus{background-color:#9a161a !important}.bg-light{background-color:#f8f9fa !important}a.bg-light:hover,a.bg-light:focus,button.bg-light:hover,button.bg-light:focus{background-color:#dae0e5 !important}.bg-dark{background-color:#343a40 !important}a.bg-dark:hover,a.bg-dark:focus,button.bg-dark:hover,button.bg-dark:focus{background-color:#1d2124 !important}.bg-white{background-color:#fff !important}.bg-transparent{background-color:transparent !important}.border{border:1px solid #dee2e6 !important}.border-top{border-top:1px solid #dee2e6 !important}.border-right{border-right:1px solid #dee2e6 !important}.border-bottom{border-bottom:1px solid #dee2e6 !important}.border-left{border-left:1px solid #dee2e6 !important}.border-0{border:0 !important}.border-top-0{border-top:0 !important}.border-right-0{border-right:0 !important}.border-bottom-0{border-bottom:0 !important}.border-left-0{border-left:0 !important}.border-primary{border-color:#2FA4E7 !important}.border-secondary{border-color:#e9ecef !important}.border-success{border-color:#73A839 !important}.border-info{border-color:#033C73 !important}.border-warning{border-color:#DD5600 !important}.border-danger{border-color:#C71C22 !important}.border-light{border-color:#f8f9fa !important}.border-dark{border-color:#343a40 !important}.border-white{border-color:#fff !important}.rounded{border-radius:0.25rem !important}.rounded-top{border-top-left-radius:0.25rem !important;border-top-right-radius:0.25rem !important}.rounded-right{border-top-right-radius:0.25rem !important;border-bottom-right-radius:0.25rem !important}.rounded-bottom{border-bottom-right-radius:0.25rem !important;border-bottom-left-radius:0.25rem !important}.rounded-left{border-top-left-radius:0.25rem !important;border-bottom-left-radius:0.25rem !important}.rounded-circle{border-radius:50% !important}.rounded-0{border-radius:0 !important}.clearfix::after{display:block;clear:both;content:""}.d-none{display:none !important}.d-inline{display:inline !important}.d-inline-block{display:inline-block !important}.d-block{display:block !important}.d-table{display:table !important}.d-table-row{display:table-row !important}.d-table-cell{display:table-cell !important}.d-flex{display:-webkit-box !important;display:-ms-flexbox !important;display:flex !important}.d-inline-flex{display:-webkit-inline-box !important;display:-ms-inline-flexbox !important;display:inline-flex !important}@media (min-width: 576px){.d-sm-none{display:none !important}.d-sm-inline{display:inline !important}.d-sm-inline-block{display:inline-block !important}.d-sm-block{display:block !important}.d-sm-table{display:table !important}.d-sm-table-row{display:table-row !important}.d-sm-table-cell{display:table-cell !important}.d-sm-flex{display:-webkit-box !important;display:-ms-flexbox !important;display:flex !important}.d-sm-inline-flex{display:-webkit-inline-box !important;display:-ms-inline-flexbox !important;display:inline-flex !important}}@media (min-width: 768px){.d-md-none{display:none !important}.d-md-inline{display:inline !important}.d-md-inline-block{display:inline-block !important}.d-md-block{display:block !important}.d-md-table{display:table !important}.d-md-table-row{display:table-row !important}.d-md-table-cell{display:table-cell !important}.d-md-flex{display:-webkit-box !important;display:-ms-flexbox !important;display:flex !important}.d-md-inline-flex{display:-webkit-inline-box !important;display:-ms-inline-flexbox !important;display:inline-flex !important}}@media (min-width: 992px){.d-lg-none{display:none !important}.d-lg-inline{display:inline !important}.d-lg-inline-block{display:inline-block !important}.d-lg-block{display:block !important}.d-lg-table{display:table !important}.d-lg-table-row{display:table-row !important}.d-lg-table-cell{display:table-cell !important}.d-lg-flex{display:-webkit-box !important;display:-ms-flexbox !important;display:flex !important}.d-lg-inline-flex{display:-webkit-inline-box !important;display:-ms-inline-flexbox !important;display:inline-flex !important}}@media (min-width: 1200px){.d-xl-none{display:none !important}.d-xl-inline{display:inline !important}.d-xl-inline-block{display:inline-block !important}.d-xl-block{display:block !important}.d-xl-table{display:table !important}.d-xl-table-row{display:table-row !important}.d-xl-table-cell{display:table-cell !important}.d-xl-flex{display:-webkit-box !important;display:-ms-flexbox !important;display:flex !important}.d-xl-inline-flex{display:-webkit-inline-box !important;display:-ms-inline-flexbox !important;display:inline-flex !important}}@media print{.d-print-none{display:none !important}.d-print-inline{display:inline !important}.d-print-inline-block{display:inline-block !important}.d-print-block{display:block !important}.d-print-table{display:table !important}.d-print-table-row{display:table-row !important}.d-print-table-cell{display:table-cell !important}.d-print-flex{display:-webkit-box !important;display:-ms-flexbox !important;display:flex !important}.d-print-inline-flex{display:-webkit-inline-box !important;display:-ms-inline-flexbox !important;display:inline-flex !important}}.embed-responsive{position:relative;display:block;width:100%;padding:0;overflow:hidden}.embed-responsive::before{display:block;content:""}.embed-responsive .embed-responsive-item,.embed-responsive iframe,.embed-responsive embed,.embed-responsive object,.embed-responsive video{position:absolute;top:0;bottom:0;left:0;width:100%;height:100%;border:0}.embed-responsive-21by9::before{padding-top:42.8571428571%}.embed-responsive-16by9::before{padding-top:56.25%}.embed-responsive-4by3::before{padding-top:75%}.embed-responsive-1by1::before{padding-top:100%}.flex-row{-webkit-box-orient:horizontal !important;-webkit-box-direction:normal !important;-ms-flex-direction:row !important;flex-direction:row !important}.flex-column{-webkit-box-orient:vertical !important;-webkit-box-direction:normal !important;-ms-flex-direction:column !important;flex-direction:column !important}.flex-row-reverse{-webkit-box-orient:horizontal !important;-webkit-box-direction:reverse !important;-ms-flex-direction:row-reverse !important;flex-direction:row-reverse !important}.flex-column-reverse{-webkit-box-orient:vertical !important;-webkit-box-direction:reverse !important;-ms-flex-direction:column-reverse !important;flex-direction:column-reverse !important}.flex-wrap{-ms-flex-wrap:wrap !important;flex-wrap:wrap !important}.flex-nowrap{-ms-flex-wrap:nowrap !important;flex-wrap:nowrap !important}.flex-wrap-reverse{-ms-flex-wrap:wrap-reverse !important;flex-wrap:wrap-reverse !important}.flex-fill{-webkit-box-flex:1 !important;-ms-flex:1 1 auto !important;flex:1 1 auto !important}.flex-grow-0{-webkit-box-flex:0 !important;-ms-flex-positive:0 !important;flex-grow:0 !important}.flex-grow-1{-webkit-box-flex:1 !important;-ms-flex-positive:1 !important;flex-grow:1 !important}.flex-shrink-0{-ms-flex-negative:0 !important;flex-shrink:0 !important}.flex-shrink-1{-ms-flex-negative:1 !important;flex-shrink:1 !important}.justify-content-start{-webkit-box-pack:start !important;-ms-flex-pack:start !important;justify-content:flex-start !important}.justify-content-end{-webkit-box-pack:end !important;-ms-flex-pack:end !important;justify-content:flex-end !important}.justify-content-center{-webkit-box-pack:center !important;-ms-flex-pack:center !important;justify-content:center !important}.justify-content-between{-webkit-box-pack:justify !important;-ms-flex-pack:justify !important;justify-content:space-between !important}.justify-content-around{-ms-flex-pack:distribute !important;justify-content:space-around !important}.align-items-start{-webkit-box-align:start !important;-ms-flex-align:start !important;align-items:flex-start !important}.align-items-end{-webkit-box-align:end !important;-ms-flex-align:end !important;align-items:flex-end !important}.align-items-center{-webkit-box-align:center !important;-ms-flex-align:center !important;align-items:center !important}.align-items-baseline{-webkit-box-align:baseline !important;-ms-flex-align:baseline !important;align-items:baseline !important}.align-items-stretch{-webkit-box-align:stretch !important;-ms-flex-align:stretch !important;align-items:stretch !important}.align-content-start{-ms-flex-line-pack:start !important;align-content:flex-start !important}.align-content-end{-ms-flex-line-pack:end !important;align-content:flex-end !important}.align-content-center{-ms-flex-line-pack:center !important;align-content:center !important}.align-content-between{-ms-flex-line-pack:justify !important;align-content:space-between !important}.align-content-around{-ms-flex-line-pack:distribute !important;align-content:space-around !important}.align-content-stretch{-ms-flex-line-pack:stretch !important;align-content:stretch !important}.align-self-auto{-ms-flex-item-align:auto !important;align-self:auto !important}.align-self-start{-ms-flex-item-align:start !important;align-self:flex-start !important}.align-self-end{-ms-flex-item-align:end !important;align-self:flex-end !important}.align-self-center{-ms-flex-item-align:center !important;align-self:center !important}.align-self-baseline{-ms-flex-item-align:baseline !important;align-self:baseline !important}.align-self-stretch{-ms-flex-item-align:stretch !important;align-self:stretch !important}@media (min-width: 576px){.flex-sm-row{-webkit-box-orient:horizontal !important;-webkit-box-direction:normal !important;-ms-flex-direction:row !important;flex-direction:row !important}.flex-sm-column{-webkit-box-orient:vertical !important;-webkit-box-direction:normal !important;-ms-flex-direction:column !important;flex-direction:column !important}.flex-sm-row-reverse{-webkit-box-orient:horizontal !important;-webkit-box-direction:reverse !important;-ms-flex-direction:row-reverse !important;flex-direction:row-reverse !important}.flex-sm-column-reverse{-webkit-box-orient:vertical !important;-webkit-box-direction:reverse !important;-ms-flex-direction:column-reverse !important;flex-direction:column-reverse !important}.flex-sm-wrap{-ms-flex-wrap:wrap !important;flex-wrap:wrap !important}.flex-sm-nowrap{-ms-flex-wrap:nowrap !important;flex-wrap:nowrap !important}.flex-sm-wrap-reverse{-ms-flex-wrap:wrap-reverse !important;flex-wrap:wrap-reverse !important}.flex-sm-fill{-webkit-box-flex:1 !important;-ms-flex:1 1 auto !important;flex:1 1 auto !important}.flex-sm-grow-0{-webkit-box-flex:0 !important;-ms-flex-positive:0 !important;flex-grow:0 !important}.flex-sm-grow-1{-webkit-box-flex:1 !important;-ms-flex-positive:1 !important;flex-grow:1 !important}.flex-sm-shrink-0{-ms-flex-negative:0 !important;flex-shrink:0 !important}.flex-sm-shrink-1{-ms-flex-negative:1 !important;flex-shrink:1 !important}.justify-content-sm-start{-webkit-box-pack:start !important;-ms-flex-pack:start !important;justify-content:flex-start !important}.justify-content-sm-end{-webkit-box-pack:end !important;-ms-flex-pack:end !important;justify-content:flex-end !important}.justify-content-sm-center{-webkit-box-pack:center !important;-ms-flex-pack:center !important;justify-content:center !important}.justify-content-sm-between{-webkit-box-pack:justify !important;-ms-flex-pack:justify !important;justify-content:space-between !important}.justify-content-sm-around{-ms-flex-pack:distribute !important;justify-content:space-around !important}.align-items-sm-start{-webkit-box-align:start !important;-ms-flex-align:start !important;align-items:flex-start !important}.align-items-sm-end{-webkit-box-align:end !important;-ms-flex-align:end !important;align-items:flex-end !important}.align-items-sm-center{-webkit-box-align:center !important;-ms-flex-align:center !important;align-items:center !important}.align-items-sm-baseline{-webkit-box-align:baseline !important;-ms-flex-align:baseline !important;align-items:baseline !important}.align-items-sm-stretch{-webkit-box-align:stretch !important;-ms-flex-align:stretch !important;align-items:stretch !important}.align-content-sm-start{-ms-flex-line-pack:start !important;align-content:flex-start !important}.align-content-sm-end{-ms-flex-line-pack:end !important;align-content:flex-end !important}.align-content-sm-center{-ms-flex-line-pack:center !important;align-content:center !important}.align-content-sm-between{-ms-flex-line-pack:justify !important;align-content:space-between !important}.align-content-sm-around{-ms-flex-line-pack:distribute !important;align-content:space-around !important}.align-content-sm-stretch{-ms-flex-line-pack:stretch !important;align-content:stretch !important}.align-self-sm-auto{-ms-flex-item-align:auto !important;align-self:auto !important}.align-self-sm-start{-ms-flex-item-align:start !important;align-self:flex-start !important}.align-self-sm-end{-ms-flex-item-align:end !important;align-self:flex-end !important}.align-self-sm-center{-ms-flex-item-align:center !important;align-self:center !important}.align-self-sm-baseline{-ms-flex-item-align:baseline !important;align-self:baseline !important}.align-self-sm-stretch{-ms-flex-item-align:stretch !important;align-self:stretch !important}}@media (min-width: 768px){.flex-md-row{-webkit-box-orient:horizontal !important;-webkit-box-direction:normal !important;-ms-flex-direction:row !important;flex-direction:row !important}.flex-md-column{-webkit-box-orient:vertical !important;-webkit-box-direction:normal !important;-ms-flex-direction:column !important;flex-direction:column !important}.flex-md-row-reverse{-webkit-box-orient:horizontal !important;-webkit-box-direction:reverse !important;-ms-flex-direction:row-reverse !important;flex-direction:row-reverse !important}.flex-md-column-reverse{-webkit-box-orient:vertical !important;-webkit-box-direction:reverse !important;-ms-flex-direction:column-reverse !important;flex-direction:column-reverse !important}.flex-md-wrap{-ms-flex-wrap:wrap !important;flex-wrap:wrap !important}.flex-md-nowrap{-ms-flex-wrap:nowrap !important;flex-wrap:nowrap !important}.flex-md-wrap-reverse{-ms-flex-wrap:wrap-reverse !important;flex-wrap:wrap-reverse !important}.flex-md-fill{-webkit-box-flex:1 !important;-ms-flex:1 1 auto !important;flex:1 1 auto !important}.flex-md-grow-0{-webkit-box-flex:0 !important;-ms-flex-positive:0 !important;flex-grow:0 !important}.flex-md-grow-1{-webkit-box-flex:1 !important;-ms-flex-positive:1 !important;flex-grow:1 !important}.flex-md-shrink-0{-ms-flex-negative:0 !important;flex-shrink:0 !important}.flex-md-shrink-1{-ms-flex-negative:1 !important;flex-shrink:1 !important}.justify-content-md-start{-webkit-box-pack:start !important;-ms-flex-pack:start !important;justify-content:flex-start !important}.justify-content-md-end{-webkit-box-pack:end !important;-ms-flex-pack:end !important;justify-content:flex-end !important}.justify-content-md-center{-webkit-box-pack:center !important;-ms-flex-pack:center !important;justify-content:center !important}.justify-content-md-between{-webkit-box-pack:justify !important;-ms-flex-pack:justify !important;justify-content:space-between !important}.justify-content-md-around{-ms-flex-pack:distribute !important;justify-content:space-around !important}.align-items-md-start{-webkit-box-align:start !important;-ms-flex-align:start !important;align-items:flex-start !important}.align-items-md-end{-webkit-box-align:end !important;-ms-flex-align:end !important;align-items:flex-end !important}.align-items-md-center{-webkit-box-align:center !important;-ms-flex-align:center !important;align-items:center !important}.align-items-md-baseline{-webkit-box-align:baseline !important;-ms-flex-align:baseline !important;align-items:baseline !important}.align-items-md-stretch{-webkit-box-align:stretch !important;-ms-flex-align:stretch !important;align-items:stretch !important}.align-content-md-start{-ms-flex-line-pack:start !important;align-content:flex-start !important}.align-content-md-end{-ms-flex-line-pack:end !important;align-content:flex-end !important}.align-content-md-center{-ms-flex-line-pack:center !important;align-content:center !important}.align-content-md-between{-ms-flex-line-pack:justify !important;align-content:space-between !important}.align-content-md-around{-ms-flex-line-pack:distribute !important;align-content:space-around !important}.align-content-md-stretch{-ms-flex-line-pack:stretch !important;align-content:stretch !important}.align-self-md-auto{-ms-flex-item-align:auto !important;align-self:auto !important}.align-self-md-start{-ms-flex-item-align:start !important;align-self:flex-start !important}.align-self-md-end{-ms-flex-item-align:end !important;align-self:flex-end !important}.align-self-md-center{-ms-flex-item-align:center !important;align-self:center !important}.align-self-md-baseline{-ms-flex-item-align:baseline !important;align-self:baseline !important}.align-self-md-stretch{-ms-flex-item-align:stretch !important;align-self:stretch !important}}@media (min-width: 992px){.flex-lg-row{-webkit-box-orient:horizontal !important;-webkit-box-direction:normal !important;-ms-flex-direction:row !important;flex-direction:row !important}.flex-lg-column{-webkit-box-orient:vertical !important;-webkit-box-direction:normal !important;-ms-flex-direction:column !important;flex-direction:column !important}.flex-lg-row-reverse{-webkit-box-orient:horizontal !important;-webkit-box-direction:reverse !important;-ms-flex-direction:row-reverse !important;flex-direction:row-reverse !important}.flex-lg-column-reverse{-webkit-box-orient:vertical !important;-webkit-box-direction:reverse !important;-ms-flex-direction:column-reverse !important;flex-direction:column-reverse !important}.flex-lg-wrap{-ms-flex-wrap:wrap !important;flex-wrap:wrap !important}.flex-lg-nowrap{-ms-flex-wrap:nowrap !important;flex-wrap:nowrap !important}.flex-lg-wrap-reverse{-ms-flex-wrap:wrap-reverse !important;flex-wrap:wrap-reverse !important}.flex-lg-fill{-webkit-box-flex:1 !important;-ms-flex:1 1 auto !important;flex:1 1 auto !important}.flex-lg-grow-0{-webkit-box-flex:0 !important;-ms-flex-positive:0 !important;flex-grow:0 !important}.flex-lg-grow-1{-webkit-box-flex:1 !important;-ms-flex-positive:1 !important;flex-grow:1 !important}.flex-lg-shrink-0{-ms-flex-negative:0 !important;flex-shrink:0 !important}.flex-lg-shrink-1{-ms-flex-negative:1 !important;flex-shrink:1 !important}.justify-content-lg-start{-webkit-box-pack:start !important;-ms-flex-pack:start !important;justify-content:flex-start !important}.justify-content-lg-end{-webkit-box-pack:end !important;-ms-flex-pack:end !important;justify-content:flex-end !important}.justify-content-lg-center{-webkit-box-pack:center !important;-ms-flex-pack:center !important;justify-content:center !important}.justify-content-lg-between{-webkit-box-pack:justify !important;-ms-flex-pack:justify !important;justify-content:space-between !important}.justify-content-lg-around{-ms-flex-pack:distribute !important;justify-content:space-around !important}.align-items-lg-start{-webkit-box-align:start !important;-ms-flex-align:start !important;align-items:flex-start !important}.align-items-lg-end{-webkit-box-align:end !important;-ms-flex-align:end !important;align-items:flex-end !important}.align-items-lg-center{-webkit-box-align:center !important;-ms-flex-align:center !important;align-items:center !important}.align-items-lg-baseline{-webkit-box-align:baseline !important;-ms-flex-align:baseline !important;align-items:baseline !important}.align-items-lg-stretch{-webkit-box-align:stretch !important;-ms-flex-align:stretch !important;align-items:stretch !important}.align-content-lg-start{-ms-flex-line-pack:start !important;align-content:flex-start !important}.align-content-lg-end{-ms-flex-line-pack:end !important;align-content:flex-end !important}.align-content-lg-center{-ms-flex-line-pack:center !important;align-content:center !important}.align-content-lg-between{-ms-flex-line-pack:justify !important;align-content:space-between !important}.align-content-lg-around{-ms-flex-line-pack:distribute !important;align-content:space-around !important}.align-content-lg-stretch{-ms-flex-line-pack:stretch !important;align-content:stretch !important}.align-self-lg-auto{-ms-flex-item-align:auto !important;align-self:auto !important}.align-self-lg-start{-ms-flex-item-align:start !important;align-self:flex-start !important}.align-self-lg-end{-ms-flex-item-align:end !important;align-self:flex-end !important}.align-self-lg-center{-ms-flex-item-align:center !important;align-self:center !important}.align-self-lg-baseline{-ms-flex-item-align:baseline !important;align-self:baseline !important}.align-self-lg-stretch{-ms-flex-item-align:stretch !important;align-self:stretch !important}}@media (min-width: 1200px){.flex-xl-row{-webkit-box-orient:horizontal !important;-webkit-box-direction:normal !important;-ms-flex-direction:row !important;flex-direction:row !important}.flex-xl-column{-webkit-box-orient:vertical !important;-webkit-box-direction:normal !important;-ms-flex-direction:column !important;flex-direction:column !important}.flex-xl-row-reverse{-webkit-box-orient:horizontal !important;-webkit-box-direction:reverse !important;-ms-flex-direction:row-reverse !important;flex-direction:row-reverse !important}.flex-xl-column-reverse{-webkit-box-orient:vertical !important;-webkit-box-direction:reverse !important;-ms-flex-direction:column-reverse !important;flex-direction:column-reverse !important}.flex-xl-wrap{-ms-flex-wrap:wrap !important;flex-wrap:wrap !important}.flex-xl-nowrap{-ms-flex-wrap:nowrap !important;flex-wrap:nowrap !important}.flex-xl-wrap-reverse{-ms-flex-wrap:wrap-reverse !important;flex-wrap:wrap-reverse !important}.flex-xl-fill{-webkit-box-flex:1 !important;-ms-flex:1 1 auto !important;flex:1 1 auto !important}.flex-xl-grow-0{-webkit-box-flex:0 !important;-ms-flex-positive:0 !important;flex-grow:0 !important}.flex-xl-grow-1{-webkit-box-flex:1 !important;-ms-flex-positive:1 !important;flex-grow:1 !important}.flex-xl-shrink-0{-ms-flex-negative:0 !important;flex-shrink:0 !important}.flex-xl-shrink-1{-ms-flex-negative:1 !important;flex-shrink:1 !important}.justify-content-xl-start{-webkit-box-pack:start !important;-ms-flex-pack:start !important;justify-content:flex-start !important}.justify-content-xl-end{-webkit-box-pack:end !important;-ms-flex-pack:end !important;justify-content:flex-end !important}.justify-content-xl-center{-webkit-box-pack:center !important;-ms-flex-pack:center !important;justify-content:center !important}.justify-content-xl-between{-webkit-box-pack:justify !important;-ms-flex-pack:justify !important;justify-content:space-between !important}.justify-content-xl-around{-ms-flex-pack:distribute !important;justify-content:space-around !important}.align-items-xl-start{-webkit-box-align:start !important;-ms-flex-align:start !important;align-items:flex-start !important}.align-items-xl-end{-webkit-box-align:end !important;-ms-flex-align:end !important;align-items:flex-end !important}.align-items-xl-center{-webkit-box-align:center !important;-ms-flex-align:center !important;align-items:center !important}.align-items-xl-baseline{-webkit-box-align:baseline !important;-ms-flex-align:baseline !important;align-items:baseline !important}.align-items-xl-stretch{-webkit-box-align:stretch !important;-ms-flex-align:stretch !important;align-items:stretch !important}.align-content-xl-start{-ms-flex-line-pack:start !important;align-content:flex-start !important}.align-content-xl-end{-ms-flex-line-pack:end !important;align-content:flex-end !important}.align-content-xl-center{-ms-flex-line-pack:center !important;align-content:center !important}.align-content-xl-between{-ms-flex-line-pack:justify !important;align-content:space-between !important}.align-content-xl-around{-ms-flex-line-pack:distribute !important;align-content:space-around !important}.align-content-xl-stretch{-ms-flex-line-pack:stretch !important;align-content:stretch !important}.align-self-xl-auto{-ms-flex-item-align:auto !important;align-self:auto !important}.align-self-xl-start{-ms-flex-item-align:start !important;align-self:flex-start !important}.align-self-xl-end{-ms-flex-item-align:end !important;align-self:flex-end !important}.align-self-xl-center{-ms-flex-item-align:center !important;align-self:center !important}.align-self-xl-baseline{-ms-flex-item-align:baseline !important;align-self:baseline !important}.align-self-xl-stretch{-ms-flex-item-align:stretch !important;align-self:stretch !important}}.float-left{float:left !important}.float-right{float:right !important}.float-none{float:none !important}@media (min-width: 576px){.float-sm-left{float:left !important}.float-sm-right{float:right !important}.float-sm-none{float:none !important}}@media (min-width: 768px){.float-md-left{float:left !important}.float-md-right{float:right !important}.float-md-none{float:none !important}}@media (min-width: 992px){.float-lg-left{float:left !important}.float-lg-right{float:right !important}.float-lg-none{float:none !important}}@media (min-width: 1200px){.float-xl-left{float:left !important}.float-xl-right{float:right !important}.float-xl-none{float:none !important}}.position-static{position:static !important}.position-relative{position:relative !important}.position-absolute{position:absolute !important}.position-fixed{position:fixed !important}.position-sticky{position:-webkit-sticky !important;position:sticky !important}.fixed-top{position:fixed;top:0;right:0;left:0;z-index:1030}.fixed-bottom{position:fixed;right:0;bottom:0;left:0;z-index:1030}@supports (position: -webkit-sticky) or (position: sticky){.sticky-top{position:-webkit-sticky;position:sticky;top:0;z-index:1020}}.sr-only{position:absolute;width:1px;height:1px;padding:0;overflow:hidden;clip:rect(0, 0, 0, 0);white-space:nowrap;border:0}.sr-only-focusable:active,.sr-only-focusable:focus{position:static;width:auto;height:auto;overflow:visible;clip:auto;white-space:normal}.shadow-sm{-webkit-box-shadow:0 0.125rem 0.25rem rgba(0,0,0,0.075) !important;box-shadow:0 0.125rem 0.25rem rgba(0,0,0,0.075) !important}.shadow{-webkit-box-shadow:0 0.5rem 1rem rgba(0,0,0,0.15) !important;box-shadow:0 0.5rem 1rem rgba(0,0,0,0.15) !important}.shadow-lg{-webkit-box-shadow:0 1rem 3rem rgba(0,0,0,0.175) !important;box-shadow:0 1rem 3rem rgba(0,0,0,0.175) !important}.shadow-none{-webkit-box-shadow:none !important;box-shadow:none !important}.w-25{width:25% !important}.w-50{width:50% !important}.w-75{width:75% !important}.w-100{width:100% !important}.w-auto{width:auto !important}.h-25{height:25% !important}.h-50{height:50% !important}.h-75{height:75% !important}.h-100{height:100% !important}.h-auto{height:auto !important}.mw-100{max-width:100% !important}.mh-100{max-height:100% !important}.m-0{margin:0 !important}.mt-0,.my-0{margin-top:0 !important}.mr-0,.mx-0{margin-right:0 !important}.mb-0,.my-0{margin-bottom:0 !important}.ml-0,.mx-0{margin-left:0 !important}.m-1{margin:0.25rem !important}.mt-1,.my-1{margin-top:0.25rem !important}.mr-1,.mx-1{margin-right:0.25rem !important}.mb-1,.my-1{margin-bottom:0.25rem !important}.ml-1,.mx-1{margin-left:0.25rem !important}.m-2{margin:0.5rem !important}.mt-2,.my-2{margin-top:0.5rem !important}.mr-2,.mx-2{margin-right:0.5rem !important}.mb-2,.my-2{margin-bottom:0.5rem !important}.ml-2,.mx-2{margin-left:0.5rem !important}.m-3{margin:1rem !important}.mt-3,.my-3{margin-top:1rem !important}.mr-3,.mx-3{margin-right:1rem !important}.mb-3,.my-3{margin-bottom:1rem !important}.ml-3,.mx-3{margin-left:1rem !important}.m-4{margin:1.5rem !important}.mt-4,.my-4{margin-top:1.5rem !important}.mr-4,.mx-4{margin-right:1.5rem !important}.mb-4,.my-4{margin-bottom:1.5rem !important}.ml-4,.mx-4{margin-left:1.5rem !important}.m-5{margin:3rem !important}.mt-5,.my-5{margin-top:3rem !important}.mr-5,.mx-5{margin-right:3rem !important}.mb-5,.my-5{margin-bottom:3rem !important}.ml-5,.mx-5{margin-left:3rem !important}.p-0{padding:0 !important}.pt-0,.py-0{padding-top:0 !important}.pr-0,.px-0{padding-right:0 !important}.pb-0,.py-0{padding-bottom:0 !important}.pl-0,.px-0{padding-left:0 !important}.p-1{padding:0.25rem !important}.pt-1,.py-1{padding-top:0.25rem !important}.pr-1,.px-1{padding-right:0.25rem !important}.pb-1,.py-1{padding-bottom:0.25rem !important}.pl-1,.px-1{padding-left:0.25rem !important}.p-2{padding:0.5rem !important}.pt-2,.py-2{padding-top:0.5rem !important}.pr-2,.px-2{padding-right:0.5rem !important}.pb-2,.py-2{padding-bottom:0.5rem !important}.pl-2,.px-2{padding-left:0.5rem !important}.p-3{padding:1rem !important}.pt-3,.py-3{padding-top:1rem !important}.pr-3,.px-3{padding-right:1rem !important}.pb-3,.py-3{padding-bottom:1rem !important}.pl-3,.px-3{padding-left:1rem !important}.p-4{padding:1.5rem !important}.pt-4,.py-4{padding-top:1.5rem !important}.pr-4,.px-4{padding-right:1.5rem !important}.pb-4,.py-4{padding-bottom:1.5rem !important}.pl-4,.px-4{padding-left:1.5rem !important}.p-5{padding:3rem !important}.pt-5,.py-5{padding-top:3rem !important}.pr-5,.px-5{padding-right:3rem !important}.pb-5,.py-5{padding-bottom:3rem !important}.pl-5,.px-5{padding-left:3rem !important}.m-auto{margin:auto !important}.mt-auto,.my-auto{margin-top:auto !important}.mr-auto,.mx-auto{margin-right:auto !important}.mb-auto,.my-auto{margin-bottom:auto !important}.ml-auto,.mx-auto{margin-left:auto !important}@media (min-width: 576px){.m-sm-0{margin:0 !important}.mt-sm-0,.my-sm-0{margin-top:0 !important}.mr-sm-0,.mx-sm-0{margin-right:0 !important}.mb-sm-0,.my-sm-0{margin-bottom:0 !important}.ml-sm-0,.mx-sm-0{margin-left:0 !important}.m-sm-1{margin:0.25rem !important}.mt-sm-1,.my-sm-1{margin-top:0.25rem !important}.mr-sm-1,.mx-sm-1{margin-right:0.25rem !important}.mb-sm-1,.my-sm-1{margin-bottom:0.25rem !important}.ml-sm-1,.mx-sm-1{margin-left:0.25rem !important}.m-sm-2{margin:0.5rem !important}.mt-sm-2,.my-sm-2{margin-top:0.5rem !important}.mr-sm-2,.mx-sm-2{margin-right:0.5rem !important}.mb-sm-2,.my-sm-2{margin-bottom:0.5rem !important}.ml-sm-2,.mx-sm-2{margin-left:0.5rem !important}.m-sm-3{margin:1rem !important}.mt-sm-3,.my-sm-3{margin-top:1rem !important}.mr-sm-3,.mx-sm-3{margin-right:1rem !important}.mb-sm-3,.my-sm-3{margin-bottom:1rem !important}.ml-sm-3,.mx-sm-3{margin-left:1rem !important}.m-sm-4{margin:1.5rem !important}.mt-sm-4,.my-sm-4{margin-top:1.5rem !important}.mr-sm-4,.mx-sm-4{margin-right:1.5rem !important}.mb-sm-4,.my-sm-4{margin-bottom:1.5rem !important}.ml-sm-4,.mx-sm-4{margin-left:1.5rem !important}.m-sm-5{margin:3rem !important}.mt-sm-5,.my-sm-5{margin-top:3rem !important}.mr-sm-5,.mx-sm-5{margin-right:3rem !important}.mb-sm-5,.my-sm-5{margin-bottom:3rem !important}.ml-sm-5,.mx-sm-5{margin-left:3rem !important}.p-sm-0{padding:0 !important}.pt-sm-0,.py-sm-0{padding-top:0 !important}.pr-sm-0,.px-sm-0{padding-right:0 !important}.pb-sm-0,.py-sm-0{padding-bottom:0 !important}.pl-sm-0,.px-sm-0{padding-left:0 !important}.p-sm-1{padding:0.25rem !important}.pt-sm-1,.py-sm-1{padding-top:0.25rem !important}.pr-sm-1,.px-sm-1{padding-right:0.25rem !important}.pb-sm-1,.py-sm-1{padding-bottom:0.25rem !important}.pl-sm-1,.px-sm-1{padding-left:0.25rem !important}.p-sm-2{padding:0.5rem !important}.pt-sm-2,.py-sm-2{padding-top:0.5rem !important}.pr-sm-2,.px-sm-2{padding-right:0.5rem !important}.pb-sm-2,.py-sm-2{padding-bottom:0.5rem !important}.pl-sm-2,.px-sm-2{padding-left:0.5rem !important}.p-sm-3{padding:1rem !important}.pt-sm-3,.py-sm-3{padding-top:1rem !important}.pr-sm-3,.px-sm-3{padding-right:1rem !important}.pb-sm-3,.py-sm-3{padding-bottom:1rem !important}.pl-sm-3,.px-sm-3{padding-left:1rem !important}.p-sm-4{padding:1.5rem !important}.pt-sm-4,.py-sm-4{padding-top:1.5rem !important}.pr-sm-4,.px-sm-4{padding-right:1.5rem !important}.pb-sm-4,.py-sm-4{padding-bottom:1.5rem !important}.pl-sm-4,.px-sm-4{padding-left:1.5rem !important}.p-sm-5{padding:3rem !important}.pt-sm-5,.py-sm-5{padding-top:3rem !important}.pr-sm-5,.px-sm-5{padding-right:3rem !important}.pb-sm-5,.py-sm-5{padding-bottom:3rem !important}.pl-sm-5,.px-sm-5{padding-left:3rem !important}.m-sm-auto{margin:auto !important}.mt-sm-auto,.my-sm-auto{margin-top:auto !important}.mr-sm-auto,.mx-sm-auto{margin-right:auto !important}.mb-sm-auto,.my-sm-auto{margin-bottom:auto !important}.ml-sm-auto,.mx-sm-auto{margin-left:auto !important}}@media (min-width: 768px){.m-md-0{margin:0 !important}.mt-md-0,.my-md-0{margin-top:0 !important}.mr-md-0,.mx-md-0{margin-right:0 !important}.mb-md-0,.my-md-0{margin-bottom:0 !important}.ml-md-0,.mx-md-0{margin-left:0 !important}.m-md-1{margin:0.25rem !important}.mt-md-1,.my-md-1{margin-top:0.25rem !important}.mr-md-1,.mx-md-1{margin-right:0.25rem !important}.mb-md-1,.my-md-1{margin-bottom:0.25rem !important}.ml-md-1,.mx-md-1{margin-left:0.25rem !important}.m-md-2{margin:0.5rem !important}.mt-md-2,.my-md-2{margin-top:0.5rem !important}.mr-md-2,.mx-md-2{margin-right:0.5rem !important}.mb-md-2,.my-md-2{margin-bottom:0.5rem !important}.ml-md-2,.mx-md-2{margin-left:0.5rem !important}.m-md-3{margin:1rem !important}.mt-md-3,.my-md-3{margin-top:1rem !important}.mr-md-3,.mx-md-3{margin-right:1rem !important}.mb-md-3,.my-md-3{margin-bottom:1rem !important}.ml-md-3,.mx-md-3{margin-left:1rem !important}.m-md-4{margin:1.5rem !important}.mt-md-4,.my-md-4{margin-top:1.5rem !important}.mr-md-4,.mx-md-4{margin-right:1.5rem !important}.mb-md-4,.my-md-4{margin-bottom:1.5rem !important}.ml-md-4,.mx-md-4{margin-left:1.5rem !important}.m-md-5{margin:3rem !important}.mt-md-5,.my-md-5{margin-top:3rem !important}.mr-md-5,.mx-md-5{margin-right:3rem !important}.mb-md-5,.my-md-5{margin-bottom:3rem !important}.ml-md-5,.mx-md-5{margin-left:3rem !important}.p-md-0{padding:0 !important}.pt-md-0,.py-md-0{padding-top:0 !important}.pr-md-0,.px-md-0{padding-right:0 !important}.pb-md-0,.py-md-0{padding-bottom:0 !important}.pl-md-0,.px-md-0{padding-left:0 !important}.p-md-1{padding:0.25rem !important}.pt-md-1,.py-md-1{padding-top:0.25rem !important}.pr-md-1,.px-md-1{padding-right:0.25rem !important}.pb-md-1,.py-md-1{padding-bottom:0.25rem !important}.pl-md-1,.px-md-1{padding-left:0.25rem !important}.p-md-2{padding:0.5rem !important}.pt-md-2,.py-md-2{padding-top:0.5rem !important}.pr-md-2,.px-md-2{padding-right:0.5rem !important}.pb-md-2,.py-md-2{padding-bottom:0.5rem !important}.pl-md-2,.px-md-2{padding-left:0.5rem !important}.p-md-3{padding:1rem !important}.pt-md-3,.py-md-3{padding-top:1rem !important}.pr-md-3,.px-md-3{padding-right:1rem !important}.pb-md-3,.py-md-3{padding-bottom:1rem !important}.pl-md-3,.px-md-3{padding-left:1rem !important}.p-md-4{padding:1.5rem !important}.pt-md-4,.py-md-4{padding-top:1.5rem !important}.pr-md-4,.px-md-4{padding-right:1.5rem !important}.pb-md-4,.py-md-4{padding-bottom:1.5rem !important}.pl-md-4,.px-md-4{padding-left:1.5rem !important}.p-md-5{padding:3rem !important}.pt-md-5,.py-md-5{padding-top:3rem !important}.pr-md-5,.px-md-5{padding-right:3rem !important}.pb-md-5,.py-md-5{padding-bottom:3rem !important}.pl-md-5,.px-md-5{padding-left:3rem !important}.m-md-auto{margin:auto !important}.mt-md-auto,.my-md-auto{margin-top:auto !important}.mr-md-auto,.mx-md-auto{margin-right:auto !important}.mb-md-auto,.my-md-auto{margin-bottom:auto !important}.ml-md-auto,.mx-md-auto{margin-left:auto !important}}@media (min-width: 992px){.m-lg-0{margin:0 !important}.mt-lg-0,.my-lg-0{margin-top:0 !important}.mr-lg-0,.mx-lg-0{margin-right:0 !important}.mb-lg-0,.my-lg-0{margin-bottom:0 !important}.ml-lg-0,.mx-lg-0{margin-left:0 !important}.m-lg-1{margin:0.25rem !important}.mt-lg-1,.my-lg-1{margin-top:0.25rem !important}.mr-lg-1,.mx-lg-1{margin-right:0.25rem !important}.mb-lg-1,.my-lg-1{margin-bottom:0.25rem !important}.ml-lg-1,.mx-lg-1{margin-left:0.25rem !important}.m-lg-2{margin:0.5rem !important}.mt-lg-2,.my-lg-2{margin-top:0.5rem !important}.mr-lg-2,.mx-lg-2{margin-right:0.5rem !important}.mb-lg-2,.my-lg-2{margin-bottom:0.5rem !important}.ml-lg-2,.mx-lg-2{margin-left:0.5rem !important}.m-lg-3{margin:1rem !important}.mt-lg-3,.my-lg-3{margin-top:1rem !important}.mr-lg-3,.mx-lg-3{margin-right:1rem !important}.mb-lg-3,.my-lg-3{margin-bottom:1rem !important}.ml-lg-3,.mx-lg-3{margin-left:1rem !important}.m-lg-4{margin:1.5rem !important}.mt-lg-4,.my-lg-4{margin-top:1.5rem !important}.mr-lg-4,.mx-lg-4{margin-right:1.5rem !important}.mb-lg-4,.my-lg-4{margin-bottom:1.5rem !important}.ml-lg-4,.mx-lg-4{margin-left:1.5rem !important}.m-lg-5{margin:3rem !important}.mt-lg-5,.my-lg-5{margin-top:3rem !important}.mr-lg-5,.mx-lg-5{margin-right:3rem !important}.mb-lg-5,.my-lg-5{margin-bottom:3rem !important}.ml-lg-5,.mx-lg-5{margin-left:3rem !important}.p-lg-0{padding:0 !important}.pt-lg-0,.py-lg-0{padding-top:0 !important}.pr-lg-0,.px-lg-0{padding-right:0 !important}.pb-lg-0,.py-lg-0{padding-bottom:0 !important}.pl-lg-0,.px-lg-0{padding-left:0 !important}.p-lg-1{padding:0.25rem !important}.pt-lg-1,.py-lg-1{padding-top:0.25rem !important}.pr-lg-1,.px-lg-1{padding-right:0.25rem !important}.pb-lg-1,.py-lg-1{padding-bottom:0.25rem !important}.pl-lg-1,.px-lg-1{padding-left:0.25rem !important}.p-lg-2{padding:0.5rem !important}.pt-lg-2,.py-lg-2{padding-top:0.5rem !important}.pr-lg-2,.px-lg-2{padding-right:0.5rem !important}.pb-lg-2,.py-lg-2{padding-bottom:0.5rem !important}.pl-lg-2,.px-lg-2{padding-left:0.5rem !important}.p-lg-3{padding:1rem !important}.pt-lg-3,.py-lg-3{padding-top:1rem !important}.pr-lg-3,.px-lg-3{padding-right:1rem !important}.pb-lg-3,.py-lg-3{padding-bottom:1rem !important}.pl-lg-3,.px-lg-3{padding-left:1rem !important}.p-lg-4{padding:1.5rem !important}.pt-lg-4,.py-lg-4{padding-top:1.5rem !important}.pr-lg-4,.px-lg-4{padding-right:1.5rem !important}.pb-lg-4,.py-lg-4{padding-bottom:1.5rem !important}.pl-lg-4,.px-lg-4{padding-left:1.5rem !important}.p-lg-5{padding:3rem !important}.pt-lg-5,.py-lg-5{padding-top:3rem !important}.pr-lg-5,.px-lg-5{padding-right:3rem !important}.pb-lg-5,.py-lg-5{padding-bottom:3rem !important}.pl-lg-5,.px-lg-5{padding-left:3rem !important}.m-lg-auto{margin:auto !important}.mt-lg-auto,.my-lg-auto{margin-top:auto !important}.mr-lg-auto,.mx-lg-auto{margin-right:auto !important}.mb-lg-auto,.my-lg-auto{margin-bottom:auto !important}.ml-lg-auto,.mx-lg-auto{margin-left:auto !important}}@media (min-width: 1200px){.m-xl-0{margin:0 !important}.mt-xl-0,.my-xl-0{margin-top:0 !important}.mr-xl-0,.mx-xl-0{margin-right:0 !important}.mb-xl-0,.my-xl-0{margin-bottom:0 !important}.ml-xl-0,.mx-xl-0{margin-left:0 !important}.m-xl-1{margin:0.25rem !important}.mt-xl-1,.my-xl-1{margin-top:0.25rem !important}.mr-xl-1,.mx-xl-1{margin-right:0.25rem !important}.mb-xl-1,.my-xl-1{margin-bottom:0.25rem !important}.ml-xl-1,.mx-xl-1{margin-left:0.25rem !important}.m-xl-2{margin:0.5rem !important}.mt-xl-2,.my-xl-2{margin-top:0.5rem !important}.mr-xl-2,.mx-xl-2{margin-right:0.5rem !important}.mb-xl-2,.my-xl-2{margin-bottom:0.5rem !important}.ml-xl-2,.mx-xl-2{margin-left:0.5rem !important}.m-xl-3{margin:1rem !important}.mt-xl-3,.my-xl-3{margin-top:1rem !important}.mr-xl-3,.mx-xl-3{margin-right:1rem !important}.mb-xl-3,.my-xl-3{margin-bottom:1rem !important}.ml-xl-3,.mx-xl-3{margin-left:1rem !important}.m-xl-4{margin:1.5rem !important}.mt-xl-4,.my-xl-4{margin-top:1.5rem !important}.mr-xl-4,.mx-xl-4{margin-right:1.5rem !important}.mb-xl-4,.my-xl-4{margin-bottom:1.5rem !important}.ml-xl-4,.mx-xl-4{margin-left:1.5rem !important}.m-xl-5{margin:3rem !important}.mt-xl-5,.my-xl-5{margin-top:3rem !important}.mr-xl-5,.mx-xl-5{margin-right:3rem !important}.mb-xl-5,.my-xl-5{margin-bottom:3rem !important}.ml-xl-5,.mx-xl-5{margin-left:3rem !important}.p-xl-0{padding:0 !important}.pt-xl-0,.py-xl-0{padding-top:0 !important}.pr-xl-0,.px-xl-0{padding-right:0 !important}.pb-xl-0,.py-xl-0{padding-bottom:0 !important}.pl-xl-0,.px-xl-0{padding-left:0 !important}.p-xl-1{padding:0.25rem !important}.pt-xl-1,.py-xl-1{padding-top:0.25rem !important}.pr-xl-1,.px-xl-1{padding-right:0.25rem !important}.pb-xl-1,.py-xl-1{padding-bottom:0.25rem !important}.pl-xl-1,.px-xl-1{padding-left:0.25rem !important}.p-xl-2{padding:0.5rem !important}.pt-xl-2,.py-xl-2{padding-top:0.5rem !important}.pr-xl-2,.px-xl-2{padding-right:0.5rem !important}.pb-xl-2,.py-xl-2{padding-bottom:0.5rem !important}.pl-xl-2,.px-xl-2{padding-left:0.5rem !important}.p-xl-3{padding:1rem !important}.pt-xl-3,.py-xl-3{padding-top:1rem !important}.pr-xl-3,.px-xl-3{padding-right:1rem !important}.pb-xl-3,.py-xl-3{padding-bottom:1rem !important}.pl-xl-3,.px-xl-3{padding-left:1rem !important}.p-xl-4{padding:1.5rem !important}.pt-xl-4,.py-xl-4{padding-top:1.5rem !important}.pr-xl-4,.px-xl-4{padding-right:1.5rem !important}.pb-xl-4,.py-xl-4{padding-bottom:1.5rem !important}.pl-xl-4,.px-xl-4{padding-left:1.5rem !important}.p-xl-5{padding:3rem !important}.pt-xl-5,.py-xl-5{padding-top:3rem !important}.pr-xl-5,.px-xl-5{padding-right:3rem !important}.pb-xl-5,.py-xl-5{padding-bottom:3rem !important}.pl-xl-5,.px-xl-5{padding-left:3rem !important}.m-xl-auto{margin:auto !important}.mt-xl-auto,.my-xl-auto{margin-top:auto !important}.mr-xl-auto,.mx-xl-auto{margin-right:auto !important}.mb-xl-auto,.my-xl-auto{margin-bottom:auto !important}.ml-xl-auto,.mx-xl-auto{margin-left:auto !important}}.text-monospace{font-family:SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace}.text-justify{text-align:justify !important}.text-nowrap{white-space:nowrap !important}.text-truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.text-left{text-align:left !important}.text-right{text-align:right !important}.text-center{text-align:center !important}@media (min-width: 576px){.text-sm-left{text-align:left !important}.text-sm-right{text-align:right !important}.text-sm-center{text-align:center !important}}@media (min-width: 768px){.text-md-left{text-align:left !important}.text-md-right{text-align:right !important}.text-md-center{text-align:center !important}}@media (min-width: 992px){.text-lg-left{text-align:left !important}.text-lg-right{text-align:right !important}.text-lg-center{text-align:center !important}}@media (min-width: 1200px){.text-xl-left{text-align:left !important}.text-xl-right{text-align:right !important}.text-xl-center{text-align:center !important}}.text-lowercase{text-transform:lowercase !important}.text-uppercase{text-transform:uppercase !important}.text-capitalize{text-transform:capitalize !important}.font-weight-light{font-weight:300 !important}.font-weight-normal{font-weight:400 !important}.font-weight-bold{font-weight:700 !important}.font-italic{font-style:italic !important}.text-white{color:#fff !important}.text-primary{color:#2FA4E7 !important}a.text-primary:hover,a.text-primary:focus{color:#178acc !important}.text-secondary{color:#e9ecef !important}a.text-secondary:hover,a.text-secondary:focus{color:#cbd3da !important}.text-success{color:#73A839 !important}a.text-success:hover,a.text-success:focus{color:#59822c !important}.text-info{color:#033C73 !important}a.text-info:hover,a.text-info:focus{color:#022241 !important}.text-warning{color:#DD5600 !important}a.text-warning:hover,a.text-warning:focus{color:#aa4200 !important}.text-danger{color:#C71C22 !important}a.text-danger:hover,a.text-danger:focus{color:#9a161a !important}.text-light{color:#f8f9fa !important}a.text-light:hover,a.text-light:focus{color:#dae0e5 !important}.text-dark{color:#343a40 !important}a.text-dark:hover,a.text-dark:focus{color:#1d2124 !important}.text-body{color:#495057 !important}.text-muted{color:#868e96 !important}.text-black-50{color:rgba(0,0,0,0.5) !important}.text-white-50{color:rgba(255,255,255,0.5) !important}.text-hide{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.visible{visibility:visible !important}.invisible{visibility:hidden !important}@media print{*,*::before,*::after{text-shadow:none !important;-webkit-box-shadow:none !important;box-shadow:none !important}a:not(.btn){text-decoration:underline}abbr[title]::after{content:" (" attr(title) ")"}pre{white-space:pre-wrap !important}pre,blockquote{border:1px solid #adb5bd;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}p,h2,h3{orphans:3;widows:3}h2,h3{page-break-after:avoid}@page{size:a3}body{min-width:992px !important}.container{min-width:992px !important}.navbar{display:none}.badge{border:1px solid #000}.table{border-collapse:collapse !important}.table td,.table th{background-color:#fff !important}.table-bordered th,.table-bordered td{border:1px solid #dee2e6 !important}.table-dark{color:inherit}.table-dark th,.table-dark td,.table-dark thead th,.table-dark tbody+tbody{border-color:#dee2e6}.table .thead-dark th{color:inherit;border-color:#dee2e6}}.bg-primary{background-image:-webkit-gradient(linear, left top, left bottom, from(#54b4eb), color-stop(60%, #2FA4E7), to(#1d9ce5));background-image:linear-gradient(#54b4eb, #2FA4E7 60%, #1d9ce5);background-repeat:no-repeat}.bg-dark{background-image:-webkit-gradient(linear, left top, left bottom, from(#04519b), color-stop(60%, #033C73), to(#02325f));background-image:linear-gradient(#04519b, #033C73 60%, #02325f);background-repeat:no-repeat}.bg-light{background-image:-webkit-gradient(linear, left top, left bottom, from(white), color-stop(60%, #e9ecef), to(#e3e7eb));background-image:linear-gradient(white, #e9ecef 60%, #e3e7eb);background-repeat:no-repeat}.navbar-brand,.nav-link{text-shadow:0 1px 0 rgba(0,0,0,0.05)}.btn{text-shadow:0 1px 0 rgba(0,0,0,0.05)}.btn-primary{background-image:-webkit-gradient(linear, left top, left bottom, from(#54b4eb), color-stop(60%, #2FA4E7), to(#1d9ce5));background-image:linear-gradient(#54b4eb, #2FA4E7 60%, #1d9ce5);background-repeat:no-repeat}.btn-secondary{background-image:-webkit-gradient(linear, left top, left bottom, from(white), color-stop(60%, #e9ecef), to(#dde2e6));background-image:linear-gradient(white, #e9ecef 60%, #dde2e6);background-repeat:no-repeat;color:#495057}.btn-success{background-image:-webkit-gradient(linear, left top, left bottom, from(#88c149), color-stop(60%, #73A839), to(#699934));background-image:linear-gradient(#88c149, #73A839 60%, #699934);background-repeat:no-repeat}.btn-info{background-image:-webkit-gradient(linear, left top, left bottom, from(#04519b), color-stop(60%, #033C73), to(#02325f));background-image:linear-gradient(#04519b, #033C73 60%, #02325f);background-repeat:no-repeat}.btn-warning{background-image:-webkit-gradient(linear, left top, left bottom, from(#ff6707), color-stop(60%, #DD5600), to(#c94e00));background-image:linear-gradient(#ff6707, #DD5600 60%, #c94e00);background-repeat:no-repeat}.btn-danger{background-image:-webkit-gradient(linear, left top, left bottom, from(#e12b31), color-stop(60%, #C71C22), to(#b5191f));background-image:linear-gradient(#e12b31, #C71C22 60%, #b5191f);background-repeat:no-repeat}.btn-light{background-image:-webkit-gradient(linear, left top, left bottom, from(white), color-stop(60%, #f8f9fa), to(#eceff2));background-image:linear-gradient(white, #f8f9fa 60%, #eceff2);background-repeat:no-repeat}.btn-dark{background-image:-webkit-gradient(linear, left top, left bottom, from(#464e57), color-stop(60%, #343a40), to(#2b3035));background-image:linear-gradient(#464e57, #343a40 60%, #2b3035);background-repeat:no-repeat}.bg-primary h1,.bg-primary h2,.bg-primary h3,.bg-primary h4,.bg-primary h5,.bg-primary h6,.bg-success h1,.bg-success h2,.bg-success h3,.bg-success h4,.bg-success h5,.bg-success h6,.bg-info h1,.bg-info h2,.bg-info h3,.bg-info h4,.bg-info h5,.bg-info h6,.bg-warning h1,.bg-warning h2,.bg-warning h3,.bg-warning h4,.bg-warning h5,.bg-warning h6,.bg-danger h1,.bg-danger h2,.bg-danger h3,.bg-danger h4,.bg-danger h5,.bg-danger h6,.bg-dark h1,.bg-dark h2,.bg-dark h3,.bg-dark h4,.bg-dark h5,.bg-dark h6{color:#fff}.dropdown-menu .dropdown-header{color:#868e96} diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/css/font-awesome.min.css b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/css/font-awesome.min.css new file mode 100644 index 0000000000000000000000000000000000000000..540440ce89f2a408aa699b65100e18f15e0f09ca --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/css/font-awesome.min.css @@ -0,0 +1,4 @@ +/*! + * Font Awesome 4.7.0 by @davegandy - http://fontawesome.io - @fontawesome + * License - http://fontawesome.io/license (Font: SIL OFL 1.1, CSS: MIT License) + */@font-face{font-family:'FontAwesome';src:url('../fonts/fontawesome-webfont.eot?v=4.7.0');src:url('../fonts/fontawesome-webfont.eot?#iefix&v=4.7.0') format('embedded-opentype'),url('../fonts/fontawesome-webfont.woff2?v=4.7.0') format('woff2'),url('../fonts/fontawesome-webfont.woff?v=4.7.0') format('woff'),url('../fonts/fontawesome-webfont.ttf?v=4.7.0') format('truetype'),url('../fonts/fontawesome-webfont.svg?v=4.7.0#fontawesomeregular') format('svg');font-weight:normal;font-style:normal}.fa{display:inline-block;font:normal normal normal 14px/1 FontAwesome;font-size:inherit;text-rendering:auto;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.fa-lg{font-size:1.33333333em;line-height:.75em;vertical-align:-15%}.fa-2x{font-size:2em}.fa-3x{font-size:3em}.fa-4x{font-size:4em}.fa-5x{font-size:5em}.fa-fw{width:1.28571429em;text-align:center}.fa-ul{padding-left:0;margin-left:2.14285714em;list-style-type:none}.fa-ul>li{position:relative}.fa-li{position:absolute;left:-2.14285714em;width:2.14285714em;top:.14285714em;text-align:center}.fa-li.fa-lg{left:-1.85714286em}.fa-border{padding:.2em .25em .15em;border:solid .08em #eee;border-radius:.1em}.fa-pull-left{float:left}.fa-pull-right{float:right}.fa.fa-pull-left{margin-right:.3em}.fa.fa-pull-right{margin-left:.3em}.pull-right{float:right}.pull-left{float:left}.fa.pull-left{margin-right:.3em}.fa.pull-right{margin-left:.3em}.fa-spin{-webkit-animation:fa-spin 2s infinite linear;animation:fa-spin 2s infinite linear}.fa-pulse{-webkit-animation:fa-spin 1s infinite steps(8);animation:fa-spin 1s infinite steps(8)}@-webkit-keyframes fa-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}100%{-webkit-transform:rotate(359deg);transform:rotate(359deg)}}@keyframes fa-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}100%{-webkit-transform:rotate(359deg);transform:rotate(359deg)}}.fa-rotate-90{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=1)";-webkit-transform:rotate(90deg);-ms-transform:rotate(90deg);transform:rotate(90deg)}.fa-rotate-180{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=2)";-webkit-transform:rotate(180deg);-ms-transform:rotate(180deg);transform:rotate(180deg)}.fa-rotate-270{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=3)";-webkit-transform:rotate(270deg);-ms-transform:rotate(270deg);transform:rotate(270deg)}.fa-flip-horizontal{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=0, mirror=1)";-webkit-transform:scale(-1, 1);-ms-transform:scale(-1, 1);transform:scale(-1, 1)}.fa-flip-vertical{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=2, mirror=1)";-webkit-transform:scale(1, -1);-ms-transform:scale(1, -1);transform:scale(1, -1)}:root .fa-rotate-90,:root .fa-rotate-180,:root .fa-rotate-270,:root .fa-flip-horizontal,:root .fa-flip-vertical{filter:none}.fa-stack{position:relative;display:inline-block;width:2em;height:2em;line-height:2em;vertical-align:middle}.fa-stack-1x,.fa-stack-2x{position:absolute;left:0;width:100%;text-align:center}.fa-stack-1x{line-height:inherit}.fa-stack-2x{font-size:2em}.fa-inverse{color:#fff}.fa-glass:before{content:"\f000"}.fa-music:before{content:"\f001"}.fa-search:before{content:"\f002"}.fa-envelope-o:before{content:"\f003"}.fa-heart:before{content:"\f004"}.fa-star:before{content:"\f005"}.fa-star-o:before{content:"\f006"}.fa-user:before{content:"\f007"}.fa-film:before{content:"\f008"}.fa-th-large:before{content:"\f009"}.fa-th:before{content:"\f00a"}.fa-th-list:before{content:"\f00b"}.fa-check:before{content:"\f00c"}.fa-remove:before,.fa-close:before,.fa-times:before{content:"\f00d"}.fa-search-plus:before{content:"\f00e"}.fa-search-minus:before{content:"\f010"}.fa-power-off:before{content:"\f011"}.fa-signal:before{content:"\f012"}.fa-gear:before,.fa-cog:before{content:"\f013"}.fa-trash-o:before{content:"\f014"}.fa-home:before{content:"\f015"}.fa-file-o:before{content:"\f016"}.fa-clock-o:before{content:"\f017"}.fa-road:before{content:"\f018"}.fa-download:before{content:"\f019"}.fa-arrow-circle-o-down:before{content:"\f01a"}.fa-arrow-circle-o-up:before{content:"\f01b"}.fa-inbox:before{content:"\f01c"}.fa-play-circle-o:before{content:"\f01d"}.fa-rotate-right:before,.fa-repeat:before{content:"\f01e"}.fa-refresh:before{content:"\f021"}.fa-list-alt:before{content:"\f022"}.fa-lock:before{content:"\f023"}.fa-flag:before{content:"\f024"}.fa-headphones:before{content:"\f025"}.fa-volume-off:before{content:"\f026"}.fa-volume-down:before{content:"\f027"}.fa-volume-up:before{content:"\f028"}.fa-qrcode:before{content:"\f029"}.fa-barcode:before{content:"\f02a"}.fa-tag:before{content:"\f02b"}.fa-tags:before{content:"\f02c"}.fa-book:before{content:"\f02d"}.fa-bookmark:before{content:"\f02e"}.fa-print:before{content:"\f02f"}.fa-camera:before{content:"\f030"}.fa-font:before{content:"\f031"}.fa-bold:before{content:"\f032"}.fa-italic:before{content:"\f033"}.fa-text-height:before{content:"\f034"}.fa-text-width:before{content:"\f035"}.fa-align-left:before{content:"\f036"}.fa-align-center:before{content:"\f037"}.fa-align-right:before{content:"\f038"}.fa-align-justify:before{content:"\f039"}.fa-list:before{content:"\f03a"}.fa-dedent:before,.fa-outdent:before{content:"\f03b"}.fa-indent:before{content:"\f03c"}.fa-video-camera:before{content:"\f03d"}.fa-photo:before,.fa-image:before,.fa-picture-o:before{content:"\f03e"}.fa-pencil:before{content:"\f040"}.fa-map-marker:before{content:"\f041"}.fa-adjust:before{content:"\f042"}.fa-tint:before{content:"\f043"}.fa-edit:before,.fa-pencil-square-o:before{content:"\f044"}.fa-share-square-o:before{content:"\f045"}.fa-check-square-o:before{content:"\f046"}.fa-arrows:before{content:"\f047"}.fa-step-backward:before{content:"\f048"}.fa-fast-backward:before{content:"\f049"}.fa-backward:before{content:"\f04a"}.fa-play:before{content:"\f04b"}.fa-pause:before{content:"\f04c"}.fa-stop:before{content:"\f04d"}.fa-forward:before{content:"\f04e"}.fa-fast-forward:before{content:"\f050"}.fa-step-forward:before{content:"\f051"}.fa-eject:before{content:"\f052"}.fa-chevron-left:before{content:"\f053"}.fa-chevron-right:before{content:"\f054"}.fa-plus-circle:before{content:"\f055"}.fa-minus-circle:before{content:"\f056"}.fa-times-circle:before{content:"\f057"}.fa-check-circle:before{content:"\f058"}.fa-question-circle:before{content:"\f059"}.fa-info-circle:before{content:"\f05a"}.fa-crosshairs:before{content:"\f05b"}.fa-times-circle-o:before{content:"\f05c"}.fa-check-circle-o:before{content:"\f05d"}.fa-ban:before{content:"\f05e"}.fa-arrow-left:before{content:"\f060"}.fa-arrow-right:before{content:"\f061"}.fa-arrow-up:before{content:"\f062"}.fa-arrow-down:before{content:"\f063"}.fa-mail-forward:before,.fa-share:before{content:"\f064"}.fa-expand:before{content:"\f065"}.fa-compress:before{content:"\f066"}.fa-plus:before{content:"\f067"}.fa-minus:before{content:"\f068"}.fa-asterisk:before{content:"\f069"}.fa-exclamation-circle:before{content:"\f06a"}.fa-gift:before{content:"\f06b"}.fa-leaf:before{content:"\f06c"}.fa-fire:before{content:"\f06d"}.fa-eye:before{content:"\f06e"}.fa-eye-slash:before{content:"\f070"}.fa-warning:before,.fa-exclamation-triangle:before{content:"\f071"}.fa-plane:before{content:"\f072"}.fa-calendar:before{content:"\f073"}.fa-random:before{content:"\f074"}.fa-comment:before{content:"\f075"}.fa-magnet:before{content:"\f076"}.fa-chevron-up:before{content:"\f077"}.fa-chevron-down:before{content:"\f078"}.fa-retweet:before{content:"\f079"}.fa-shopping-cart:before{content:"\f07a"}.fa-folder:before{content:"\f07b"}.fa-folder-open:before{content:"\f07c"}.fa-arrows-v:before{content:"\f07d"}.fa-arrows-h:before{content:"\f07e"}.fa-bar-chart-o:before,.fa-bar-chart:before{content:"\f080"}.fa-twitter-square:before{content:"\f081"}.fa-facebook-square:before{content:"\f082"}.fa-camera-retro:before{content:"\f083"}.fa-key:before{content:"\f084"}.fa-gears:before,.fa-cogs:before{content:"\f085"}.fa-comments:before{content:"\f086"}.fa-thumbs-o-up:before{content:"\f087"}.fa-thumbs-o-down:before{content:"\f088"}.fa-star-half:before{content:"\f089"}.fa-heart-o:before{content:"\f08a"}.fa-sign-out:before{content:"\f08b"}.fa-linkedin-square:before{content:"\f08c"}.fa-thumb-tack:before{content:"\f08d"}.fa-external-link:before{content:"\f08e"}.fa-sign-in:before{content:"\f090"}.fa-trophy:before{content:"\f091"}.fa-github-square:before{content:"\f092"}.fa-upload:before{content:"\f093"}.fa-lemon-o:before{content:"\f094"}.fa-phone:before{content:"\f095"}.fa-square-o:before{content:"\f096"}.fa-bookmark-o:before{content:"\f097"}.fa-phone-square:before{content:"\f098"}.fa-twitter:before{content:"\f099"}.fa-facebook-f:before,.fa-facebook:before{content:"\f09a"}.fa-github:before{content:"\f09b"}.fa-unlock:before{content:"\f09c"}.fa-credit-card:before{content:"\f09d"}.fa-feed:before,.fa-rss:before{content:"\f09e"}.fa-hdd-o:before{content:"\f0a0"}.fa-bullhorn:before{content:"\f0a1"}.fa-bell:before{content:"\f0f3"}.fa-certificate:before{content:"\f0a3"}.fa-hand-o-right:before{content:"\f0a4"}.fa-hand-o-left:before{content:"\f0a5"}.fa-hand-o-up:before{content:"\f0a6"}.fa-hand-o-down:before{content:"\f0a7"}.fa-arrow-circle-left:before{content:"\f0a8"}.fa-arrow-circle-right:before{content:"\f0a9"}.fa-arrow-circle-up:before{content:"\f0aa"}.fa-arrow-circle-down:before{content:"\f0ab"}.fa-globe:before{content:"\f0ac"}.fa-wrench:before{content:"\f0ad"}.fa-tasks:before{content:"\f0ae"}.fa-filter:before{content:"\f0b0"}.fa-briefcase:before{content:"\f0b1"}.fa-arrows-alt:before{content:"\f0b2"}.fa-group:before,.fa-users:before{content:"\f0c0"}.fa-chain:before,.fa-link:before{content:"\f0c1"}.fa-cloud:before{content:"\f0c2"}.fa-flask:before{content:"\f0c3"}.fa-cut:before,.fa-scissors:before{content:"\f0c4"}.fa-copy:before,.fa-files-o:before{content:"\f0c5"}.fa-paperclip:before{content:"\f0c6"}.fa-save:before,.fa-floppy-o:before{content:"\f0c7"}.fa-square:before{content:"\f0c8"}.fa-navicon:before,.fa-reorder:before,.fa-bars:before{content:"\f0c9"}.fa-list-ul:before{content:"\f0ca"}.fa-list-ol:before{content:"\f0cb"}.fa-strikethrough:before{content:"\f0cc"}.fa-underline:before{content:"\f0cd"}.fa-table:before{content:"\f0ce"}.fa-magic:before{content:"\f0d0"}.fa-truck:before{content:"\f0d1"}.fa-pinterest:before{content:"\f0d2"}.fa-pinterest-square:before{content:"\f0d3"}.fa-google-plus-square:before{content:"\f0d4"}.fa-google-plus:before{content:"\f0d5"}.fa-money:before{content:"\f0d6"}.fa-caret-down:before{content:"\f0d7"}.fa-caret-up:before{content:"\f0d8"}.fa-caret-left:before{content:"\f0d9"}.fa-caret-right:before{content:"\f0da"}.fa-columns:before{content:"\f0db"}.fa-unsorted:before,.fa-sort:before{content:"\f0dc"}.fa-sort-down:before,.fa-sort-desc:before{content:"\f0dd"}.fa-sort-up:before,.fa-sort-asc:before{content:"\f0de"}.fa-envelope:before{content:"\f0e0"}.fa-linkedin:before{content:"\f0e1"}.fa-rotate-left:before,.fa-undo:before{content:"\f0e2"}.fa-legal:before,.fa-gavel:before{content:"\f0e3"}.fa-dashboard:before,.fa-tachometer:before{content:"\f0e4"}.fa-comment-o:before{content:"\f0e5"}.fa-comments-o:before{content:"\f0e6"}.fa-flash:before,.fa-bolt:before{content:"\f0e7"}.fa-sitemap:before{content:"\f0e8"}.fa-umbrella:before{content:"\f0e9"}.fa-paste:before,.fa-clipboard:before{content:"\f0ea"}.fa-lightbulb-o:before{content:"\f0eb"}.fa-exchange:before{content:"\f0ec"}.fa-cloud-download:before{content:"\f0ed"}.fa-cloud-upload:before{content:"\f0ee"}.fa-user-md:before{content:"\f0f0"}.fa-stethoscope:before{content:"\f0f1"}.fa-suitcase:before{content:"\f0f2"}.fa-bell-o:before{content:"\f0a2"}.fa-coffee:before{content:"\f0f4"}.fa-cutlery:before{content:"\f0f5"}.fa-file-text-o:before{content:"\f0f6"}.fa-building-o:before{content:"\f0f7"}.fa-hospital-o:before{content:"\f0f8"}.fa-ambulance:before{content:"\f0f9"}.fa-medkit:before{content:"\f0fa"}.fa-fighter-jet:before{content:"\f0fb"}.fa-beer:before{content:"\f0fc"}.fa-h-square:before{content:"\f0fd"}.fa-plus-square:before{content:"\f0fe"}.fa-angle-double-left:before{content:"\f100"}.fa-angle-double-right:before{content:"\f101"}.fa-angle-double-up:before{content:"\f102"}.fa-angle-double-down:before{content:"\f103"}.fa-angle-left:before{content:"\f104"}.fa-angle-right:before{content:"\f105"}.fa-angle-up:before{content:"\f106"}.fa-angle-down:before{content:"\f107"}.fa-desktop:before{content:"\f108"}.fa-laptop:before{content:"\f109"}.fa-tablet:before{content:"\f10a"}.fa-mobile-phone:before,.fa-mobile:before{content:"\f10b"}.fa-circle-o:before{content:"\f10c"}.fa-quote-left:before{content:"\f10d"}.fa-quote-right:before{content:"\f10e"}.fa-spinner:before{content:"\f110"}.fa-circle:before{content:"\f111"}.fa-mail-reply:before,.fa-reply:before{content:"\f112"}.fa-github-alt:before{content:"\f113"}.fa-folder-o:before{content:"\f114"}.fa-folder-open-o:before{content:"\f115"}.fa-smile-o:before{content:"\f118"}.fa-frown-o:before{content:"\f119"}.fa-meh-o:before{content:"\f11a"}.fa-gamepad:before{content:"\f11b"}.fa-keyboard-o:before{content:"\f11c"}.fa-flag-o:before{content:"\f11d"}.fa-flag-checkered:before{content:"\f11e"}.fa-terminal:before{content:"\f120"}.fa-code:before{content:"\f121"}.fa-mail-reply-all:before,.fa-reply-all:before{content:"\f122"}.fa-star-half-empty:before,.fa-star-half-full:before,.fa-star-half-o:before{content:"\f123"}.fa-location-arrow:before{content:"\f124"}.fa-crop:before{content:"\f125"}.fa-code-fork:before{content:"\f126"}.fa-unlink:before,.fa-chain-broken:before{content:"\f127"}.fa-question:before{content:"\f128"}.fa-info:before{content:"\f129"}.fa-exclamation:before{content:"\f12a"}.fa-superscript:before{content:"\f12b"}.fa-subscript:before{content:"\f12c"}.fa-eraser:before{content:"\f12d"}.fa-puzzle-piece:before{content:"\f12e"}.fa-microphone:before{content:"\f130"}.fa-microphone-slash:before{content:"\f131"}.fa-shield:before{content:"\f132"}.fa-calendar-o:before{content:"\f133"}.fa-fire-extinguisher:before{content:"\f134"}.fa-rocket:before{content:"\f135"}.fa-maxcdn:before{content:"\f136"}.fa-chevron-circle-left:before{content:"\f137"}.fa-chevron-circle-right:before{content:"\f138"}.fa-chevron-circle-up:before{content:"\f139"}.fa-chevron-circle-down:before{content:"\f13a"}.fa-html5:before{content:"\f13b"}.fa-css3:before{content:"\f13c"}.fa-anchor:before{content:"\f13d"}.fa-unlock-alt:before{content:"\f13e"}.fa-bullseye:before{content:"\f140"}.fa-ellipsis-h:before{content:"\f141"}.fa-ellipsis-v:before{content:"\f142"}.fa-rss-square:before{content:"\f143"}.fa-play-circle:before{content:"\f144"}.fa-ticket:before{content:"\f145"}.fa-minus-square:before{content:"\f146"}.fa-minus-square-o:before{content:"\f147"}.fa-level-up:before{content:"\f148"}.fa-level-down:before{content:"\f149"}.fa-check-square:before{content:"\f14a"}.fa-pencil-square:before{content:"\f14b"}.fa-external-link-square:before{content:"\f14c"}.fa-share-square:before{content:"\f14d"}.fa-compass:before{content:"\f14e"}.fa-toggle-down:before,.fa-caret-square-o-down:before{content:"\f150"}.fa-toggle-up:before,.fa-caret-square-o-up:before{content:"\f151"}.fa-toggle-right:before,.fa-caret-square-o-right:before{content:"\f152"}.fa-euro:before,.fa-eur:before{content:"\f153"}.fa-gbp:before{content:"\f154"}.fa-dollar:before,.fa-usd:before{content:"\f155"}.fa-rupee:before,.fa-inr:before{content:"\f156"}.fa-cny:before,.fa-rmb:before,.fa-yen:before,.fa-jpy:before{content:"\f157"}.fa-ruble:before,.fa-rouble:before,.fa-rub:before{content:"\f158"}.fa-won:before,.fa-krw:before{content:"\f159"}.fa-bitcoin:before,.fa-btc:before{content:"\f15a"}.fa-file:before{content:"\f15b"}.fa-file-text:before{content:"\f15c"}.fa-sort-alpha-asc:before{content:"\f15d"}.fa-sort-alpha-desc:before{content:"\f15e"}.fa-sort-amount-asc:before{content:"\f160"}.fa-sort-amount-desc:before{content:"\f161"}.fa-sort-numeric-asc:before{content:"\f162"}.fa-sort-numeric-desc:before{content:"\f163"}.fa-thumbs-up:before{content:"\f164"}.fa-thumbs-down:before{content:"\f165"}.fa-youtube-square:before{content:"\f166"}.fa-youtube:before{content:"\f167"}.fa-xing:before{content:"\f168"}.fa-xing-square:before{content:"\f169"}.fa-youtube-play:before{content:"\f16a"}.fa-dropbox:before{content:"\f16b"}.fa-stack-overflow:before{content:"\f16c"}.fa-instagram:before{content:"\f16d"}.fa-flickr:before{content:"\f16e"}.fa-adn:before{content:"\f170"}.fa-bitbucket:before{content:"\f171"}.fa-bitbucket-square:before{content:"\f172"}.fa-tumblr:before{content:"\f173"}.fa-tumblr-square:before{content:"\f174"}.fa-long-arrow-down:before{content:"\f175"}.fa-long-arrow-up:before{content:"\f176"}.fa-long-arrow-left:before{content:"\f177"}.fa-long-arrow-right:before{content:"\f178"}.fa-apple:before{content:"\f179"}.fa-windows:before{content:"\f17a"}.fa-android:before{content:"\f17b"}.fa-linux:before{content:"\f17c"}.fa-dribbble:before{content:"\f17d"}.fa-skype:before{content:"\f17e"}.fa-foursquare:before{content:"\f180"}.fa-trello:before{content:"\f181"}.fa-female:before{content:"\f182"}.fa-male:before{content:"\f183"}.fa-gittip:before,.fa-gratipay:before{content:"\f184"}.fa-sun-o:before{content:"\f185"}.fa-moon-o:before{content:"\f186"}.fa-archive:before{content:"\f187"}.fa-bug:before{content:"\f188"}.fa-vk:before{content:"\f189"}.fa-weibo:before{content:"\f18a"}.fa-renren:before{content:"\f18b"}.fa-pagelines:before{content:"\f18c"}.fa-stack-exchange:before{content:"\f18d"}.fa-arrow-circle-o-right:before{content:"\f18e"}.fa-arrow-circle-o-left:before{content:"\f190"}.fa-toggle-left:before,.fa-caret-square-o-left:before{content:"\f191"}.fa-dot-circle-o:before{content:"\f192"}.fa-wheelchair:before{content:"\f193"}.fa-vimeo-square:before{content:"\f194"}.fa-turkish-lira:before,.fa-try:before{content:"\f195"}.fa-plus-square-o:before{content:"\f196"}.fa-space-shuttle:before{content:"\f197"}.fa-slack:before{content:"\f198"}.fa-envelope-square:before{content:"\f199"}.fa-wordpress:before{content:"\f19a"}.fa-openid:before{content:"\f19b"}.fa-institution:before,.fa-bank:before,.fa-university:before{content:"\f19c"}.fa-mortar-board:before,.fa-graduation-cap:before{content:"\f19d"}.fa-yahoo:before{content:"\f19e"}.fa-google:before{content:"\f1a0"}.fa-reddit:before{content:"\f1a1"}.fa-reddit-square:before{content:"\f1a2"}.fa-stumbleupon-circle:before{content:"\f1a3"}.fa-stumbleupon:before{content:"\f1a4"}.fa-delicious:before{content:"\f1a5"}.fa-digg:before{content:"\f1a6"}.fa-pied-piper-pp:before{content:"\f1a7"}.fa-pied-piper-alt:before{content:"\f1a8"}.fa-drupal:before{content:"\f1a9"}.fa-joomla:before{content:"\f1aa"}.fa-language:before{content:"\f1ab"}.fa-fax:before{content:"\f1ac"}.fa-building:before{content:"\f1ad"}.fa-child:before{content:"\f1ae"}.fa-paw:before{content:"\f1b0"}.fa-spoon:before{content:"\f1b1"}.fa-cube:before{content:"\f1b2"}.fa-cubes:before{content:"\f1b3"}.fa-behance:before{content:"\f1b4"}.fa-behance-square:before{content:"\f1b5"}.fa-steam:before{content:"\f1b6"}.fa-steam-square:before{content:"\f1b7"}.fa-recycle:before{content:"\f1b8"}.fa-automobile:before,.fa-car:before{content:"\f1b9"}.fa-cab:before,.fa-taxi:before{content:"\f1ba"}.fa-tree:before{content:"\f1bb"}.fa-spotify:before{content:"\f1bc"}.fa-deviantart:before{content:"\f1bd"}.fa-soundcloud:before{content:"\f1be"}.fa-database:before{content:"\f1c0"}.fa-file-pdf-o:before{content:"\f1c1"}.fa-file-word-o:before{content:"\f1c2"}.fa-file-excel-o:before{content:"\f1c3"}.fa-file-powerpoint-o:before{content:"\f1c4"}.fa-file-photo-o:before,.fa-file-picture-o:before,.fa-file-image-o:before{content:"\f1c5"}.fa-file-zip-o:before,.fa-file-archive-o:before{content:"\f1c6"}.fa-file-sound-o:before,.fa-file-audio-o:before{content:"\f1c7"}.fa-file-movie-o:before,.fa-file-video-o:before{content:"\f1c8"}.fa-file-code-o:before{content:"\f1c9"}.fa-vine:before{content:"\f1ca"}.fa-codepen:before{content:"\f1cb"}.fa-jsfiddle:before{content:"\f1cc"}.fa-life-bouy:before,.fa-life-buoy:before,.fa-life-saver:before,.fa-support:before,.fa-life-ring:before{content:"\f1cd"}.fa-circle-o-notch:before{content:"\f1ce"}.fa-ra:before,.fa-resistance:before,.fa-rebel:before{content:"\f1d0"}.fa-ge:before,.fa-empire:before{content:"\f1d1"}.fa-git-square:before{content:"\f1d2"}.fa-git:before{content:"\f1d3"}.fa-y-combinator-square:before,.fa-yc-square:before,.fa-hacker-news:before{content:"\f1d4"}.fa-tencent-weibo:before{content:"\f1d5"}.fa-qq:before{content:"\f1d6"}.fa-wechat:before,.fa-weixin:before{content:"\f1d7"}.fa-send:before,.fa-paper-plane:before{content:"\f1d8"}.fa-send-o:before,.fa-paper-plane-o:before{content:"\f1d9"}.fa-history:before{content:"\f1da"}.fa-circle-thin:before{content:"\f1db"}.fa-header:before{content:"\f1dc"}.fa-paragraph:before{content:"\f1dd"}.fa-sliders:before{content:"\f1de"}.fa-share-alt:before{content:"\f1e0"}.fa-share-alt-square:before{content:"\f1e1"}.fa-bomb:before{content:"\f1e2"}.fa-soccer-ball-o:before,.fa-futbol-o:before{content:"\f1e3"}.fa-tty:before{content:"\f1e4"}.fa-binoculars:before{content:"\f1e5"}.fa-plug:before{content:"\f1e6"}.fa-slideshare:before{content:"\f1e7"}.fa-twitch:before{content:"\f1e8"}.fa-yelp:before{content:"\f1e9"}.fa-newspaper-o:before{content:"\f1ea"}.fa-wifi:before{content:"\f1eb"}.fa-calculator:before{content:"\f1ec"}.fa-paypal:before{content:"\f1ed"}.fa-google-wallet:before{content:"\f1ee"}.fa-cc-visa:before{content:"\f1f0"}.fa-cc-mastercard:before{content:"\f1f1"}.fa-cc-discover:before{content:"\f1f2"}.fa-cc-amex:before{content:"\f1f3"}.fa-cc-paypal:before{content:"\f1f4"}.fa-cc-stripe:before{content:"\f1f5"}.fa-bell-slash:before{content:"\f1f6"}.fa-bell-slash-o:before{content:"\f1f7"}.fa-trash:before{content:"\f1f8"}.fa-copyright:before{content:"\f1f9"}.fa-at:before{content:"\f1fa"}.fa-eyedropper:before{content:"\f1fb"}.fa-paint-brush:before{content:"\f1fc"}.fa-birthday-cake:before{content:"\f1fd"}.fa-area-chart:before{content:"\f1fe"}.fa-pie-chart:before{content:"\f200"}.fa-line-chart:before{content:"\f201"}.fa-lastfm:before{content:"\f202"}.fa-lastfm-square:before{content:"\f203"}.fa-toggle-off:before{content:"\f204"}.fa-toggle-on:before{content:"\f205"}.fa-bicycle:before{content:"\f206"}.fa-bus:before{content:"\f207"}.fa-ioxhost:before{content:"\f208"}.fa-angellist:before{content:"\f209"}.fa-cc:before{content:"\f20a"}.fa-shekel:before,.fa-sheqel:before,.fa-ils:before{content:"\f20b"}.fa-meanpath:before{content:"\f20c"}.fa-buysellads:before{content:"\f20d"}.fa-connectdevelop:before{content:"\f20e"}.fa-dashcube:before{content:"\f210"}.fa-forumbee:before{content:"\f211"}.fa-leanpub:before{content:"\f212"}.fa-sellsy:before{content:"\f213"}.fa-shirtsinbulk:before{content:"\f214"}.fa-simplybuilt:before{content:"\f215"}.fa-skyatlas:before{content:"\f216"}.fa-cart-plus:before{content:"\f217"}.fa-cart-arrow-down:before{content:"\f218"}.fa-diamond:before{content:"\f219"}.fa-ship:before{content:"\f21a"}.fa-user-secret:before{content:"\f21b"}.fa-motorcycle:before{content:"\f21c"}.fa-street-view:before{content:"\f21d"}.fa-heartbeat:before{content:"\f21e"}.fa-venus:before{content:"\f221"}.fa-mars:before{content:"\f222"}.fa-mercury:before{content:"\f223"}.fa-intersex:before,.fa-transgender:before{content:"\f224"}.fa-transgender-alt:before{content:"\f225"}.fa-venus-double:before{content:"\f226"}.fa-mars-double:before{content:"\f227"}.fa-venus-mars:before{content:"\f228"}.fa-mars-stroke:before{content:"\f229"}.fa-mars-stroke-v:before{content:"\f22a"}.fa-mars-stroke-h:before{content:"\f22b"}.fa-neuter:before{content:"\f22c"}.fa-genderless:before{content:"\f22d"}.fa-facebook-official:before{content:"\f230"}.fa-pinterest-p:before{content:"\f231"}.fa-whatsapp:before{content:"\f232"}.fa-server:before{content:"\f233"}.fa-user-plus:before{content:"\f234"}.fa-user-times:before{content:"\f235"}.fa-hotel:before,.fa-bed:before{content:"\f236"}.fa-viacoin:before{content:"\f237"}.fa-train:before{content:"\f238"}.fa-subway:before{content:"\f239"}.fa-medium:before{content:"\f23a"}.fa-yc:before,.fa-y-combinator:before{content:"\f23b"}.fa-optin-monster:before{content:"\f23c"}.fa-opencart:before{content:"\f23d"}.fa-expeditedssl:before{content:"\f23e"}.fa-battery-4:before,.fa-battery:before,.fa-battery-full:before{content:"\f240"}.fa-battery-3:before,.fa-battery-three-quarters:before{content:"\f241"}.fa-battery-2:before,.fa-battery-half:before{content:"\f242"}.fa-battery-1:before,.fa-battery-quarter:before{content:"\f243"}.fa-battery-0:before,.fa-battery-empty:before{content:"\f244"}.fa-mouse-pointer:before{content:"\f245"}.fa-i-cursor:before{content:"\f246"}.fa-object-group:before{content:"\f247"}.fa-object-ungroup:before{content:"\f248"}.fa-sticky-note:before{content:"\f249"}.fa-sticky-note-o:before{content:"\f24a"}.fa-cc-jcb:before{content:"\f24b"}.fa-cc-diners-club:before{content:"\f24c"}.fa-clone:before{content:"\f24d"}.fa-balance-scale:before{content:"\f24e"}.fa-hourglass-o:before{content:"\f250"}.fa-hourglass-1:before,.fa-hourglass-start:before{content:"\f251"}.fa-hourglass-2:before,.fa-hourglass-half:before{content:"\f252"}.fa-hourglass-3:before,.fa-hourglass-end:before{content:"\f253"}.fa-hourglass:before{content:"\f254"}.fa-hand-grab-o:before,.fa-hand-rock-o:before{content:"\f255"}.fa-hand-stop-o:before,.fa-hand-paper-o:before{content:"\f256"}.fa-hand-scissors-o:before{content:"\f257"}.fa-hand-lizard-o:before{content:"\f258"}.fa-hand-spock-o:before{content:"\f259"}.fa-hand-pointer-o:before{content:"\f25a"}.fa-hand-peace-o:before{content:"\f25b"}.fa-trademark:before{content:"\f25c"}.fa-registered:before{content:"\f25d"}.fa-creative-commons:before{content:"\f25e"}.fa-gg:before{content:"\f260"}.fa-gg-circle:before{content:"\f261"}.fa-tripadvisor:before{content:"\f262"}.fa-odnoklassniki:before{content:"\f263"}.fa-odnoklassniki-square:before{content:"\f264"}.fa-get-pocket:before{content:"\f265"}.fa-wikipedia-w:before{content:"\f266"}.fa-safari:before{content:"\f267"}.fa-chrome:before{content:"\f268"}.fa-firefox:before{content:"\f269"}.fa-opera:before{content:"\f26a"}.fa-internet-explorer:before{content:"\f26b"}.fa-tv:before,.fa-television:before{content:"\f26c"}.fa-contao:before{content:"\f26d"}.fa-500px:before{content:"\f26e"}.fa-amazon:before{content:"\f270"}.fa-calendar-plus-o:before{content:"\f271"}.fa-calendar-minus-o:before{content:"\f272"}.fa-calendar-times-o:before{content:"\f273"}.fa-calendar-check-o:before{content:"\f274"}.fa-industry:before{content:"\f275"}.fa-map-pin:before{content:"\f276"}.fa-map-signs:before{content:"\f277"}.fa-map-o:before{content:"\f278"}.fa-map:before{content:"\f279"}.fa-commenting:before{content:"\f27a"}.fa-commenting-o:before{content:"\f27b"}.fa-houzz:before{content:"\f27c"}.fa-vimeo:before{content:"\f27d"}.fa-black-tie:before{content:"\f27e"}.fa-fonticons:before{content:"\f280"}.fa-reddit-alien:before{content:"\f281"}.fa-edge:before{content:"\f282"}.fa-credit-card-alt:before{content:"\f283"}.fa-codiepie:before{content:"\f284"}.fa-modx:before{content:"\f285"}.fa-fort-awesome:before{content:"\f286"}.fa-usb:before{content:"\f287"}.fa-product-hunt:before{content:"\f288"}.fa-mixcloud:before{content:"\f289"}.fa-scribd:before{content:"\f28a"}.fa-pause-circle:before{content:"\f28b"}.fa-pause-circle-o:before{content:"\f28c"}.fa-stop-circle:before{content:"\f28d"}.fa-stop-circle-o:before{content:"\f28e"}.fa-shopping-bag:before{content:"\f290"}.fa-shopping-basket:before{content:"\f291"}.fa-hashtag:before{content:"\f292"}.fa-bluetooth:before{content:"\f293"}.fa-bluetooth-b:before{content:"\f294"}.fa-percent:before{content:"\f295"}.fa-gitlab:before{content:"\f296"}.fa-wpbeginner:before{content:"\f297"}.fa-wpforms:before{content:"\f298"}.fa-envira:before{content:"\f299"}.fa-universal-access:before{content:"\f29a"}.fa-wheelchair-alt:before{content:"\f29b"}.fa-question-circle-o:before{content:"\f29c"}.fa-blind:before{content:"\f29d"}.fa-audio-description:before{content:"\f29e"}.fa-volume-control-phone:before{content:"\f2a0"}.fa-braille:before{content:"\f2a1"}.fa-assistive-listening-systems:before{content:"\f2a2"}.fa-asl-interpreting:before,.fa-american-sign-language-interpreting:before{content:"\f2a3"}.fa-deafness:before,.fa-hard-of-hearing:before,.fa-deaf:before{content:"\f2a4"}.fa-glide:before{content:"\f2a5"}.fa-glide-g:before{content:"\f2a6"}.fa-signing:before,.fa-sign-language:before{content:"\f2a7"}.fa-low-vision:before{content:"\f2a8"}.fa-viadeo:before{content:"\f2a9"}.fa-viadeo-square:before{content:"\f2aa"}.fa-snapchat:before{content:"\f2ab"}.fa-snapchat-ghost:before{content:"\f2ac"}.fa-snapchat-square:before{content:"\f2ad"}.fa-pied-piper:before{content:"\f2ae"}.fa-first-order:before{content:"\f2b0"}.fa-yoast:before{content:"\f2b1"}.fa-themeisle:before{content:"\f2b2"}.fa-google-plus-circle:before,.fa-google-plus-official:before{content:"\f2b3"}.fa-fa:before,.fa-font-awesome:before{content:"\f2b4"}.fa-handshake-o:before{content:"\f2b5"}.fa-envelope-open:before{content:"\f2b6"}.fa-envelope-open-o:before{content:"\f2b7"}.fa-linode:before{content:"\f2b8"}.fa-address-book:before{content:"\f2b9"}.fa-address-book-o:before{content:"\f2ba"}.fa-vcard:before,.fa-address-card:before{content:"\f2bb"}.fa-vcard-o:before,.fa-address-card-o:before{content:"\f2bc"}.fa-user-circle:before{content:"\f2bd"}.fa-user-circle-o:before{content:"\f2be"}.fa-user-o:before{content:"\f2c0"}.fa-id-badge:before{content:"\f2c1"}.fa-drivers-license:before,.fa-id-card:before{content:"\f2c2"}.fa-drivers-license-o:before,.fa-id-card-o:before{content:"\f2c3"}.fa-quora:before{content:"\f2c4"}.fa-free-code-camp:before{content:"\f2c5"}.fa-telegram:before{content:"\f2c6"}.fa-thermometer-4:before,.fa-thermometer:before,.fa-thermometer-full:before{content:"\f2c7"}.fa-thermometer-3:before,.fa-thermometer-three-quarters:before{content:"\f2c8"}.fa-thermometer-2:before,.fa-thermometer-half:before{content:"\f2c9"}.fa-thermometer-1:before,.fa-thermometer-quarter:before{content:"\f2ca"}.fa-thermometer-0:before,.fa-thermometer-empty:before{content:"\f2cb"}.fa-shower:before{content:"\f2cc"}.fa-bathtub:before,.fa-s15:before,.fa-bath:before{content:"\f2cd"}.fa-podcast:before{content:"\f2ce"}.fa-window-maximize:before{content:"\f2d0"}.fa-window-minimize:before{content:"\f2d1"}.fa-window-restore:before{content:"\f2d2"}.fa-times-rectangle:before,.fa-window-close:before{content:"\f2d3"}.fa-times-rectangle-o:before,.fa-window-close-o:before{content:"\f2d4"}.fa-bandcamp:before{content:"\f2d5"}.fa-grav:before{content:"\f2d6"}.fa-etsy:before{content:"\f2d7"}.fa-imdb:before{content:"\f2d8"}.fa-ravelry:before{content:"\f2d9"}.fa-eercast:before{content:"\f2da"}.fa-microchip:before{content:"\f2db"}.fa-snowflake-o:before{content:"\f2dc"}.fa-superpowers:before{content:"\f2dd"}.fa-wpexplorer:before{content:"\f2de"}.fa-meetup:before{content:"\f2e0"}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0, 0, 0, 0);border:0}.sr-only-focusable:active,.sr-only-focusable:focus{position:static;width:auto;height:auto;margin:0;overflow:visible;clip:auto} diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/fonts/fontawesome-webfont.eot b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/fonts/fontawesome-webfont.eot new file mode 100644 index 0000000000000000000000000000000000000000..67601ff7b470edd10d81e1fa7b05aef75b70fdbd --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/fonts/fontawesome-webfont.eot @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7bfcab6db99d5cfbf1705ca0536ddc78585432cc5fa41bbd7ad0f009033b2979 +size 165742 diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/fonts/fontawesome-webfont.svg b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/fonts/fontawesome-webfont.svg new file mode 100644 index 0000000000000000000000000000000000000000..855c845e538b65548118279537a04eab2ec6ef0d --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/fonts/fontawesome-webfont.svg @@ -0,0 +1,2671 @@ + + + + +Created by FontForge 20120731 at Mon Oct 24 17:37:40 2016 + By ,,, +Copyright Dave Gandy 2016. All rights reserved. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/fonts/fontawesome-webfont.ttf b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/fonts/fontawesome-webfont.ttf new file mode 100644 index 0000000000000000000000000000000000000000..cc52454fa7571648ba36785d6ac971f5e26ae914 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/fonts/fontawesome-webfont.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:aa58f33f239a0fb02f5c7a6c45c043d7a9ac9a093335806694ecd6d4edc0d6a8 +size 165548 diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/fonts/fontawesome-webfont.woff b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/fonts/fontawesome-webfont.woff new file mode 100644 index 0000000000000000000000000000000000000000..400014a4b06eee3d0c0d54402a47ab2601b2862b Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/fonts/fontawesome-webfont.woff differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/fonts/fontawesome-webfont.woff2 b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/fonts/fontawesome-webfont.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..4d13fc60404b91e398a37200c4a77b645cfd9586 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/fonts/fontawesome-webfont.woff2 differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/img/favicon.ico b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/img/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..e85006a3ce1c6fd81faa6d5a13095519c4a6fc96 Binary files /dev/null and b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/img/favicon.ico differ diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/img/grid.png b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/img/grid.png new file mode 100644 index 0000000000000000000000000000000000000000..ada19977c9aac19b08f41f18a3193a77d79cf84c --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/img/grid.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6e2a58503494a708105ac646d3af5c08c8c890325bb781a257d10f91ff968a9c +size 1458 diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/js/base.js b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/js/base.js new file mode 100644 index 0000000000000000000000000000000000000000..b0f4726bf15c26845a2fa6756c4ba90b9452fbb7 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/js/base.js @@ -0,0 +1,283 @@ +function getSearchTerm() { + var sPageURL = window.location.search.substring(1); + var sURLVariables = sPageURL.split('&'); + for (var i = 0; i < sURLVariables.length; i++) { + var sParameterName = sURLVariables[i].split('='); + if (sParameterName[0] == 'q') { + return sParameterName[1]; + } + } +} + +function applyTopPadding() { + // Update various absolute positions to match where the main container + // starts. This is necessary for handling multi-line nav headers, since + // that pushes the main container down. + var offset = $('body > .container').offset(); + $('html').css('scroll-padding-top', offset.top + 'px'); + $('.bs-sidebar.affix').css('top', offset.top + 'px'); +} + +$(document).ready(function() { + + applyTopPadding(); + + var search_term = getSearchTerm(), + $search_modal = $('#mkdocs_search_modal'), + $keyboard_modal = $('#mkdocs_keyboard_modal'); + + if (search_term) { + $search_modal.modal(); + } + + // make sure search input gets autofocus every time modal opens. + $search_modal.on('shown.bs.modal', function() { + $search_modal.find('#mkdocs-search-query').focus(); + }); + + // Close search modal when result is selected + // The links get added later so listen to parent + $('#mkdocs-search-results').click(function(e) { + if ($(e.target).is('a')) { + $search_modal.modal('hide'); + } + }); + + // Populate keyboard modal with proper Keys + $keyboard_modal.find('.help.shortcut kbd')[0].innerHTML = keyCodes[shortcuts.help]; + $keyboard_modal.find('.prev.shortcut kbd')[0].innerHTML = keyCodes[shortcuts.previous]; + $keyboard_modal.find('.next.shortcut kbd')[0].innerHTML = keyCodes[shortcuts.next]; + $keyboard_modal.find('.search.shortcut kbd')[0].innerHTML = keyCodes[shortcuts.search]; + + // Keyboard navigation + document.addEventListener("keydown", function(e) { + if ($(e.target).is(':input')) return true; + var key = e.which || e.keyCode || window.event && window.event.keyCode; + var page; + switch (key) { + case shortcuts.next: + page = $('.navbar a[rel="next"]:first').prop('href'); + break; + case shortcuts.previous: + page = $('.navbar a[rel="prev"]:first').prop('href'); + break; + case shortcuts.search: + e.preventDefault(); + $keyboard_modal.modal('hide'); + $search_modal.modal('show'); + $search_modal.find('#mkdocs-search-query').focus(); + break; + case shortcuts.help: + $search_modal.modal('hide'); + $keyboard_modal.modal('show'); + break; + default: break; + } + if (page) { + $keyboard_modal.modal('hide'); + window.location.href = page; + } + }); + + $('table').addClass('table table-striped table-hover'); + + // Improve the scrollspy behaviour when users click on a TOC item. + $(".bs-sidenav a").on("click", function() { + var clicked = this; + setTimeout(function() { + var active = $('.nav li.active a'); + active = active[active.length - 1]; + if (clicked !== active) { + $(active).parent().removeClass("active"); + $(clicked).parent().addClass("active"); + } + }, 50); + }); + + function showInnerDropdown(item) { + var popup = $(item).next('.dropdown-menu'); + popup.addClass('show'); + $(item).addClass('open'); + + // First, close any sibling dropdowns. + var container = $(item).parent().parent(); + container.find('> .dropdown-submenu > a').each(function(i, el) { + if (el !== item) { + hideInnerDropdown(el); + } + }); + + var popupMargin = 10; + var maxBottom = $(window).height() - popupMargin; + var bounds = item.getBoundingClientRect(); + + popup.css('left', bounds.right + 'px'); + if (bounds.top + popup.height() > maxBottom && + bounds.top > $(window).height() / 2) { + popup.css({ + 'top': (bounds.bottom - popup.height()) + 'px', + 'max-height': (bounds.bottom - popupMargin) + 'px', + }); + } else { + popup.css({ + 'top': bounds.top + 'px', + 'max-height': (maxBottom - bounds.top) + 'px', + }); + } + } + + function hideInnerDropdown(item) { + var popup = $(item).next('.dropdown-menu'); + popup.removeClass('show'); + $(item).removeClass('open'); + + popup.scrollTop(0); + popup.find('.dropdown-menu').scrollTop(0).removeClass('show'); + popup.find('.dropdown-submenu > a').removeClass('open'); + } + + $('.dropdown-submenu > a').on('click', function(e) { + if ($(this).next('.dropdown-menu').hasClass('show')) { + hideInnerDropdown(this); + } else { + showInnerDropdown(this); + } + + e.stopPropagation(); + e.preventDefault(); + }); + + $('.dropdown-menu').parent().on('hide.bs.dropdown', function(e) { + $(this).find('.dropdown-menu').scrollTop(0); + $(this).find('.dropdown-submenu > a').removeClass('open'); + $(this).find('.dropdown-menu .dropdown-menu').removeClass('show'); + }); +}); + +$(window).on('resize', applyTopPadding); + +$('body').scrollspy({ + target: '.bs-sidebar', + offset: 100 +}); + +/* Prevent disabled links from causing a page reload */ +$("li.disabled a").click(function() { + event.preventDefault(); +}); + +// See https://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes +// We only list common keys below. Obscure keys are omitted and their use is discouraged. +var keyCodes = { + 8: 'backspace', + 9: 'tab', + 13: 'enter', + 16: 'shift', + 17: 'ctrl', + 18: 'alt', + 19: 'pause/break', + 20: 'caps lock', + 27: 'escape', + 32: 'spacebar', + 33: 'page up', + 34: 'page down', + 35: 'end', + 36: 'home', + 37: '←', + 38: '↑', + 39: '→', + 40: '↓', + 45: 'insert', + 46: 'delete', + 48: '0', + 49: '1', + 50: '2', + 51: '3', + 52: '4', + 53: '5', + 54: '6', + 55: '7', + 56: '8', + 57: '9', + 65: 'a', + 66: 'b', + 67: 'c', + 68: 'd', + 69: 'e', + 70: 'f', + 71: 'g', + 72: 'h', + 73: 'i', + 74: 'j', + 75: 'k', + 76: 'l', + 77: 'm', + 78: 'n', + 79: 'o', + 80: 'p', + 81: 'q', + 82: 'r', + 83: 's', + 84: 't', + 85: 'u', + 86: 'v', + 87: 'w', + 88: 'x', + 89: 'y', + 90: 'z', + 91: 'Left Windows Key / Left ⌘', + 92: 'Right Windows Key', + 93: 'Windows Menu / Right ⌘', + 96: 'numpad 0', + 97: 'numpad 1', + 98: 'numpad 2', + 99: 'numpad 3', + 100: 'numpad 4', + 101: 'numpad 5', + 102: 'numpad 6', + 103: 'numpad 7', + 104: 'numpad 8', + 105: 'numpad 9', + 106: 'multiply', + 107: 'add', + 109: 'subtract', + 110: 'decimal point', + 111: 'divide', + 112: 'f1', + 113: 'f2', + 114: 'f3', + 115: 'f4', + 116: 'f5', + 117: 'f6', + 118: 'f7', + 119: 'f8', + 120: 'f9', + 121: 'f10', + 122: 'f11', + 123: 'f12', + 124: 'f13', + 125: 'f14', + 126: 'f15', + 127: 'f16', + 128: 'f17', + 129: 'f18', + 130: 'f19', + 131: 'f20', + 132: 'f21', + 133: 'f22', + 134: 'f23', + 135: 'f24', + 144: 'num lock', + 145: 'scroll lock', + 186: ';', + 187: '=', + 188: ',', + 189: '‐', + 190: '.', + 191: '?', + 192: '`', + 219: '[', + 220: '\', + 221: ']', + 222: ''', +}; diff --git a/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/js/bootstrap.min.js b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/js/bootstrap.min.js new file mode 100644 index 0000000000000000000000000000000000000000..ca013b70fbbb50148bb85d33b5db8bb7a38fa4d7 --- /dev/null +++ b/platform/dataops/dto/.venv/lib/python3.12/site-packages/mkdocs/themes/mkdocs/js/bootstrap.min.js @@ -0,0 +1,7 @@ +/*! + * Bootstrap v4.3.1 (https://getbootstrap.com/) + * Copyright 2011-2019 The Bootstrap Authors (https://github.com/twbs/bootstrap/graphs/contributors) + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) + */ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("jquery"),require("popper.js")):"function"==typeof define&&define.amd?define(["exports","jquery","popper.js"],e):e((t=t||self).bootstrap={},t.jQuery,t.Popper)}(this,function(t,g,u){"use strict";function i(t,e){for(var n=0;nthis._items.length-1||t<0))if(this._isSliding)g(this._element).one(Q.SLID,function(){return e.to(t)});else{if(n===t)return this.pause(),void this.cycle();var i=ndocument.documentElement.clientHeight;!this._isBodyOverflowing&&t&&(this._element.style.paddingLeft=this._scrollbarWidth+"px"),this._isBodyOverflowing&&!t&&(this._element.style.paddingRight=this._scrollbarWidth+"px")},t._resetAdjustments=function(){this._element.style.paddingLeft="",this._element.style.paddingRight=""},t._checkScrollbar=function(){var t=document.body.getBoundingClientRect();this._isBodyOverflowing=t.left+t.right
',trigger:"hover focus",title:"",delay:0,html:!1,selector:!1,placement:"top",offset:0,container:!1,fallbackPlacement:"flip",boundary:"scrollParent",sanitize:!0,sanitizeFn:null,whiteList:Ee},je="show",He="out",Re={HIDE:"hide"+De,HIDDEN:"hidden"+De,SHOW:"show"+De,SHOWN:"shown"+De,INSERTED:"inserted"+De,CLICK:"click"+De,FOCUSIN:"focusin"+De,FOCUSOUT:"focusout"+De,MOUSEENTER:"mouseenter"+De,MOUSELEAVE:"mouseleave"+De},xe="fade",Fe="show",Ue=".tooltip-inner",We=".arrow",qe="hover",Me="focus",Ke="click",Qe="manual",Be=function(){function i(t,e){if("undefined"==typeof u)throw new TypeError("Bootstrap's tooltips require Popper.js (https://popper.js.org/)");this._isEnabled=!0,this._timeout=0,this._hoverState="",this._activeTrigger={},this._popper=null,this.element=t,this.config=this._getConfig(e),this.tip=null,this._setListeners()}var t=i.prototype;return t.enable=function(){this._isEnabled=!0},t.disable=function(){this._isEnabled=!1},t.toggleEnabled=function(){this._isEnabled=!this._isEnabled},t.toggle=function(t){if(this._isEnabled)if(t){var e=this.constructor.DATA_KEY,n=g(t.currentTarget).data(e);n||(n=new this.constructor(t.currentTarget,this._getDelegateConfig()),g(t.currentTarget).data(e,n)),n._activeTrigger.click=!n._activeTrigger.click,n._isWithActiveTrigger()?n._enter(null,n):n._leave(null,n)}else{if(g(this.getTipElement()).hasClass(Fe))return void this._leave(null,this);this._enter(null,this)}},t.dispose=function(){clearTimeout(this._timeout),g.removeData(this.element,this.constructor.DATA_KEY),g(this.element).off(this.constructor.EVENT_KEY),g(this.element).closest(".modal").off("hide.bs.modal"),this.tip&&g(this.tip).remove(),this._isEnabled=null,this._timeout=null,this._hoverState=null,(this._activeTrigger=null)!==this._popper&&this._popper.destroy(),this._popper=null,this.element=null,this.config=null,this.tip=null},t.show=function(){var e=this;if("none"===g(this.element).css("display"))throw new Error("Please use show on visible elements");var t=g.Event(this.constructor.Event.SHOW);if(this.isWithContent()&&this._isEnabled){g(this.element).trigger(t);var n=_.findShadowRoot(this.element),i=g.contains(null!==n?n:this.element.ownerDocument.documentElement,this.element);if(t.isDefaultPrevented()||!i)return;var o=this.getTipElement(),r=_.getUID(this.constructor.NAME);o.setAttribute("id",r),this.element.setAttribute("aria-describedby",r),this.setContent(),this.config.animation&&g(o).addClass(xe);var s="function"==typeof this.config.placement?this.config.placement.call(this,o,this.element):this.config.placement,a=this._getAttachment(s);this.addAttachmentClass(a);var l=this._getContainer();g(o).data(this.constructor.DATA_KEY,this),g.contains(this.element.ownerDocument.documentElement,this.tip)||g(o).appendTo(l),g(this.element).trigger(this.constructor.Event.INSERTED),this._popper=new u(this.element,o,{placement:a,modifiers:{offset:this._getOffset(),flip:{behavior:this.config.fallbackPlacement},arrow:{element:We},preventOverflow:{boundariesElement:this.config.boundary}},onCreate:function(t){t.originalPlacement!==t.placement&&e._handlePopperPlacementChange(t)},onUpdate:function(t){return e._handlePopperPlacementChange(t)}}),g(o).addClass(Fe),"ontouchstart"in document.documentElement&&g(document.body).children().on("mouseover",null,g.noop);var c=function(){e.config.animation&&e._fixTransition();var t=e._hoverState;e._hoverState=null,g(e.element).trigger(e.constructor.Event.SHOWN),t===He&&e._leave(null,e)};if(g(this.tip).hasClass(xe)){var h=_.getTransitionDurationFromElement(this.tip);g(this.tip).one(_.TRANSITION_END,c).emulateTransitionEnd(h)}else c()}},t.hide=function(t){var e=this,n=this.getTipElement(),i=g.Event(this.constructor.Event.HIDE),o=function(){e._hoverState!==je&&n.parentNode&&n.parentNode.removeChild(n),e._cleanTipClass(),e.element.removeAttribute("aria-describedby"),g(e.element).trigger(e.constructor.Event.HIDDEN),null!==e._popper&&e._popper.destroy(),t&&t()};if(g(this.element).trigger(i),!i.isDefaultPrevented()){if(g(n).removeClass(Fe),"ontouchstart"in document.documentElement&&g(document.body).children().off("mouseover",null,g.noop),this._activeTrigger[Ke]=!1,this._activeTrigger[Me]=!1,this._activeTrigger[qe]=!1,g(this.tip).hasClass(xe)){var r=_.getTransitionDurationFromElement(n);g(n).one(_.TRANSITION_END,o).emulateTransitionEnd(r)}else o();this._hoverState=""}},t.update=function(){null!==this._popper&&this._popper.scheduleUpdate()},t.isWithContent=function(){return Boolean(this.getTitle())},t.addAttachmentClass=function(t){g(this.getTipElement()).addClass(Ae+"-"+t)},t.getTipElement=function(){return this.tip=this.tip||g(this.config.template)[0],this.tip},t.setContent=function(){var t=this.getTipElement();this.setElementContent(g(t.querySelectorAll(Ue)),this.getTitle()),g(t).removeClass(xe+" "+Fe)},t.setElementContent=function(t,e){"object"!=typeof e||!e.nodeType&&!e.jquery?this.config.html?(this.config.sanitize&&(e=Se(e,this.config.whiteList,this.config.sanitizeFn)),t.html(e)):t.text(e):this.config.html?g(e).parent().is(t)||t.empty().append(e):t.text(g(e).text())},t.getTitle=function(){var t=this.element.getAttribute("data-original-title");return t||(t="function"==typeof this.config.title?this.config.title.call(this.element):this.config.title),t},t._getOffset=function(){var e=this,t={};return"function"==typeof this.config.offset?t.fn=function(t){return t.offsets=l({},t.offsets,e.config.offset(t.offsets,e.element)||{}),t}:t.offset=this.config.offset,t},t._getContainer=function(){return!1===this.config.container?document.body:_.isElement(this.config.container)?g(this.config.container):g(document).find(this.config.container)},t._getAttachment=function(t){return Pe[t.toUpperCase()]},t._setListeners=function(){var i=this;this.config.trigger.split(" ").forEach(function(t){if("click"===t)g(i.element).on(i.constructor.Event.CLICK,i.config.selector,function(t){return i.toggle(t)});else if(t!==Qe){var e=t===qe?i.constructor.Event.MOUSEENTER:i.constructor.Event.FOCUSIN,n=t===qe?i.constructor.Event.MOUSELEAVE:i.constructor.Event.FOCUSOUT;g(i.element).on(e,i.config.selector,function(t){return i._enter(t)}).on(n,i.config.selector,function(t){return i._leave(t)})}}),g(this.element).closest(".modal").on("hide.bs.modal",function(){i.element&&i.hide()}),this.config.selector?this.config=l({},this.config,{trigger:"manual",selector:""}):this._fixTitle()},t._fixTitle=function(){var t=typeof this.element.getAttribute("data-original-title");(this.element.getAttribute("title")||"string"!==t)&&(this.element.setAttribute("data-original-title",this.element.getAttribute("title")||""),this.element.setAttribute("title",""))},t._enter=function(t,e){var n=this.constructor.DATA_KEY;(e=e||g(t.currentTarget).data(n))||(e=new this.constructor(t.currentTarget,this._getDelegateConfig()),g(t.currentTarget).data(n,e)),t&&(e._activeTrigger["focusin"===t.type?Me:qe]=!0),g(e.getTipElement()).hasClass(Fe)||e._hoverState===je?e._hoverState=je:(clearTimeout(e._timeout),e._hoverState=je,e.config.delay&&e.config.delay.show?e._timeout=setTimeout(function(){e._hoverState===je&&e.show()},e.config.delay.show):e.show())},t._leave=function(t,e){var n=this.constructor.DATA_KEY;(e=e||g(t.currentTarget).data(n))||(e=new this.constructor(t.currentTarget,this._getDelegateConfig()),g(t.currentTarget).data(n,e)),t&&(e._activeTrigger["focusout"===t.type?Me:qe]=!1),e._isWithActiveTrigger()||(clearTimeout(e._timeout),e._hoverState=He,e.config.delay&&e.config.delay.hide?e._timeout=setTimeout(function(){e._hoverState===He&&e.hide()},e.config.delay.hide):e.hide())},t._isWithActiveTrigger=function(){for(var t in this._activeTrigger)if(this._activeTrigger[t])return!0;return!1},t._getConfig=function(t){var e=g(this.element).data();return Object.keys(e).forEach(function(t){-1!==Oe.indexOf(t)&&delete e[t]}),"number"==typeof(t=l({},this.constructor.Default,e,"object"==typeof t&&t?t:{})).delay&&(t.delay={show:t.delay,hide:t.delay}),"number"==typeof t.title&&(t.title=t.title.toString()),"number"==typeof t.content&&(t.content=t.content.toString()),_.typeCheckConfig(be,t,this.constructor.DefaultType),t.sanitize&&(t.template=Se(t.template,t.whiteList,t.sanitizeFn)),t},t._getDelegateConfig=function(){var t={};if(this.config)for(var e in this.config)this.constructor.Default[e]!==this.config[e]&&(t[e]=this.config[e]);return t},t._cleanTipClass=function(){var t=g(this.getTipElement()),e=t.attr("class").match(Ne);null!==e&&e.length&&t.removeClass(e.join(""))},t._handlePopperPlacementChange=function(t){var e=t.instance;this.tip=e.popper,this._cleanTipClass(),this.addAttachmentClass(this._getAttachment(t.placement))},t._fixTransition=function(){var t=this.getTipElement(),e=this.config.animation;null===t.getAttribute("x-placement")&&(g(t).removeClass(xe),this.config.animation=!1,this.hide(),this.show(),this.config.animation=e)},i._jQueryInterface=function(n){return this.each(function(){var t=g(this).data(Ie),e="object"==typeof n&&n;if((t||!/dispose|hide/.test(n))&&(t||(t=new i(this,e),g(this).data(Ie,t)),"string"==typeof n)){if("undefined"==typeof t[n])throw new TypeError('No method named "'+n+'"');t[n]()}})},s(i,null,[{key:"VERSION",get:function(){return"4.3.1"}},{key:"Default",get:function(){return Le}},{key:"NAME",get:function(){return be}},{key:"DATA_KEY",get:function(){return Ie}},{key:"Event",get:function(){return Re}},{key:"EVENT_KEY",get:function(){return De}},{key:"DefaultType",get:function(){return ke}}]),i}();g.fn[be]=Be._jQueryInterface,g.fn[be].Constructor=Be,g.fn[be].noConflict=function(){return g.fn[be]=we,Be._jQueryInterface};var Ve="popover",Ye="bs.popover",ze="."+Ye,Xe=g.fn[Ve],$e="bs-popover",Ge=new RegExp("(^|\\s)"+$e+"\\S+","g"),Je=l({},Be.Default,{placement:"right",trigger:"click",content:"",template:''}),Ze=l({},Be.DefaultType,{content:"(string|element|function)"}),tn="fade",en="show",nn=".popover-header",on=".popover-body",rn={HIDE:"hide"+ze,HIDDEN:"hidden"+ze,SHOW:"show"+ze,SHOWN:"shown"+ze,INSERTED:"inserted"+ze,CLICK:"click"+ze,FOCUSIN:"focusin"+ze,FOCUSOUT:"focusout"+ze,MOUSEENTER:"mouseenter"+ze,MOUSELEAVE:"mouseleave"+ze},sn=function(t){var e,n;function i(){return t.apply(this,arguments)||this}n=t,(e=i).prototype=Object.create(n.prototype),(e.prototype.constructor=e).__proto__=n;var o=i.prototype;return o.isWithContent=function(){return this.getTitle()||this._getContent()},o.addAttachmentClass=function(t){g(this.getTipElement()).addClass($e+"-"+t)},o.getTipElement=function(){return this.tip=this.tip||g(this.config.template)[0],this.tip},o.setContent=function(){var t=g(this.getTipElement());this.setElementContent(t.find(nn),this.getTitle());var e=this._getContent();"function"==typeof e&&(e=e.call(this.element)),this.setElementContent(t.find(on),e),t.removeClass(tn+" "+en)},o._getContent=function(){return this.element.getAttribute("data-content")||this.config.content},o._cleanTipClass=function(){var t=g(this.getTipElement()),e=t.attr("class").match(Ge);null!==e&&0=this._offsets[o]&&("undefined"==typeof this._offsets[o+1]||t+~]|"+M+")"+M+"*"),U=new RegExp(M+"|>"),X=new RegExp(F),V=new RegExp("^"+I+"$"),G={ID:new RegExp("^#("+I+")"),CLASS:new RegExp("^\\.("+I+")"),TAG:new RegExp("^("+I+"|[*])"),ATTR:new RegExp("^"+W),PSEUDO:new RegExp("^"+F),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+R+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/HTML$/i,Q=/^(?:input|select|textarea|button)$/i,J=/^h\d$/i,K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ee=/[+~]/,te=new RegExp("\\\\[\\da-fA-F]{1,6}"+M+"?|\\\\([^\\r\\n\\f])","g"),ne=function(e,t){var n="0x"+e.slice(1)-65536;return t||(n<0?String.fromCharCode(n+65536):String.fromCharCode(n>>10|55296,1023&n|56320))},re=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ie=function(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},oe=function(){T()},ae=be(function(e){return!0===e.disabled&&"fieldset"===e.nodeName.toLowerCase()},{dir:"parentNode",next:"legend"});try{H.apply(t=O.call(p.childNodes),p.childNodes),t[p.childNodes.length].nodeType}catch(e){H={apply:t.length?function(e,t){L.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function se(t,e,n,r){var i,o,a,s,u,l,c,f=e&&e.ownerDocument,p=e?e.nodeType:9;if(n=n||[],"string"!=typeof t||!t||1!==p&&9!==p&&11!==p)return n;if(!r&&(T(e),e=e||C,E)){if(11!==p&&(u=Z.exec(t)))if(i=u[1]){if(9===p){if(!(a=e.getElementById(i)))return n;if(a.id===i)return n.push(a),n}else if(f&&(a=f.getElementById(i))&&y(e,a)&&a.id===i)return n.push(a),n}else{if(u[2])return H.apply(n,e.getElementsByTagName(t)),n;if((i=u[3])&&d.getElementsByClassName&&e.getElementsByClassName)return H.apply(n,e.getElementsByClassName(i)),n}if(d.qsa&&!N[t+" "]&&(!v||!v.test(t))&&(1!==p||"object"!==e.nodeName.toLowerCase())){if(c=t,f=e,1===p&&(U.test(t)||z.test(t))){(f=ee.test(t)&&ye(e.parentNode)||e)===e&&d.scope||((s=e.getAttribute("id"))?s=s.replace(re,ie):e.setAttribute("id",s=S)),o=(l=h(t)).length;while(o--)l[o]=(s?"#"+s:":scope")+" "+xe(l[o]);c=l.join(",")}try{return H.apply(n,f.querySelectorAll(c)),n}catch(e){N(t,!0)}finally{s===S&&e.removeAttribute("id")}}}return g(t.replace($,"$1"),e,n,r)}function ue(){var r=[];return function e(t,n){return r.push(t+" ")>b.cacheLength&&delete e[r.shift()],e[t+" "]=n}}function le(e){return e[S]=!0,e}function ce(e){var t=C.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function fe(e,t){var n=e.split("|"),r=n.length;while(r--)b.attrHandle[n[r]]=t}function pe(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function de(t){return function(e){return"input"===e.nodeName.toLowerCase()&&e.type===t}}function he(n){return function(e){var t=e.nodeName.toLowerCase();return("input"===t||"button"===t)&&e.type===n}}function ge(t){return function(e){return"form"in e?e.parentNode&&!1===e.disabled?"label"in e?"label"in e.parentNode?e.parentNode.disabled===t:e.disabled===t:e.isDisabled===t||e.isDisabled!==!t&&ae(e)===t:e.disabled===t:"label"in e&&e.disabled===t}}function ve(a){return le(function(o){return o=+o,le(function(e,t){var n,r=a([],e.length,o),i=r.length;while(i--)e[n=r[i]]&&(e[n]=!(t[n]=e[n]))})})}function ye(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}for(e in d=se.support={},i=se.isXML=function(e){var t=e&&e.namespaceURI,n=e&&(e.ownerDocument||e).documentElement;return!Y.test(t||n&&n.nodeName||"HTML")},T=se.setDocument=function(e){var t,n,r=e?e.ownerDocument||e:p;return r!=C&&9===r.nodeType&&r.documentElement&&(a=(C=r).documentElement,E=!i(C),p!=C&&(n=C.defaultView)&&n.top!==n&&(n.addEventListener?n.addEventListener("unload",oe,!1):n.attachEvent&&n.attachEvent("onunload",oe)),d.scope=ce(function(e){return a.appendChild(e).appendChild(C.createElement("div")),"undefined"!=typeof e.querySelectorAll&&!e.querySelectorAll(":scope fieldset div").length}),d.attributes=ce(function(e){return e.className="i",!e.getAttribute("className")}),d.getElementsByTagName=ce(function(e){return e.appendChild(C.createComment("")),!e.getElementsByTagName("*").length}),d.getElementsByClassName=K.test(C.getElementsByClassName),d.getById=ce(function(e){return a.appendChild(e).id=S,!C.getElementsByName||!C.getElementsByName(S).length}),d.getById?(b.filter.ID=function(e){var t=e.replace(te,ne);return function(e){return e.getAttribute("id")===t}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n=t.getElementById(e);return n?[n]:[]}}):(b.filter.ID=function(e){var n=e.replace(te,ne);return function(e){var t="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return t&&t.value===n}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),b.find.TAG=d.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):d.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},b.find.CLASS=d.getElementsByClassName&&function(e,t){if("undefined"!=typeof t.getElementsByClassName&&E)return t.getElementsByClassName(e)},s=[],v=[],(d.qsa=K.test(C.querySelectorAll))&&(ce(function(e){var t;a.appendChild(e).innerHTML="",e.querySelectorAll("[msallowcapture^='']").length&&v.push("[*^$]="+M+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||v.push("\\["+M+"*(?:value|"+R+")"),e.querySelectorAll("[id~="+S+"-]").length||v.push("~="),(t=C.createElement("input")).setAttribute("name",""),e.appendChild(t),e.querySelectorAll("[name='']").length||v.push("\\["+M+"*name"+M+"*="+M+"*(?:''|\"\")"),e.querySelectorAll(":checked").length||v.push(":checked"),e.querySelectorAll("a#"+S+"+*").length||v.push(".#.+[+~]"),e.querySelectorAll("\\\f"),v.push("[\\r\\n\\f]")}),ce(function(e){e.innerHTML="";var t=C.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&v.push("name"+M+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&v.push(":enabled",":disabled"),a.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&v.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),v.push(",.*:")})),(d.matchesSelector=K.test(c=a.matches||a.webkitMatchesSelector||a.mozMatchesSelector||a.oMatchesSelector||a.msMatchesSelector))&&ce(function(e){d.disconnectedMatch=c.call(e,"*"),c.call(e,"[s!='']:x"),s.push("!=",F)}),v=v.length&&new RegExp(v.join("|")),s=s.length&&new RegExp(s.join("|")),t=K.test(a.compareDocumentPosition),y=t||K.test(a.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},j=t?function(e,t){if(e===t)return l=!0,0;var n=!e.compareDocumentPosition-!t.compareDocumentPosition;return n||(1&(n=(e.ownerDocument||e)==(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!d.sortDetached&&t.compareDocumentPosition(e)===n?e==C||e.ownerDocument==p&&y(p,e)?-1:t==C||t.ownerDocument==p&&y(p,t)?1:u?P(u,e)-P(u,t):0:4&n?-1:1)}:function(e,t){if(e===t)return l=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,a=[e],s=[t];if(!i||!o)return e==C?-1:t==C?1:i?-1:o?1:u?P(u,e)-P(u,t):0;if(i===o)return pe(e,t);n=e;while(n=n.parentNode)a.unshift(n);n=t;while(n=n.parentNode)s.unshift(n);while(a[r]===s[r])r++;return r?pe(a[r],s[r]):a[r]==p?-1:s[r]==p?1:0}),C},se.matches=function(e,t){return se(e,null,null,t)},se.matchesSelector=function(e,t){if(T(e),d.matchesSelector&&E&&!N[t+" "]&&(!s||!s.test(t))&&(!v||!v.test(t)))try{var n=c.call(e,t);if(n||d.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(e){N(t,!0)}return 0":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(te,ne),e[3]=(e[3]||e[4]||e[5]||"").replace(te,ne),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||se.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&se.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return G.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&X.test(n)&&(t=h(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(te,ne).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=m[e+" "];return t||(t=new RegExp("(^|"+M+")"+e+"("+M+"|$)"))&&m(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(n,r,i){return function(e){var t=se.attr(e,n);return null==t?"!="===r:!r||(t+="","="===r?t===i:"!="===r?t!==i:"^="===r?i&&0===t.indexOf(i):"*="===r?i&&-1:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function j(e,n,r){return m(n)?S.grep(e,function(e,t){return!!n.call(e,t,e)!==r}):n.nodeType?S.grep(e,function(e){return e===n!==r}):"string"!=typeof n?S.grep(e,function(e){return-1)[^>]*|#([\w-]+))$/;(S.fn.init=function(e,t,n){var r,i;if(!e)return this;if(n=n||D,"string"==typeof e){if(!(r="<"===e[0]&&">"===e[e.length-1]&&3<=e.length?[null,e,null]:q.exec(e))||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof S?t[0]:t,S.merge(this,S.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:E,!0)),N.test(r[1])&&S.isPlainObject(t))for(r in t)m(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}return(i=E.getElementById(r[2]))&&(this[0]=i,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):m(e)?void 0!==n.ready?n.ready(e):e(S):S.makeArray(e,this)}).prototype=S.fn,D=S(E);var L=/^(?:parents|prev(?:Until|All))/,H={children:!0,contents:!0,next:!0,prev:!0};function O(e,t){while((e=e[t])&&1!==e.nodeType);return e}S.fn.extend({has:function(e){var t=S(e,this),n=t.length;return this.filter(function(){for(var e=0;e\x20\t\r\n\f]*)/i,he=/^$|^module$|\/(?:java|ecma)script/i;ce=E.createDocumentFragment().appendChild(E.createElement("div")),(fe=E.createElement("input")).setAttribute("type","radio"),fe.setAttribute("checked","checked"),fe.setAttribute("name","t"),ce.appendChild(fe),y.checkClone=ce.cloneNode(!0).cloneNode(!0).lastChild.checked,ce.innerHTML="",y.noCloneChecked=!!ce.cloneNode(!0).lastChild.defaultValue,ce.innerHTML="",y.option=!!ce.lastChild;var ge={thead:[1,"","
"],col:[2,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};function ve(e,t){var n;return n="undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t||"*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&A(e,t)?S.merge([e],n):n}function ye(e,t){for(var n=0,r=e.length;n",""]);var me=/<|&#?\w+;/;function xe(e,t,n,r,i){for(var o,a,s,u,l,c,f=t.createDocumentFragment(),p=[],d=0,h=e.length;d\s*$/g;function je(e,t){return A(e,"table")&&A(11!==t.nodeType?t:t.firstChild,"tr")&&S(e).children("tbody")[0]||e}function De(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function qe(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Le(e,t){var n,r,i,o,a,s;if(1===t.nodeType){if(Y.hasData(e)&&(s=Y.get(e).events))for(i in Y.remove(t,"handle events"),s)for(n=0,r=s[i].length;n").attr(n.scriptAttrs||{}).prop({charset:n.scriptCharset,src:n.url}).on("load error",i=function(e){r.remove(),i=null,e&&t("error"===e.type?404:200,e.type)}),E.head.appendChild(r[0])},abort:function(){i&&i()}}});var _t,zt=[],Ut=/(=)\?(?=&|$)|\?\?/;S.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=zt.pop()||S.expando+"_"+wt.guid++;return this[e]=!0,e}}),S.ajaxPrefilter("json jsonp",function(e,t,n){var r,i,o,a=!1!==e.jsonp&&(Ut.test(e.url)?"url":"string"==typeof e.data&&0===(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&Ut.test(e.data)&&"data");if(a||"jsonp"===e.dataTypes[0])return r=e.jsonpCallback=m(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,a?e[a]=e[a].replace(Ut,"$1"+r):!1!==e.jsonp&&(e.url+=(Tt.test(e.url)?"&":"?")+e.jsonp+"="+r),e.converters["script json"]=function(){return o||S.error(r+" was not called"),o[0]},e.dataTypes[0]="json",i=C[r],C[r]=function(){o=arguments},n.always(function(){void 0===i?S(C).removeProp(r):C[r]=i,e[r]&&(e.jsonpCallback=t.jsonpCallback,zt.push(r)),o&&m(i)&&i(o[0]),o=i=void 0}),"script"}),y.createHTMLDocument=((_t=E.implementation.createHTMLDocument("").body).innerHTML="
",2===_t.childNodes.length),S.parseHTML=function(e,t,n){return"string"!=typeof e?[]:("boolean"==typeof t&&(n=t,t=!1),t||(y.createHTMLDocument?((r=(t=E.implementation.createHTMLDocument("")).createElement("base")).href=E.location.href,t.head.appendChild(r)):t=E),o=!n&&[],(i=N.exec(e))?[t.createElement(i[1])]:(i=xe([e],t,o),o&&o.length&&S(o).remove(),S.merge([],i.childNodes)));var r,i,o},S.fn.load=function(e,t,n){var r,i,o,a=this,s=e.indexOf(" ");return-1").append(S.parseHTML(e)).find(r):e)}).always(n&&function(e,t){a.each(function(){n.apply(this,o||[e.responseText,t,e])})}),this},S.expr.pseudos.animated=function(t){return S.grep(S.timers,function(e){return t===e.elem}).length},S.offset={setOffset:function(e,t,n){var r,i,o,a,s,u,l=S.css(e,"position"),c=S(e),f={};"static"===l&&(e.style.position="relative"),s=c.offset(),o=S.css(e,"top"),u=S.css(e,"left"),("absolute"===l||"fixed"===l)&&-1<(o+u).indexOf("auto")?(a=(r=c.position()).top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(u)||0),m(t)&&(t=t.call(e,n,S.extend({},s))),null!=t.top&&(f.top=t.top-s.top+a),null!=t.left&&(f.left=t.left-s.left+i),"using"in t?t.using.call(e,f):c.css(f)}},S.fn.extend({offset:function(t){if(arguments.length)return void 0===t?this:this.each(function(e){S.offset.setOffset(this,t,e)});var e,n,r=this[0];return r?r.getClientRects().length?(e=r.getBoundingClientRect(),n=r.ownerDocument.defaultView,{top:e.top+n.pageYOffset,left:e.left+n.pageXOffset}):{top:0,left:0}:void 0},position:function(){if(this[0]){var e,t,n,r=this[0],i={top:0,left:0};if("fixed"===S.css(r,"position"))t=r.getBoundingClientRect();else{t=this.offset(),n=r.ownerDocument,e=r.offsetParent||n.documentElement;while(e&&(e===n.body||e===n.documentElement)&&"static"===S.css(e,"position"))e=e.parentNode;e&&e!==r&&1===e.nodeType&&((i=S(e).offset()).top+=S.css(e,"borderTopWidth",!0),i.left+=S.css(e,"borderLeftWidth",!0))}return{top:t.top-i.top-S.css(r,"marginTop",!0),left:t.left-i.left-S.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent;while(e&&"static"===S.css(e,"position"))e=e.offsetParent;return e||re})}}),S.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,i){var o="pageYOffset"===i;S.fn[t]=function(e){return $(this,function(e,t,n){var r;if(x(e)?r=e:9===e.nodeType&&(r=e.defaultView),void 0===n)return r?r[i]:e[t];r?r.scrollTo(o?r.pageXOffset:n,o?n:r.pageYOffset):e[t]=n},t,e,arguments.length)}}),S.each(["top","left"],function(e,n){S.cssHooks[n]=Fe(y.pixelPosition,function(e,t){if(t)return t=We(e,n),Pe.test(t)?S(e).position()[n]+"px":t})}),S.each({Height:"height",Width:"width"},function(a,s){S.each({padding:"inner"+a,content:s,"":"outer"+a},function(r,o){S.fn[o]=function(e,t){var n=arguments.length&&(r||"boolean"!=typeof e),i=r||(!0===e||!0===t?"margin":"border");return $(this,function(e,t,n){var r;return x(e)?0===o.indexOf("outer")?e["inner"+a]:e.document.documentElement["client"+a]:9===e.nodeType?(r=e.documentElement,Math.max(e.body["scroll"+a],r["scroll"+a],e.body["offset"+a],r["offset"+a],r["client"+a])):void 0===n?S.css(e,t,i):S.style(e,t,n,i)},s,n?e:void 0,n)}})}),S.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){S.fn[t]=function(e){return this.on(t,e)}}),S.fn.extend({bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}}),S.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(e,n){S.fn[n]=function(e,t){return 0