diff --git a/demo.html b/demo.html index 466fb88..6477458 100644 --- a/demo.html +++ b/demo.html @@ -1,30 +1,90 @@ - - +

Group Chat

+ +
+ + + + +
+ +
+ + +
+ +

Room: None

+ +
+ + +
+ + + + diff --git a/demos/README.md b/demos/README.md new file mode 100644 index 0000000..265fc06 --- /dev/null +++ b/demos/README.md @@ -0,0 +1,7 @@ +You can test all demos LIVE here: + +* https://muazkhan.com:9001/ + +## License + +[RTCMultiConnection](https://github.com/muaz-khan/RTCMultiConnection) is released under [MIT licence](https://github.com/muaz-khan/RTCMultiConnection/blob/master/LICENSE.md) . Copyright (c) [Muaz Khan](https://MuazKhan.com/). diff --git a/demos/SSEConnection.html b/demos/SSEConnection.html new file mode 100644 index 0000000..59d6747 --- /dev/null +++ b/demos/SSEConnection.html @@ -0,0 +1,218 @@ + + + + + SSE+PHP Signaling using RTCMultiConnection + + + + + + +
+ + MenuMenu + +
+ +

+ SSE+PHP Signaling using RTCMultiConnection +

This demo is using SSE (Server Sent Events) to setup WebRTC one-to-one connection. Check PHP Source Codes

+

+ +
+ + + + + + + +
+
+ + + + + + + + + + + diff --git a/demos/SSEConnection/README.md b/demos/SSEConnection/README.md new file mode 100644 index 0000000..321ea02 --- /dev/null +++ b/demos/SSEConnection/README.md @@ -0,0 +1,18 @@ +Live Demo: https://muazkhan.com:9001/demos/SSEConnection.html + +Server Sent Events (SSE) are used to setup WebRTC peer-to-peer connections. + +1. Download above directory +2. Upload to your PHP webserver +3. Give the directory both read-and-write permissions +4. Go to [`dev/SSEConnection.js`](https://github.com/muaz-khan/RTCMultiConnection/blob/master/dev/SSEConnection.js) and replace [`sseDirPath`](https://github.com/muaz-khan/RTCMultiConnection/blob/master/dev/SSEConnection.js#L6) with `sseDirPath='https://php-server.com/SSEConnection/';` +5. Try [`demos/SSEConnection.html`](https://github.com/muaz-khan/RTCMultiConnection/blob/master/demos/SSEConnection.html) demo on HTTPs or localhost. + +Relevant files: + +1. https://github.com/muaz-khan/RTCMultiConnection/blob/master/dev/SSEConnection.js +2. https://github.com/muaz-khan/RTCMultiConnection/blob/master/demos/SSEConnection.html + +PHP Source: + +* https://github.com/muaz-khan/RTCMultiConnection/tree/master/demos/SSEConnection diff --git a/demos/SSEConnection/SSE.php b/demos/SSEConnection/SSE.php new file mode 100644 index 0000000..41b3668 --- /dev/null +++ b/demos/SSEConnection/SSE.php @@ -0,0 +1,29 @@ + $val) { + // skip duplicate entries for future requests + // todo: find a better solution to clear only entries; NOT the entire JSON. + removeJSON($me, $receiver); +} + +ob_flush(); +flush(); +?> \ No newline at end of file diff --git a/demos/SSEConnection/checkPresence.php b/demos/SSEConnection/checkPresence.php new file mode 100644 index 0000000..43b94d7 --- /dev/null +++ b/demos/SSEConnection/checkPresence.php @@ -0,0 +1,24 @@ + true, + 'roomid' => getParam('roomid') + )); + } else { + echo json_encode(array( + 'isRoomExist' => false, + 'roomid' => getParam('roomid') + )); + } +} +?> \ No newline at end of file diff --git a/demos/SSEConnection/enableCORS.php b/demos/SSEConnection/enableCORS.php new file mode 100644 index 0000000..464c599 --- /dev/null +++ b/demos/SSEConnection/enableCORS.php @@ -0,0 +1,32 @@ + \ No newline at end of file diff --git a/demos/SSEConnection/get-param.php b/demos/SSEConnection/get-param.php new file mode 100644 index 0000000..bb38015 --- /dev/null +++ b/demos/SSEConnection/get-param.php @@ -0,0 +1,22 @@ + \ No newline at end of file diff --git a/demos/SSEConnection/publish.php b/demos/SSEConnection/publish.php new file mode 100644 index 0000000..e854ab7 --- /dev/null +++ b/demos/SSEConnection/publish.php @@ -0,0 +1,20 @@ + \ No newline at end of file diff --git a/demos/SSEConnection/rooms/README.md b/demos/SSEConnection/rooms/README.md new file mode 100644 index 0000000..8938ad9 --- /dev/null +++ b/demos/SSEConnection/rooms/README.md @@ -0,0 +1,20 @@ +> "rooms" directory is used to store json-files created via "publish.php" + +Live Demo: https://muazkhan.com:9001/demos/SSEConnection.html + +Server Sent Events (SSE) are used to setup WebRTC peer-to-peer connections. + +1. Download above directory +2. Upload to your PHP webserver +3. Give the directory both read-and-write permissions +4. Go to [`dev/SSEConnection.js`](https://github.com/muaz-khan/RTCMultiConnection/blob/master/dev/SSEConnection.js) and replace [`sseDirPath`](https://github.com/muaz-khan/RTCMultiConnection/blob/master/dev/SSEConnection.js#L6) with `sseDirPath='https://php-server.com/SSEConnection/';` +5. Try [`demos/SSEConnection.html`](https://github.com/muaz-khan/RTCMultiConnection/blob/master/demos/SSEConnection.html) demo on HTTPs or localhost. + +Relevant files: + +1. https://github.com/muaz-khan/RTCMultiConnection/blob/master/dev/SSEConnection.js +2. https://github.com/muaz-khan/RTCMultiConnection/blob/master/demos/SSEConnection.html + +PHP Source: + +* https://github.com/muaz-khan/RTCMultiConnection/tree/master/demos/SSEConnection diff --git a/demos/SSEConnection/write-json.php b/demos/SSEConnection/write-json.php new file mode 100644 index 0000000..95e1736 --- /dev/null +++ b/demos/SSEConnection/write-json.php @@ -0,0 +1,92 @@ + \ No newline at end of file diff --git a/demos/Scalable-Broadcast.html b/demos/Scalable-Broadcast.html new file mode 100644 index 0000000..e63c197 --- /dev/null +++ b/demos/Scalable-Broadcast.html @@ -0,0 +1,389 @@ + + + + + WebRTC Scalable Broadcast using RTCMultiConnection + + + + + + +
+ + MenuMenu + +
+ +

+ WebRTC Scalable Broadcast using RTCMultiConnection +

+ Use peer-to-peer protocol to broadcast your video over 20+ users. +

+

+ +
+

+

+ + + +
+

+ + +
+ + + + + + + +
+

How this works?

+

+ This module simply initializes socket.io and configures it in a way that single audio/video/screen stream can be shared/relayed over unlimited users without any bandwidth/CPU usage issues. Everything happens peer-to-peer! +

+

+ Check this thread or this github repository. +

+
+ + + + + + diff --git a/demos/audio-conferencing.html b/demos/audio-conferencing.html new file mode 100644 index 0000000..f87d28e --- /dev/null +++ b/demos/audio-conferencing.html @@ -0,0 +1,242 @@ + + + + + Audio Conferencing using RTCMultiConnection + + + + + + +
+ + MenuMenu + +
+ +

+ Audio Conferencing using RTCMultiConnection +

+ Multi-user (many-to-many) audio-calling using mesh networking model. +

+

+ +
+ + + + + + + +
+
+ + + + + + + + + + + + + + diff --git a/demos/call-by-username.html b/demos/call-by-username.html new file mode 100644 index 0000000..0e48f8e --- /dev/null +++ b/demos/call-by-username.html @@ -0,0 +1,290 @@ + + + + + Call-By-UserName using RTCMultiConnection + + + + + + + +
+ + MenuMenu + +
+ +

+ Call-By-UserName +

+ Call Any Person By His UserName. +

+

+ +
+ + + + + + + + + + + + + + + +
+ + + + +
+ + + + +
+
+
+ + +
+ + + + + + + + + + + + + + + diff --git a/demos/camera-zoom.html b/demos/camera-zoom.html new file mode 100644 index 0000000..16be104 --- /dev/null +++ b/demos/camera-zoom.html @@ -0,0 +1,332 @@ + + + + + + + + + Zoom Camera during WebRTC Live Streaming | RTCMultiConnection + + + + + + + + +
+ +
+

Zoom Camera during WebRTC Live Streaming | RTCMultiConnection

+

+ HOME + © + Muaz Khan . + @WebRTCWeb . + Github . + Latest issues . + What's New? +

+
+ + +
+ +
+
+ + + + +

+ + + +
+ +
+
+ + + + + + + +
+

Latest Updates

+
+
+ +
+

Latest Issues

+
+
+ +
+

Feedback

+
+ +
+ Enter your email too; if you want "direct" reply! +
+ + + + + + +
+ + + + + + diff --git a/demos/css/bootstrap.min.css b/demos/css/bootstrap.min.css new file mode 100644 index 0000000..8826912 --- /dev/null +++ b/demos/css/bootstrap.min.css @@ -0,0 +1,7 @@ +/*! + * 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:#007bff;--indigo:#6610f2;--purple:#6f42c1;--pink:#e83e8c;--red:#dc3545;--orange:#fd7e14;--yellow:#ffc107;--green:#28a745;--teal:#20c997;--cyan:#17a2b8;--white:#fff;--gray:#6c757d;--gray-dark:#343a40;--primary:#007bff;--secondary:#6c757d;--success:#28a745;--info:#17a2b8;--warning:#ffc107;--danger:#dc3545;--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}*,::after,::before{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:#212529;text-align:left;background-color:#fff}[tabindex="-1"]:focus{outline:0!important}hr{box-sizing:content-box;height:0;overflow:visible}h1,h2,h3,h4,h5,h6{margin-top:0;margin-bottom:.5rem}p{margin-top:0;margin-bottom:1rem}abbr[data-original-title],abbr[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}dl,ol,ul{margin-top:0;margin-bottom:1rem}ol ol,ol ul,ul ol,ul ul{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:#007bff;text-decoration:none;background-color:transparent;-webkit-text-decoration-skip:objects}a:hover{color:#0056b3;text-decoration:underline}a:not([href]):not([tabindex]){color:inherit;text-decoration:none}a:not([href]):not([tabindex]):focus,a:not([href]):not([tabindex]):hover{color:inherit;text-decoration:none}a:not([href]):not([tabindex]):focus{outline:0}code,kbd,pre,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:.75rem;padding-bottom:.75rem;color:#6c757d;text-align:left;caption-side:bottom}th{text-align:inherit}label{display:inline-block;margin-bottom:.5rem}button{border-radius:0}button:focus{outline:1px dotted;outline:5px auto -webkit-focus-ring-color}button,input,optgroup,select,textarea{margin:0;font-family:inherit;font-size:inherit;line-height:inherit}button,input{overflow:visible}button,select{text-transform:none}[type=reset],[type=submit],button,html [type=button]{-webkit-appearance:button}[type=button]::-moz-focus-inner,[type=reset]::-moz-focus-inner,[type=submit]::-moz-focus-inner,button::-moz-focus-inner{padding:0;border-style:none}input[type=checkbox],input[type=radio]{box-sizing:border-box;padding:0}input[type=date],input[type=datetime-local],input[type=month],input[type=time]{-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:.5rem;font-family:inherit;font-weight:500;line-height:1.2;color:inherit}.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,.1)}.small,small{font-size:80%;font-weight:400}.mark,mark{padding:.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:.5rem}.initialism{font-size:90%;text-transform:uppercase}.blockquote{margin-bottom:1rem;font-size:1.25rem}.blockquote-footer{display:block;font-size:80%;color:#6c757d}.blockquote-footer::before{content:"\2014 \00A0"}.img-fluid{max-width:100%;height:auto}.img-thumbnail{padding:.25rem;background-color:#fff;border:1px solid #dee2e6;border-radius:.25rem;max-width:100%;height:auto}.figure{display:inline-block}.figure-img{margin-bottom:.5rem;line-height:1}.figure-caption{font-size:90%;color:#6c757d}code{font-size:87.5%;color:#e83e8c;word-break:break-word}a>code{color:inherit}kbd{padding:.2rem .4rem;font-size:87.5%;color:#fff;background-color:#212529;border-radius:.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:-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,.col-1,.col-10,.col-11,.col-12,.col-2,.col-3,.col-4,.col-5,.col-6,.col-7,.col-8,.col-9,.col-auto,.col-lg,.col-lg-1,.col-lg-10,.col-lg-11,.col-lg-12,.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-auto,.col-md,.col-md-1,.col-md-10,.col-md-11,.col-md-12,.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-auto,.col-sm,.col-sm-1,.col-sm-10,.col-sm-11,.col-sm-12,.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-auto,.col-xl,.col-xl-1,.col-xl-10,.col-xl-11,.col-xl-12,.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-auto{position:relative;width:100%;min-height:1px;padding-right:15px;padding-left:15px}.col{-ms-flex-preferred-size:0;flex-basis:0;-ms-flex-positive:1;flex-grow:1;max-width:100%}.col-auto{-ms-flex:0 0 auto;flex:0 0 auto;width:auto;max-width:none}.col-1{-ms-flex:0 0 8.333333%;flex:0 0 8.333333%;max-width:8.333333%}.col-2{-ms-flex:0 0 16.666667%;flex:0 0 16.666667%;max-width:16.666667%}.col-3{-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.col-4{-ms-flex:0 0 33.333333%;flex:0 0 33.333333%;max-width:33.333333%}.col-5{-ms-flex:0 0 41.666667%;flex:0 0 41.666667%;max-width:41.666667%}.col-6{-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.col-7{-ms-flex:0 0 58.333333%;flex:0 0 58.333333%;max-width:58.333333%}.col-8{-ms-flex:0 0 66.666667%;flex:0 0 66.666667%;max-width:66.666667%}.col-9{-ms-flex:0 0 75%;flex:0 0 75%;max-width:75%}.col-10{-ms-flex:0 0 83.333333%;flex:0 0 83.333333%;max-width:83.333333%}.col-11{-ms-flex:0 0 91.666667%;flex:0 0 91.666667%;max-width:91.666667%}.col-12{-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.order-first{-ms-flex-order:-1;order:-1}.order-last{-ms-flex-order:13;order:13}.order-0{-ms-flex-order:0;order:0}.order-1{-ms-flex-order:1;order:1}.order-2{-ms-flex-order:2;order:2}.order-3{-ms-flex-order:3;order:3}.order-4{-ms-flex-order:4;order:4}.order-5{-ms-flex-order:5;order:5}.order-6{-ms-flex-order:6;order:6}.order-7{-ms-flex-order:7;order:7}.order-8{-ms-flex-order:8;order:8}.order-9{-ms-flex-order:9;order:9}.order-10{-ms-flex-order:10;order:10}.order-11{-ms-flex-order:11;order:11}.order-12{-ms-flex-order:12;order:12}.offset-1{margin-left:8.333333%}.offset-2{margin-left:16.666667%}.offset-3{margin-left:25%}.offset-4{margin-left:33.333333%}.offset-5{margin-left:41.666667%}.offset-6{margin-left:50%}.offset-7{margin-left:58.333333%}.offset-8{margin-left:66.666667%}.offset-9{margin-left:75%}.offset-10{margin-left:83.333333%}.offset-11{margin-left:91.666667%}@media (min-width:576px){.col-sm{-ms-flex-preferred-size:0;flex-basis:0;-ms-flex-positive:1;flex-grow:1;max-width:100%}.col-sm-auto{-ms-flex:0 0 auto;flex:0 0 auto;width:auto;max-width:none}.col-sm-1{-ms-flex:0 0 8.333333%;flex:0 0 8.333333%;max-width:8.333333%}.col-sm-2{-ms-flex:0 0 16.666667%;flex:0 0 16.666667%;max-width:16.666667%}.col-sm-3{-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.col-sm-4{-ms-flex:0 0 33.333333%;flex:0 0 33.333333%;max-width:33.333333%}.col-sm-5{-ms-flex:0 0 41.666667%;flex:0 0 41.666667%;max-width:41.666667%}.col-sm-6{-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.col-sm-7{-ms-flex:0 0 58.333333%;flex:0 0 58.333333%;max-width:58.333333%}.col-sm-8{-ms-flex:0 0 66.666667%;flex:0 0 66.666667%;max-width:66.666667%}.col-sm-9{-ms-flex:0 0 75%;flex:0 0 75%;max-width:75%}.col-sm-10{-ms-flex:0 0 83.333333%;flex:0 0 83.333333%;max-width:83.333333%}.col-sm-11{-ms-flex:0 0 91.666667%;flex:0 0 91.666667%;max-width:91.666667%}.col-sm-12{-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.order-sm-first{-ms-flex-order:-1;order:-1}.order-sm-last{-ms-flex-order:13;order:13}.order-sm-0{-ms-flex-order:0;order:0}.order-sm-1{-ms-flex-order:1;order:1}.order-sm-2{-ms-flex-order:2;order:2}.order-sm-3{-ms-flex-order:3;order:3}.order-sm-4{-ms-flex-order:4;order:4}.order-sm-5{-ms-flex-order:5;order:5}.order-sm-6{-ms-flex-order:6;order:6}.order-sm-7{-ms-flex-order:7;order:7}.order-sm-8{-ms-flex-order:8;order:8}.order-sm-9{-ms-flex-order:9;order:9}.order-sm-10{-ms-flex-order:10;order:10}.order-sm-11{-ms-flex-order:11;order:11}.order-sm-12{-ms-flex-order:12;order:12}.offset-sm-0{margin-left:0}.offset-sm-1{margin-left:8.333333%}.offset-sm-2{margin-left:16.666667%}.offset-sm-3{margin-left:25%}.offset-sm-4{margin-left:33.333333%}.offset-sm-5{margin-left:41.666667%}.offset-sm-6{margin-left:50%}.offset-sm-7{margin-left:58.333333%}.offset-sm-8{margin-left:66.666667%}.offset-sm-9{margin-left:75%}.offset-sm-10{margin-left:83.333333%}.offset-sm-11{margin-left:91.666667%}}@media (min-width:768px){.col-md{-ms-flex-preferred-size:0;flex-basis:0;-ms-flex-positive:1;flex-grow:1;max-width:100%}.col-md-auto{-ms-flex:0 0 auto;flex:0 0 auto;width:auto;max-width:none}.col-md-1{-ms-flex:0 0 8.333333%;flex:0 0 8.333333%;max-width:8.333333%}.col-md-2{-ms-flex:0 0 16.666667%;flex:0 0 16.666667%;max-width:16.666667%}.col-md-3{-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.col-md-4{-ms-flex:0 0 33.333333%;flex:0 0 33.333333%;max-width:33.333333%}.col-md-5{-ms-flex:0 0 41.666667%;flex:0 0 41.666667%;max-width:41.666667%}.col-md-6{-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.col-md-7{-ms-flex:0 0 58.333333%;flex:0 0 58.333333%;max-width:58.333333%}.col-md-8{-ms-flex:0 0 66.666667%;flex:0 0 66.666667%;max-width:66.666667%}.col-md-9{-ms-flex:0 0 75%;flex:0 0 75%;max-width:75%}.col-md-10{-ms-flex:0 0 83.333333%;flex:0 0 83.333333%;max-width:83.333333%}.col-md-11{-ms-flex:0 0 91.666667%;flex:0 0 91.666667%;max-width:91.666667%}.col-md-12{-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.order-md-first{-ms-flex-order:-1;order:-1}.order-md-last{-ms-flex-order:13;order:13}.order-md-0{-ms-flex-order:0;order:0}.order-md-1{-ms-flex-order:1;order:1}.order-md-2{-ms-flex-order:2;order:2}.order-md-3{-ms-flex-order:3;order:3}.order-md-4{-ms-flex-order:4;order:4}.order-md-5{-ms-flex-order:5;order:5}.order-md-6{-ms-flex-order:6;order:6}.order-md-7{-ms-flex-order:7;order:7}.order-md-8{-ms-flex-order:8;order:8}.order-md-9{-ms-flex-order:9;order:9}.order-md-10{-ms-flex-order:10;order:10}.order-md-11{-ms-flex-order:11;order:11}.order-md-12{-ms-flex-order:12;order:12}.offset-md-0{margin-left:0}.offset-md-1{margin-left:8.333333%}.offset-md-2{margin-left:16.666667%}.offset-md-3{margin-left:25%}.offset-md-4{margin-left:33.333333%}.offset-md-5{margin-left:41.666667%}.offset-md-6{margin-left:50%}.offset-md-7{margin-left:58.333333%}.offset-md-8{margin-left:66.666667%}.offset-md-9{margin-left:75%}.offset-md-10{margin-left:83.333333%}.offset-md-11{margin-left:91.666667%}}@media (min-width:992px){.col-lg{-ms-flex-preferred-size:0;flex-basis:0;-ms-flex-positive:1;flex-grow:1;max-width:100%}.col-lg-auto{-ms-flex:0 0 auto;flex:0 0 auto;width:auto;max-width:none}.col-lg-1{-ms-flex:0 0 8.333333%;flex:0 0 8.333333%;max-width:8.333333%}.col-lg-2{-ms-flex:0 0 16.666667%;flex:0 0 16.666667%;max-width:16.666667%}.col-lg-3{-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.col-lg-4{-ms-flex:0 0 33.333333%;flex:0 0 33.333333%;max-width:33.333333%}.col-lg-5{-ms-flex:0 0 41.666667%;flex:0 0 41.666667%;max-width:41.666667%}.col-lg-6{-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.col-lg-7{-ms-flex:0 0 58.333333%;flex:0 0 58.333333%;max-width:58.333333%}.col-lg-8{-ms-flex:0 0 66.666667%;flex:0 0 66.666667%;max-width:66.666667%}.col-lg-9{-ms-flex:0 0 75%;flex:0 0 75%;max-width:75%}.col-lg-10{-ms-flex:0 0 83.333333%;flex:0 0 83.333333%;max-width:83.333333%}.col-lg-11{-ms-flex:0 0 91.666667%;flex:0 0 91.666667%;max-width:91.666667%}.col-lg-12{-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.order-lg-first{-ms-flex-order:-1;order:-1}.order-lg-last{-ms-flex-order:13;order:13}.order-lg-0{-ms-flex-order:0;order:0}.order-lg-1{-ms-flex-order:1;order:1}.order-lg-2{-ms-flex-order:2;order:2}.order-lg-3{-ms-flex-order:3;order:3}.order-lg-4{-ms-flex-order:4;order:4}.order-lg-5{-ms-flex-order:5;order:5}.order-lg-6{-ms-flex-order:6;order:6}.order-lg-7{-ms-flex-order:7;order:7}.order-lg-8{-ms-flex-order:8;order:8}.order-lg-9{-ms-flex-order:9;order:9}.order-lg-10{-ms-flex-order:10;order:10}.order-lg-11{-ms-flex-order:11;order:11}.order-lg-12{-ms-flex-order:12;order:12}.offset-lg-0{margin-left:0}.offset-lg-1{margin-left:8.333333%}.offset-lg-2{margin-left:16.666667%}.offset-lg-3{margin-left:25%}.offset-lg-4{margin-left:33.333333%}.offset-lg-5{margin-left:41.666667%}.offset-lg-6{margin-left:50%}.offset-lg-7{margin-left:58.333333%}.offset-lg-8{margin-left:66.666667%}.offset-lg-9{margin-left:75%}.offset-lg-10{margin-left:83.333333%}.offset-lg-11{margin-left:91.666667%}}@media (min-width:1200px){.col-xl{-ms-flex-preferred-size:0;flex-basis:0;-ms-flex-positive:1;flex-grow:1;max-width:100%}.col-xl-auto{-ms-flex:0 0 auto;flex:0 0 auto;width:auto;max-width:none}.col-xl-1{-ms-flex:0 0 8.333333%;flex:0 0 8.333333%;max-width:8.333333%}.col-xl-2{-ms-flex:0 0 16.666667%;flex:0 0 16.666667%;max-width:16.666667%}.col-xl-3{-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.col-xl-4{-ms-flex:0 0 33.333333%;flex:0 0 33.333333%;max-width:33.333333%}.col-xl-5{-ms-flex:0 0 41.666667%;flex:0 0 41.666667%;max-width:41.666667%}.col-xl-6{-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.col-xl-7{-ms-flex:0 0 58.333333%;flex:0 0 58.333333%;max-width:58.333333%}.col-xl-8{-ms-flex:0 0 66.666667%;flex:0 0 66.666667%;max-width:66.666667%}.col-xl-9{-ms-flex:0 0 75%;flex:0 0 75%;max-width:75%}.col-xl-10{-ms-flex:0 0 83.333333%;flex:0 0 83.333333%;max-width:83.333333%}.col-xl-11{-ms-flex:0 0 91.666667%;flex:0 0 91.666667%;max-width:91.666667%}.col-xl-12{-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.order-xl-first{-ms-flex-order:-1;order:-1}.order-xl-last{-ms-flex-order:13;order:13}.order-xl-0{-ms-flex-order:0;order:0}.order-xl-1{-ms-flex-order:1;order:1}.order-xl-2{-ms-flex-order:2;order:2}.order-xl-3{-ms-flex-order:3;order:3}.order-xl-4{-ms-flex-order:4;order:4}.order-xl-5{-ms-flex-order:5;order:5}.order-xl-6{-ms-flex-order:6;order:6}.order-xl-7{-ms-flex-order:7;order:7}.order-xl-8{-ms-flex-order:8;order:8}.order-xl-9{-ms-flex-order:9;order:9}.order-xl-10{-ms-flex-order:10;order:10}.order-xl-11{-ms-flex-order:11;order:11}.order-xl-12{-ms-flex-order:12;order:12}.offset-xl-0{margin-left:0}.offset-xl-1{margin-left:8.333333%}.offset-xl-2{margin-left:16.666667%}.offset-xl-3{margin-left:25%}.offset-xl-4{margin-left:33.333333%}.offset-xl-5{margin-left:41.666667%}.offset-xl-6{margin-left:50%}.offset-xl-7{margin-left:58.333333%}.offset-xl-8{margin-left:66.666667%}.offset-xl-9{margin-left:75%}.offset-xl-10{margin-left:83.333333%}.offset-xl-11{margin-left:91.666667%}}.table{width:100%;margin-bottom:1rem;background-color:transparent}.table td,.table th{padding:.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 td,.table-sm th{padding:.3rem}.table-bordered{border:1px solid #dee2e6}.table-bordered td,.table-bordered th{border:1px solid #dee2e6}.table-bordered thead td,.table-bordered thead th{border-bottom-width:2px}.table-borderless tbody+tbody,.table-borderless td,.table-borderless th,.table-borderless thead th{border:0}.table-striped tbody tr:nth-of-type(odd){background-color:rgba(0,0,0,.05)}.table-hover tbody tr:hover{background-color:rgba(0,0,0,.075)}.table-primary,.table-primary>td,.table-primary>th{background-color:#b8daff}.table-hover .table-primary:hover{background-color:#9fcdff}.table-hover .table-primary:hover>td,.table-hover .table-primary:hover>th{background-color:#9fcdff}.table-secondary,.table-secondary>td,.table-secondary>th{background-color:#d6d8db}.table-hover .table-secondary:hover{background-color:#c8cbcf}.table-hover .table-secondary:hover>td,.table-hover .table-secondary:hover>th{background-color:#c8cbcf}.table-success,.table-success>td,.table-success>th{background-color:#c3e6cb}.table-hover .table-success:hover{background-color:#b1dfbb}.table-hover .table-success:hover>td,.table-hover .table-success:hover>th{background-color:#b1dfbb}.table-info,.table-info>td,.table-info>th{background-color:#bee5eb}.table-hover .table-info:hover{background-color:#abdde5}.table-hover .table-info:hover>td,.table-hover .table-info:hover>th{background-color:#abdde5}.table-warning,.table-warning>td,.table-warning>th{background-color:#ffeeba}.table-hover .table-warning:hover{background-color:#ffe8a1}.table-hover .table-warning:hover>td,.table-hover .table-warning:hover>th{background-color:#ffe8a1}.table-danger,.table-danger>td,.table-danger>th{background-color:#f5c6cb}.table-hover .table-danger:hover{background-color:#f1b0b7}.table-hover .table-danger:hover>td,.table-hover .table-danger:hover>th{background-color:#f1b0b7}.table-light,.table-light>td,.table-light>th{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>td,.table-dark>th{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>td,.table-active>th{background-color:rgba(0,0,0,.075)}.table-hover .table-active:hover{background-color:rgba(0,0,0,.075)}.table-hover .table-active:hover>td,.table-hover .table-active:hover>th{background-color:rgba(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 td,.table-dark th,.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,.05)}.table-dark.table-hover tbody tr:hover{background-color:rgba(255,255,255,.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:.375rem .75rem;font-size:1rem;line-height:1.5;color:#495057;background-color:#fff;background-clip:padding-box;border:1px solid #ced4da;border-radius:.25rem;transition:border-color .15s ease-in-out,box-shadow .15s ease-in-out}@media screen and (prefers-reduced-motion:reduce){.form-control{transition:none}}.form-control::-ms-expand{background-color:transparent;border:0}.form-control:focus{color:#495057;background-color:#fff;border-color:#80bdff;outline:0;box-shadow:0 0 0 .2rem rgba(0,123,255,.25)}.form-control::-webkit-input-placeholder{color:#6c757d;opacity:1}.form-control::-moz-placeholder{color:#6c757d;opacity:1}.form-control:-ms-input-placeholder{color:#6c757d;opacity:1}.form-control::-ms-input-placeholder{color:#6c757d;opacity:1}.form-control::placeholder{color:#6c757d;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(.375rem + 1px);padding-bottom:calc(.375rem + 1px);margin-bottom:0;font-size:inherit;line-height:1.5}.col-form-label-lg{padding-top:calc(.5rem + 1px);padding-bottom:calc(.5rem + 1px);font-size:1.25rem;line-height:1.5}.col-form-label-sm{padding-top:calc(.25rem + 1px);padding-bottom:calc(.25rem + 1px);font-size:.875rem;line-height:1.5}.form-control-plaintext{display:block;width:100%;padding-top:.375rem;padding-bottom:.375rem;margin-bottom:0;line-height:1.5;color:#212529;background-color:transparent;border:solid transparent;border-width:1px 0}.form-control-plaintext.form-control-lg,.form-control-plaintext.form-control-sm{padding-right:0;padding-left:0}.form-control-sm{height:calc(1.8125rem + 2px);padding:.25rem .5rem;font-size:.875rem;line-height:1.5;border-radius:.2rem}.form-control-lg{height:calc(2.875rem + 2px);padding:.5rem 1rem;font-size:1.25rem;line-height:1.5;border-radius:.3rem}select.form-control[multiple],select.form-control[size]{height:auto}textarea.form-control{height:auto}.form-group{margin-bottom:1rem}.form-text{display:block;margin-top:.25rem}.form-row{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:.3rem;margin-left:-1.25rem}.form-check-input:disabled~.form-check-label{color:#6c757d}.form-check-label{margin-bottom:0}.form-check-inline{display:-ms-inline-flexbox;display:inline-flex;-ms-flex-align:center;align-items:center;padding-left:0;margin-right:.75rem}.form-check-inline .form-check-input{position:static;margin-top:0;margin-right:.3125rem;margin-left:0}.valid-feedback{display:none;width:100%;margin-top:.25rem;font-size:80%;color:#28a745}.valid-tooltip{position:absolute;top:100%;z-index:5;display:none;max-width:100%;padding:.25rem .5rem;margin-top:.1rem;font-size:.875rem;line-height:1.5;color:#fff;background-color:rgba(40,167,69,.9);border-radius:.25rem}.custom-select.is-valid,.form-control.is-valid,.was-validated .custom-select:valid,.was-validated .form-control:valid{border-color:#28a745}.custom-select.is-valid:focus,.form-control.is-valid:focus,.was-validated .custom-select:valid:focus,.was-validated .form-control:valid:focus{border-color:#28a745;box-shadow:0 0 0 .2rem rgba(40,167,69,.25)}.custom-select.is-valid~.valid-feedback,.custom-select.is-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,.was-validated .form-control:valid~.valid-feedback,.was-validated .form-control:valid~.valid-tooltip{display:block}.form-control-file.is-valid~.valid-feedback,.form-control-file.is-valid~.valid-tooltip,.was-validated .form-control-file:valid~.valid-feedback,.was-validated .form-control-file:valid~.valid-tooltip{display:block}.form-check-input.is-valid~.form-check-label,.was-validated .form-check-input:valid~.form-check-label{color:#28a745}.form-check-input.is-valid~.valid-feedback,.form-check-input.is-valid~.valid-tooltip,.was-validated .form-check-input:valid~.valid-feedback,.was-validated .form-check-input:valid~.valid-tooltip{display:block}.custom-control-input.is-valid~.custom-control-label,.was-validated .custom-control-input:valid~.custom-control-label{color:#28a745}.custom-control-input.is-valid~.custom-control-label::before,.was-validated .custom-control-input:valid~.custom-control-label::before{background-color:#71dd8a}.custom-control-input.is-valid~.valid-feedback,.custom-control-input.is-valid~.valid-tooltip,.was-validated .custom-control-input:valid~.valid-feedback,.was-validated .custom-control-input:valid~.valid-tooltip{display:block}.custom-control-input.is-valid:checked~.custom-control-label::before,.was-validated .custom-control-input:valid:checked~.custom-control-label::before{background-color:#34ce57}.custom-control-input.is-valid:focus~.custom-control-label::before,.was-validated .custom-control-input:valid:focus~.custom-control-label::before{box-shadow:0 0 0 1px #fff,0 0 0 .2rem rgba(40,167,69,.25)}.custom-file-input.is-valid~.custom-file-label,.was-validated .custom-file-input:valid~.custom-file-label{border-color:#28a745}.custom-file-input.is-valid~.custom-file-label::after,.was-validated .custom-file-input:valid~.custom-file-label::after{border-color:inherit}.custom-file-input.is-valid~.valid-feedback,.custom-file-input.is-valid~.valid-tooltip,.was-validated .custom-file-input:valid~.valid-feedback,.was-validated .custom-file-input:valid~.valid-tooltip{display:block}.custom-file-input.is-valid:focus~.custom-file-label,.was-validated .custom-file-input:valid:focus~.custom-file-label{box-shadow:0 0 0 .2rem rgba(40,167,69,.25)}.invalid-feedback{display:none;width:100%;margin-top:.25rem;font-size:80%;color:#dc3545}.invalid-tooltip{position:absolute;top:100%;z-index:5;display:none;max-width:100%;padding:.25rem .5rem;margin-top:.1rem;font-size:.875rem;line-height:1.5;color:#fff;background-color:rgba(220,53,69,.9);border-radius:.25rem}.custom-select.is-invalid,.form-control.is-invalid,.was-validated .custom-select:invalid,.was-validated .form-control:invalid{border-color:#dc3545}.custom-select.is-invalid:focus,.form-control.is-invalid:focus,.was-validated .custom-select:invalid:focus,.was-validated .form-control:invalid:focus{border-color:#dc3545;box-shadow:0 0 0 .2rem rgba(220,53,69,.25)}.custom-select.is-invalid~.invalid-feedback,.custom-select.is-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,.was-validated .form-control:invalid~.invalid-feedback,.was-validated .form-control:invalid~.invalid-tooltip{display:block}.form-control-file.is-invalid~.invalid-feedback,.form-control-file.is-invalid~.invalid-tooltip,.was-validated .form-control-file:invalid~.invalid-feedback,.was-validated .form-control-file:invalid~.invalid-tooltip{display:block}.form-check-input.is-invalid~.form-check-label,.was-validated .form-check-input:invalid~.form-check-label{color:#dc3545}.form-check-input.is-invalid~.invalid-feedback,.form-check-input.is-invalid~.invalid-tooltip,.was-validated .form-check-input:invalid~.invalid-feedback,.was-validated .form-check-input:invalid~.invalid-tooltip{display:block}.custom-control-input.is-invalid~.custom-control-label,.was-validated .custom-control-input:invalid~.custom-control-label{color:#dc3545}.custom-control-input.is-invalid~.custom-control-label::before,.was-validated .custom-control-input:invalid~.custom-control-label::before{background-color:#efa2a9}.custom-control-input.is-invalid~.invalid-feedback,.custom-control-input.is-invalid~.invalid-tooltip,.was-validated .custom-control-input:invalid~.invalid-feedback,.was-validated .custom-control-input:invalid~.invalid-tooltip{display:block}.custom-control-input.is-invalid:checked~.custom-control-label::before,.was-validated .custom-control-input:invalid:checked~.custom-control-label::before{background-color:#e4606d}.custom-control-input.is-invalid:focus~.custom-control-label::before,.was-validated .custom-control-input:invalid:focus~.custom-control-label::before{box-shadow:0 0 0 1px #fff,0 0 0 .2rem rgba(220,53,69,.25)}.custom-file-input.is-invalid~.custom-file-label,.was-validated .custom-file-input:invalid~.custom-file-label{border-color:#dc3545}.custom-file-input.is-invalid~.custom-file-label::after,.was-validated .custom-file-input:invalid~.custom-file-label::after{border-color:inherit}.custom-file-input.is-invalid~.invalid-feedback,.custom-file-input.is-invalid~.invalid-tooltip,.was-validated .custom-file-input:invalid~.invalid-feedback,.was-validated .custom-file-input:invalid~.invalid-tooltip{display:block}.custom-file-input.is-invalid:focus~.custom-file-label,.was-validated .custom-file-input:invalid:focus~.custom-file-label{box-shadow:0 0 0 .2rem rgba(220,53,69,.25)}.form-inline{display:-ms-flexbox;display:flex;-ms-flex-flow:row wrap;flex-flow:row wrap;-ms-flex-align:center;align-items:center}.form-inline .form-check{width:100%}@media (min-width:576px){.form-inline label{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center;margin-bottom:0}.form-inline .form-group{display:-ms-flexbox;display:flex;-ms-flex:0 0 auto;flex:0 0 auto;-ms-flex-flow:row wrap;flex-flow:row wrap;-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 .custom-select,.form-inline .input-group{width:auto}.form-inline .form-check{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items: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:.25rem;margin-left:0}.form-inline .custom-control{-ms-flex-align:center;align-items: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:.375rem .75rem;font-size:1rem;line-height:1.5;border-radius:.25rem;transition:color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out}@media screen and (prefers-reduced-motion:reduce){.btn{transition:none}}.btn:focus,.btn:hover{text-decoration:none}.btn.focus,.btn:focus{outline:0;box-shadow:0 0 0 .2rem rgba(0,123,255,.25)}.btn.disabled,.btn:disabled{opacity:.65}.btn:not(:disabled):not(.disabled){cursor:pointer}a.btn.disabled,fieldset:disabled a.btn{pointer-events:none}.btn-primary{color:#fff;background-color:#007bff;border-color:#007bff}.btn-primary:hover{color:#fff;background-color:#0069d9;border-color:#0062cc}.btn-primary.focus,.btn-primary:focus{box-shadow:0 0 0 .2rem rgba(0,123,255,.5)}.btn-primary.disabled,.btn-primary:disabled{color:#fff;background-color:#007bff;border-color:#007bff}.btn-primary:not(:disabled):not(.disabled).active,.btn-primary:not(:disabled):not(.disabled):active,.show>.btn-primary.dropdown-toggle{color:#fff;background-color:#0062cc;border-color:#005cbf}.btn-primary:not(:disabled):not(.disabled).active:focus,.btn-primary:not(:disabled):not(.disabled):active:focus,.show>.btn-primary.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(0,123,255,.5)}.btn-secondary{color:#fff;background-color:#6c757d;border-color:#6c757d}.btn-secondary:hover{color:#fff;background-color:#5a6268;border-color:#545b62}.btn-secondary.focus,.btn-secondary:focus{box-shadow:0 0 0 .2rem rgba(108,117,125,.5)}.btn-secondary.disabled,.btn-secondary:disabled{color:#fff;background-color:#6c757d;border-color:#6c757d}.btn-secondary:not(:disabled):not(.disabled).active,.btn-secondary:not(:disabled):not(.disabled):active,.show>.btn-secondary.dropdown-toggle{color:#fff;background-color:#545b62;border-color:#4e555b}.btn-secondary:not(:disabled):not(.disabled).active:focus,.btn-secondary:not(:disabled):not(.disabled):active:focus,.show>.btn-secondary.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(108,117,125,.5)}.btn-success{color:#fff;background-color:#28a745;border-color:#28a745}.btn-success:hover{color:#fff;background-color:#218838;border-color:#1e7e34}.btn-success.focus,.btn-success:focus{box-shadow:0 0 0 .2rem rgba(40,167,69,.5)}.btn-success.disabled,.btn-success:disabled{color:#fff;background-color:#28a745;border-color:#28a745}.btn-success:not(:disabled):not(.disabled).active,.btn-success:not(:disabled):not(.disabled):active,.show>.btn-success.dropdown-toggle{color:#fff;background-color:#1e7e34;border-color:#1c7430}.btn-success:not(:disabled):not(.disabled).active:focus,.btn-success:not(:disabled):not(.disabled):active:focus,.show>.btn-success.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(40,167,69,.5)}.btn-info{color:#fff;background-color:#17a2b8;border-color:#17a2b8}.btn-info:hover{color:#fff;background-color:#138496;border-color:#117a8b}.btn-info.focus,.btn-info:focus{box-shadow:0 0 0 .2rem rgba(23,162,184,.5)}.btn-info.disabled,.btn-info:disabled{color:#fff;background-color:#17a2b8;border-color:#17a2b8}.btn-info:not(:disabled):not(.disabled).active,.btn-info:not(:disabled):not(.disabled):active,.show>.btn-info.dropdown-toggle{color:#fff;background-color:#117a8b;border-color:#10707f}.btn-info:not(:disabled):not(.disabled).active:focus,.btn-info:not(:disabled):not(.disabled):active:focus,.show>.btn-info.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(23,162,184,.5)}.btn-warning{color:#212529;background-color:#ffc107;border-color:#ffc107}.btn-warning:hover{color:#212529;background-color:#e0a800;border-color:#d39e00}.btn-warning.focus,.btn-warning:focus{box-shadow:0 0 0 .2rem rgba(255,193,7,.5)}.btn-warning.disabled,.btn-warning:disabled{color:#212529;background-color:#ffc107;border-color:#ffc107}.btn-warning:not(:disabled):not(.disabled).active,.btn-warning:not(:disabled):not(.disabled):active,.show>.btn-warning.dropdown-toggle{color:#212529;background-color:#d39e00;border-color:#c69500}.btn-warning:not(:disabled):not(.disabled).active:focus,.btn-warning:not(:disabled):not(.disabled):active:focus,.show>.btn-warning.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(255,193,7,.5)}.btn-danger{color:#fff;background-color:#dc3545;border-color:#dc3545}.btn-danger:hover{color:#fff;background-color:#c82333;border-color:#bd2130}.btn-danger.focus,.btn-danger:focus{box-shadow:0 0 0 .2rem rgba(220,53,69,.5)}.btn-danger.disabled,.btn-danger:disabled{color:#fff;background-color:#dc3545;border-color:#dc3545}.btn-danger:not(:disabled):not(.disabled).active,.btn-danger:not(:disabled):not(.disabled):active,.show>.btn-danger.dropdown-toggle{color:#fff;background-color:#bd2130;border-color:#b21f2d}.btn-danger:not(:disabled):not(.disabled).active:focus,.btn-danger:not(:disabled):not(.disabled):active:focus,.show>.btn-danger.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(220,53,69,.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{box-shadow:0 0 0 .2rem rgba(248,249,250,.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{box-shadow:0 0 0 .2rem rgba(248,249,250,.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{box-shadow:0 0 0 .2rem rgba(52,58,64,.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{box-shadow:0 0 0 .2rem rgba(52,58,64,.5)}.btn-outline-primary{color:#007bff;background-color:transparent;background-image:none;border-color:#007bff}.btn-outline-primary:hover{color:#fff;background-color:#007bff;border-color:#007bff}.btn-outline-primary.focus,.btn-outline-primary:focus{box-shadow:0 0 0 .2rem rgba(0,123,255,.5)}.btn-outline-primary.disabled,.btn-outline-primary:disabled{color:#007bff;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:#007bff;border-color:#007bff}.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{box-shadow:0 0 0 .2rem rgba(0,123,255,.5)}.btn-outline-secondary{color:#6c757d;background-color:transparent;background-image:none;border-color:#6c757d}.btn-outline-secondary:hover{color:#fff;background-color:#6c757d;border-color:#6c757d}.btn-outline-secondary.focus,.btn-outline-secondary:focus{box-shadow:0 0 0 .2rem rgba(108,117,125,.5)}.btn-outline-secondary.disabled,.btn-outline-secondary:disabled{color:#6c757d;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:#fff;background-color:#6c757d;border-color:#6c757d}.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{box-shadow:0 0 0 .2rem rgba(108,117,125,.5)}.btn-outline-success{color:#28a745;background-color:transparent;background-image:none;border-color:#28a745}.btn-outline-success:hover{color:#fff;background-color:#28a745;border-color:#28a745}.btn-outline-success.focus,.btn-outline-success:focus{box-shadow:0 0 0 .2rem rgba(40,167,69,.5)}.btn-outline-success.disabled,.btn-outline-success:disabled{color:#28a745;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:#28a745;border-color:#28a745}.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{box-shadow:0 0 0 .2rem rgba(40,167,69,.5)}.btn-outline-info{color:#17a2b8;background-color:transparent;background-image:none;border-color:#17a2b8}.btn-outline-info:hover{color:#fff;background-color:#17a2b8;border-color:#17a2b8}.btn-outline-info.focus,.btn-outline-info:focus{box-shadow:0 0 0 .2rem rgba(23,162,184,.5)}.btn-outline-info.disabled,.btn-outline-info:disabled{color:#17a2b8;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:#17a2b8;border-color:#17a2b8}.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{box-shadow:0 0 0 .2rem rgba(23,162,184,.5)}.btn-outline-warning{color:#ffc107;background-color:transparent;background-image:none;border-color:#ffc107}.btn-outline-warning:hover{color:#212529;background-color:#ffc107;border-color:#ffc107}.btn-outline-warning.focus,.btn-outline-warning:focus{box-shadow:0 0 0 .2rem rgba(255,193,7,.5)}.btn-outline-warning.disabled,.btn-outline-warning:disabled{color:#ffc107;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:#212529;background-color:#ffc107;border-color:#ffc107}.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{box-shadow:0 0 0 .2rem rgba(255,193,7,.5)}.btn-outline-danger{color:#dc3545;background-color:transparent;background-image:none;border-color:#dc3545}.btn-outline-danger:hover{color:#fff;background-color:#dc3545;border-color:#dc3545}.btn-outline-danger.focus,.btn-outline-danger:focus{box-shadow:0 0 0 .2rem rgba(220,53,69,.5)}.btn-outline-danger.disabled,.btn-outline-danger:disabled{color:#dc3545;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:#dc3545;border-color:#dc3545}.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{box-shadow:0 0 0 .2rem rgba(220,53,69,.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{box-shadow:0 0 0 .2rem rgba(248,249,250,.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{box-shadow:0 0 0 .2rem rgba(248,249,250,.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{box-shadow:0 0 0 .2rem rgba(52,58,64,.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{box-shadow:0 0 0 .2rem rgba(52,58,64,.5)}.btn-link{font-weight:400;color:#007bff;background-color:transparent}.btn-link:hover{color:#0056b3;text-decoration:underline;background-color:transparent;border-color:transparent}.btn-link.focus,.btn-link:focus{text-decoration:underline;border-color:transparent;box-shadow:none}.btn-link.disabled,.btn-link:disabled{color:#6c757d;pointer-events:none}.btn-group-lg>.btn,.btn-lg{padding:.5rem 1rem;font-size:1.25rem;line-height:1.5;border-radius:.3rem}.btn-group-sm>.btn,.btn-sm{padding:.25rem .5rem;font-size:.875rem;line-height:1.5;border-radius:.2rem}.btn-block{display:block;width:100%}.btn-block+.btn-block{margin-top:.5rem}input[type=button].btn-block,input[type=reset].btn-block,input[type=submit].btn-block{width:100%}.fade{transition:opacity .15s linear}@media screen and (prefers-reduced-motion:reduce){.fade{transition:none}}.fade:not(.show){opacity:0}.collapse:not(.show){display:none}.collapsing{position:relative;height:0;overflow:hidden;transition:height .35s ease}@media screen and (prefers-reduced-motion:reduce){.collapsing{transition:none}}.dropdown,.dropleft,.dropright,.dropup{position:relative}.dropdown-toggle::after{display:inline-block;width:0;height:0;margin-left:.255em;vertical-align:.255em;content:"";border-top:.3em solid;border-right:.3em solid transparent;border-bottom:0;border-left:.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:.5rem 0;margin:.125rem 0 0;font-size:1rem;color:#212529;text-align:left;list-style:none;background-color:#fff;background-clip:padding-box;border:1px solid rgba(0,0,0,.15);border-radius:.25rem}.dropdown-menu-right{right:0;left:auto}.dropup .dropdown-menu{top:auto;bottom:100%;margin-top:0;margin-bottom:.125rem}.dropup .dropdown-toggle::after{display:inline-block;width:0;height:0;margin-left:.255em;vertical-align:.255em;content:"";border-top:0;border-right:.3em solid transparent;border-bottom:.3em solid;border-left:.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:.125rem}.dropright .dropdown-toggle::after{display:inline-block;width:0;height:0;margin-left:.255em;vertical-align:.255em;content:"";border-top:.3em solid transparent;border-right:0;border-bottom:.3em solid transparent;border-left:.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:.125rem}.dropleft .dropdown-toggle::after{display:inline-block;width:0;height:0;margin-left:.255em;vertical-align:.255em;content:""}.dropleft .dropdown-toggle::after{display:none}.dropleft .dropdown-toggle::before{display:inline-block;width:0;height:0;margin-right:.255em;vertical-align:.255em;content:"";border-top:.3em solid transparent;border-right:.3em solid;border-bottom:.3em solid transparent}.dropleft .dropdown-toggle:empty::after{margin-left:0}.dropleft .dropdown-toggle::before{vertical-align:0}.dropdown-menu[x-placement^=bottom],.dropdown-menu[x-placement^=left],.dropdown-menu[x-placement^=right],.dropdown-menu[x-placement^=top]{right:auto;bottom:auto}.dropdown-divider{height:0;margin:.5rem 0;overflow:hidden;border-top:1px solid #e9ecef}.dropdown-item{display:block;width:100%;padding:.25rem 1.5rem;clear:both;font-weight:400;color:#212529;text-align:inherit;white-space:nowrap;background-color:transparent;border:0}.dropdown-item:focus,.dropdown-item:hover{color:#16181b;text-decoration:none;background-color:#f8f9fa}.dropdown-item.active,.dropdown-item:active{color:#fff;text-decoration:none;background-color:#007bff}.dropdown-item.disabled,.dropdown-item:disabled{color:#6c757d;background-color:transparent}.dropdown-menu.show{display:block}.dropdown-header{display:block;padding:.5rem 1.5rem;margin-bottom:0;font-size:.875rem;color:#6c757d;white-space:nowrap}.dropdown-item-text{display:block;padding:.25rem 1.5rem;color:#212529}.btn-group,.btn-group-vertical{position:relative;display:-ms-inline-flexbox;display:inline-flex;vertical-align:middle}.btn-group-vertical>.btn,.btn-group>.btn{position:relative;-ms-flex:0 1 auto;flex:0 1 auto}.btn-group-vertical>.btn:hover,.btn-group>.btn:hover{z-index:1}.btn-group-vertical>.btn.active,.btn-group-vertical>.btn:active,.btn-group-vertical>.btn:focus,.btn-group>.btn.active,.btn-group>.btn:active,.btn-group>.btn:focus{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:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;-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-group:not(:last-child)>.btn,.btn-group>.btn:not(:last-child):not(.dropdown-toggle){border-top-right-radius:0;border-bottom-right-radius:0}.btn-group>.btn-group:not(:first-child)>.btn,.btn-group>.btn:not(:first-child){border-top-left-radius:0;border-bottom-left-radius:0}.dropdown-toggle-split{padding-right:.5625rem;padding-left:.5625rem}.dropdown-toggle-split::after,.dropright .dropdown-toggle-split::after,.dropup .dropdown-toggle-split::after{margin-left:0}.dropleft .dropdown-toggle-split::before{margin-right:0}.btn-group-sm>.btn+.dropdown-toggle-split,.btn-sm+.dropdown-toggle-split{padding-right:.375rem;padding-left:.375rem}.btn-group-lg>.btn+.dropdown-toggle-split,.btn-lg+.dropdown-toggle-split{padding-right:.75rem;padding-left:.75rem}.btn-group-vertical{-ms-flex-direction:column;flex-direction:column;-ms-flex-align:start;align-items:flex-start;-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-group:not(:last-child)>.btn,.btn-group-vertical>.btn:not(:last-child):not(.dropdown-toggle){border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical>.btn-group:not(:first-child)>.btn,.btn-group-vertical>.btn:not(:first-child){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=checkbox],.btn-group-toggle>.btn input[type=radio],.btn-group-toggle>.btn-group>.btn input[type=checkbox],.btn-group-toggle>.btn-group>.btn input[type=radio]{position:absolute;clip:rect(0,0,0,0);pointer-events:none}.input-group{position:relative;display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;-ms-flex-align:stretch;align-items:stretch;width:100%}.input-group>.custom-file,.input-group>.custom-select,.input-group>.form-control{position:relative;-ms-flex:1 1 auto;flex:1 1 auto;width:1%;margin-bottom:0}.input-group>.custom-file+.custom-file,.input-group>.custom-file+.custom-select,.input-group>.custom-file+.form-control,.input-group>.custom-select+.custom-file,.input-group>.custom-select+.custom-select,.input-group>.custom-select+.form-control,.input-group>.form-control+.custom-file,.input-group>.form-control+.custom-select,.input-group>.form-control+.form-control{margin-left:-1px}.input-group>.custom-file .custom-file-input:focus~.custom-file-label,.input-group>.custom-select:focus,.input-group>.form-control:focus{z-index:3}.input-group>.custom-file .custom-file-input:focus{z-index:4}.input-group>.custom-select:not(:last-child),.input-group>.form-control:not(:last-child){border-top-right-radius:0;border-bottom-right-radius:0}.input-group>.custom-select:not(:first-child),.input-group>.form-control:not(:first-child){border-top-left-radius:0;border-bottom-left-radius:0}.input-group>.custom-file{display:-ms-flexbox;display:flex;-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-append,.input-group-prepend{display:-ms-flexbox;display:flex}.input-group-append .btn,.input-group-prepend .btn{position:relative;z-index:2}.input-group-append .btn+.btn,.input-group-append .btn+.input-group-text,.input-group-append .input-group-text+.btn,.input-group-append .input-group-text+.input-group-text,.input-group-prepend .btn+.btn,.input-group-prepend .btn+.input-group-text,.input-group-prepend .input-group-text+.btn,.input-group-prepend .input-group-text+.input-group-text{margin-left:-1px}.input-group-prepend{margin-right:-1px}.input-group-append{margin-left:-1px}.input-group-text{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;padding:.375rem .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:.25rem}.input-group-text input[type=checkbox],.input-group-text input[type=radio]{margin-top:0}.input-group-lg>.form-control,.input-group-lg>.input-group-append>.btn,.input-group-lg>.input-group-append>.input-group-text,.input-group-lg>.input-group-prepend>.btn,.input-group-lg>.input-group-prepend>.input-group-text{height:calc(2.875rem + 2px);padding:.5rem 1rem;font-size:1.25rem;line-height:1.5;border-radius:.3rem}.input-group-sm>.form-control,.input-group-sm>.input-group-append>.btn,.input-group-sm>.input-group-append>.input-group-text,.input-group-sm>.input-group-prepend>.btn,.input-group-sm>.input-group-prepend>.input-group-text{height:calc(1.8125rem + 2px);padding:.25rem .5rem;font-size:.875rem;line-height:1.5;border-radius:.2rem}.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),.input-group>.input-group-append:not(:last-child)>.btn,.input-group>.input-group-append:not(:last-child)>.input-group-text,.input-group>.input-group-prepend>.btn,.input-group>.input-group-prepend>.input-group-text{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:first-child>.btn:not(:first-child),.input-group>.input-group-prepend:first-child>.input-group-text:not(:first-child),.input-group>.input-group-prepend:not(:first-child)>.btn,.input-group>.input-group-prepend:not(:first-child)>.input-group-text{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:-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:#007bff}.custom-control-input:focus~.custom-control-label::before{box-shadow:0 0 0 1px #fff,0 0 0 .2rem rgba(0,123,255,.25)}.custom-control-input:active~.custom-control-label::before{color:#fff;background-color:#b3d7ff}.custom-control-input:disabled~.custom-control-label{color:#6c757d}.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:.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:.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:.25rem}.custom-checkbox .custom-control-input:checked~.custom-control-label::before{background-color:#007bff}.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:#007bff}.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(0,123,255,.5)}.custom-checkbox .custom-control-input:disabled:indeterminate~.custom-control-label::before{background-color:rgba(0,123,255,.5)}.custom-radio .custom-control-label::before{border-radius:50%}.custom-radio .custom-control-input:checked~.custom-control-label::before{background-color:#007bff}.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(0,123,255,.5)}.custom-select{display:inline-block;width:100%;height:calc(2.25rem + 2px);padding:.375rem 1.75rem .375rem .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 .75rem center;background-size:8px 10px;border:1px solid #ced4da;border-radius:.25rem;-webkit-appearance:none;-moz-appearance:none;appearance:none}.custom-select:focus{border-color:#80bdff;outline:0;box-shadow:0 0 0 .2rem rgba(128,189,255,.5)}.custom-select:focus::-ms-value{color:#495057;background-color:#fff}.custom-select[multiple],.custom-select[size]:not([size="1"]){height:auto;padding-right:.75rem;background-image:none}.custom-select:disabled{color:#6c757d;background-color:#e9ecef}.custom-select::-ms-expand{opacity:0}.custom-select-sm{height:calc(1.8125rem + 2px);padding-top:.375rem;padding-bottom:.375rem;font-size:75%}.custom-select-lg{height:calc(2.875rem + 2px);padding-top:.375rem;padding-bottom:.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:#80bdff;box-shadow:0 0 0 .2rem rgba(0,123,255,.25)}.custom-file-input:focus~.custom-file-label::after{border-color:#80bdff}.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:.375rem .75rem;line-height:1.5;color:#495057;background-color:#fff;border:1px solid #ced4da;border-radius:.25rem}.custom-file-label::after{position:absolute;top:0;right:0;bottom:0;z-index:3;display:block;height:2.25rem;padding:.375rem .75rem;line-height:1.5;color:#495057;content:"Browse";background-color:#e9ecef;border-left:1px solid #ced4da;border-radius:0 .25rem .25rem 0}.custom-range{width:100%;padding-left:0;background-color:transparent;-webkit-appearance:none;-moz-appearance:none;appearance:none}.custom-range:focus{outline:0}.custom-range:focus::-webkit-slider-thumb{box-shadow:0 0 0 1px #fff,0 0 0 .2rem rgba(0,123,255,.25)}.custom-range:focus::-moz-range-thumb{box-shadow:0 0 0 1px #fff,0 0 0 .2rem rgba(0,123,255,.25)}.custom-range:focus::-ms-thumb{box-shadow:0 0 0 1px #fff,0 0 0 .2rem rgba(0,123,255,.25)}.custom-range::-moz-focus-outer{border:0}.custom-range::-webkit-slider-thumb{width:1rem;height:1rem;margin-top:-.25rem;background-color:#007bff;border:0;border-radius:1rem;transition:background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;-webkit-appearance:none;appearance:none}@media screen and (prefers-reduced-motion:reduce){.custom-range::-webkit-slider-thumb{transition:none}}.custom-range::-webkit-slider-thumb:active{background-color:#b3d7ff}.custom-range::-webkit-slider-runnable-track{width:100%;height:.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:#007bff;border:0;border-radius:1rem;transition:background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;-moz-appearance:none;appearance:none}@media screen and (prefers-reduced-motion:reduce){.custom-range::-moz-range-thumb{transition:none}}.custom-range::-moz-range-thumb:active{background-color:#b3d7ff}.custom-range::-moz-range-track{width:100%;height:.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:.2rem;margin-left:.2rem;background-color:#007bff;border:0;border-radius:1rem;transition:background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;appearance:none}@media screen and (prefers-reduced-motion:reduce){.custom-range::-ms-thumb{transition:none}}.custom-range::-ms-thumb:active{background-color:#b3d7ff}.custom-range::-ms-track{width:100%;height:.5rem;color:transparent;cursor:pointer;background-color:transparent;border-color:transparent;border-width:.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{transition:background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out}@media screen and (prefers-reduced-motion:reduce){.custom-control-label::before,.custom-file-label,.custom-select{transition:none}}.nav{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:.5rem 1rem}.nav-link:focus,.nav-link:hover{text-decoration:none}.nav-link.disabled{color:#6c757d}.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:.25rem;border-top-right-radius:.25rem}.nav-tabs .nav-link:focus,.nav-tabs .nav-link:hover{border-color:#e9ecef #e9ecef #dee2e6}.nav-tabs .nav-link.disabled{color:#6c757d;background-color:transparent;border-color:transparent}.nav-tabs .nav-item.show .nav-link,.nav-tabs .nav-link.active{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:.25rem}.nav-pills .nav-link.active,.nav-pills .show>.nav-link{color:#fff;background-color:#007bff}.nav-fill .nav-item{-ms-flex:1 1 auto;flex:1 1 auto;text-align:center}.nav-justified .nav-item{-ms-flex-preferred-size:0;flex-basis:0;-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:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;-ms-flex-align:center;align-items:center;-ms-flex-pack:justify;justify-content:space-between;padding:.5rem 1rem}.navbar>.container,.navbar>.container-fluid{display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;-ms-flex-align:center;align-items:center;-ms-flex-pack:justify;justify-content:space-between}.navbar-brand{display:inline-block;padding-top:.3125rem;padding-bottom:.3125rem;margin-right:1rem;font-size:1.25rem;line-height:inherit;white-space:nowrap}.navbar-brand:focus,.navbar-brand:hover{text-decoration:none}.navbar-nav{display:-ms-flexbox;display:flex;-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:.5rem;padding-bottom:.5rem}.navbar-collapse{-ms-flex-preferred-size:100%;flex-basis:100%;-ms-flex-positive:1;flex-grow:1;-ms-flex-align:center;align-items:center}.navbar-toggler{padding:.25rem .75rem;font-size:1.25rem;line-height:1;background-color:transparent;border:1px solid transparent;border-radius:.25rem}.navbar-toggler:focus,.navbar-toggler:hover{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{-ms-flex-flow:row nowrap;flex-flow:row nowrap;-ms-flex-pack:start;justify-content:flex-start}.navbar-expand-sm .navbar-nav{-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:.5rem;padding-left:.5rem}.navbar-expand-sm>.container,.navbar-expand-sm>.container-fluid{-ms-flex-wrap:nowrap;flex-wrap:nowrap}.navbar-expand-sm .navbar-collapse{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{-ms-flex-flow:row nowrap;flex-flow:row nowrap;-ms-flex-pack:start;justify-content:flex-start}.navbar-expand-md .navbar-nav{-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:.5rem;padding-left:.5rem}.navbar-expand-md>.container,.navbar-expand-md>.container-fluid{-ms-flex-wrap:nowrap;flex-wrap:nowrap}.navbar-expand-md .navbar-collapse{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{-ms-flex-flow:row nowrap;flex-flow:row nowrap;-ms-flex-pack:start;justify-content:flex-start}.navbar-expand-lg .navbar-nav{-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:.5rem;padding-left:.5rem}.navbar-expand-lg>.container,.navbar-expand-lg>.container-fluid{-ms-flex-wrap:nowrap;flex-wrap:nowrap}.navbar-expand-lg .navbar-collapse{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{-ms-flex-flow:row nowrap;flex-flow:row nowrap;-ms-flex-pack:start;justify-content:flex-start}.navbar-expand-xl .navbar-nav{-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:.5rem;padding-left:.5rem}.navbar-expand-xl>.container,.navbar-expand-xl>.container-fluid{-ms-flex-wrap:nowrap;flex-wrap:nowrap}.navbar-expand-xl .navbar-collapse{display:-ms-flexbox!important;display:flex!important;-ms-flex-preferred-size:auto;flex-basis:auto}.navbar-expand-xl .navbar-toggler{display:none}}.navbar-expand{-ms-flex-flow:row nowrap;flex-flow:row nowrap;-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{-ms-flex-direction:row;flex-direction:row}.navbar-expand .navbar-nav .dropdown-menu{position:absolute}.navbar-expand .navbar-nav .nav-link{padding-right:.5rem;padding-left:.5rem}.navbar-expand>.container,.navbar-expand>.container-fluid{-ms-flex-wrap:nowrap;flex-wrap:nowrap}.navbar-expand .navbar-collapse{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,.9)}.navbar-light .navbar-brand:focus,.navbar-light .navbar-brand:hover{color:rgba(0,0,0,.9)}.navbar-light .navbar-nav .nav-link{color:rgba(0,0,0,.5)}.navbar-light .navbar-nav .nav-link:focus,.navbar-light .navbar-nav .nav-link:hover{color:rgba(0,0,0,.7)}.navbar-light .navbar-nav .nav-link.disabled{color:rgba(0,0,0,.3)}.navbar-light .navbar-nav .active>.nav-link,.navbar-light .navbar-nav .nav-link.active,.navbar-light .navbar-nav .nav-link.show,.navbar-light .navbar-nav .show>.nav-link{color:rgba(0,0,0,.9)}.navbar-light .navbar-toggler{color:rgba(0,0,0,.5);border-color:rgba(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,.5)}.navbar-light .navbar-text a{color:rgba(0,0,0,.9)}.navbar-light .navbar-text a:focus,.navbar-light .navbar-text a:hover{color:rgba(0,0,0,.9)}.navbar-dark .navbar-brand{color:#fff}.navbar-dark .navbar-brand:focus,.navbar-dark .navbar-brand:hover{color:#fff}.navbar-dark .navbar-nav .nav-link{color:rgba(255,255,255,.5)}.navbar-dark .navbar-nav .nav-link:focus,.navbar-dark .navbar-nav .nav-link:hover{color:rgba(255,255,255,.75)}.navbar-dark .navbar-nav .nav-link.disabled{color:rgba(255,255,255,.25)}.navbar-dark .navbar-nav .active>.nav-link,.navbar-dark .navbar-nav .nav-link.active,.navbar-dark .navbar-nav .nav-link.show,.navbar-dark .navbar-nav .show>.nav-link{color:#fff}.navbar-dark .navbar-toggler{color:rgba(255,255,255,.5);border-color:rgba(255,255,255,.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.5)' 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,.5)}.navbar-dark .navbar-text a{color:#fff}.navbar-dark .navbar-text a:focus,.navbar-dark .navbar-text a:hover{color:#fff}.card{position:relative;display:-ms-flexbox;display:flex;-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,.125);border-radius:.25rem}.card>hr{margin-right:0;margin-left:0}.card>.list-group:first-child .list-group-item:first-child{border-top-left-radius:.25rem;border-top-right-radius:.25rem}.card>.list-group:last-child .list-group-item:last-child{border-bottom-right-radius:.25rem;border-bottom-left-radius:.25rem}.card-body{-ms-flex:1 1 auto;flex:1 1 auto;padding:1.25rem}.card-title{margin-bottom:.75rem}.card-subtitle{margin-top:-.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:.75rem 1.25rem;margin-bottom:0;background-color:rgba(0,0,0,.03);border-bottom:1px solid rgba(0,0,0,.125)}.card-header:first-child{border-radius:calc(.25rem - 1px) calc(.25rem - 1px) 0 0}.card-header+.list-group .list-group-item:first-child{border-top:0}.card-footer{padding:.75rem 1.25rem;background-color:rgba(0,0,0,.03);border-top:1px solid rgba(0,0,0,.125)}.card-footer:last-child{border-radius:0 0 calc(.25rem - 1px) calc(.25rem - 1px)}.card-header-tabs{margin-right:-.625rem;margin-bottom:-.75rem;margin-left:-.625rem;border-bottom:0}.card-header-pills{margin-right:-.625rem;margin-left:-.625rem}.card-img-overlay{position:absolute;top:0;right:0;bottom:0;left:0;padding:1.25rem}.card-img{width:100%;border-radius:calc(.25rem - 1px)}.card-img-top{width:100%;border-top-left-radius:calc(.25rem - 1px);border-top-right-radius:calc(.25rem - 1px)}.card-img-bottom{width:100%;border-bottom-right-radius:calc(.25rem - 1px);border-bottom-left-radius:calc(.25rem - 1px)}.card-deck{display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column}.card-deck .card{margin-bottom:15px}@media (min-width:576px){.card-deck{-ms-flex-flow:row wrap;flex-flow:row wrap;margin-right:-15px;margin-left:-15px}.card-deck .card{display:-ms-flexbox;display:flex;-ms-flex:1 0 0%;flex:1 0 0%;-ms-flex-direction:column;flex-direction:column;margin-right:15px;margin-bottom:0;margin-left:15px}}.card-group{display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column}.card-group>.card{margin-bottom:15px}@media (min-width:576px){.card-group{-ms-flex-flow:row wrap;flex-flow:row wrap}.card-group>.card{-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-header,.card-group>.card:first-child .card-img-top{border-top-right-radius:0}.card-group>.card:first-child .card-footer,.card-group>.card:first-child .card-img-bottom{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-header,.card-group>.card:last-child .card-img-top{border-top-left-radius:0}.card-group>.card:last-child .card-footer,.card-group>.card:last-child .card-img-bottom{border-bottom-left-radius:0}.card-group>.card:only-child{border-radius:.25rem}.card-group>.card:only-child .card-header,.card-group>.card:only-child .card-img-top{border-top-left-radius:.25rem;border-top-right-radius:.25rem}.card-group>.card:only-child .card-footer,.card-group>.card:only-child .card-img-bottom{border-bottom-right-radius:.25rem;border-bottom-left-radius:.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-footer,.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-img-bottom,.card-group>.card:not(:first-child):not(:last-child):not(:only-child) .card-img-top{border-radius:0}}.card-columns .card{margin-bottom:.75rem}@media (min-width:576px){.card-columns{-webkit-column-count:3;-moz-column-count:3;column-count:3;-webkit-column-gap:1.25rem;-moz-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:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;padding:.75rem 1rem;margin-bottom:1rem;list-style:none;background-color:#e9ecef;border-radius:.25rem}.breadcrumb-item+.breadcrumb-item{padding-left:.5rem}.breadcrumb-item+.breadcrumb-item::before{display:inline-block;padding-right:.5rem;color:#6c757d;content:"/"}.breadcrumb-item+.breadcrumb-item:hover::before{text-decoration:underline}.breadcrumb-item+.breadcrumb-item:hover::before{text-decoration:none}.breadcrumb-item.active{color:#6c757d}.pagination{display:-ms-flexbox;display:flex;padding-left:0;list-style:none;border-radius:.25rem}.page-link{position:relative;display:block;padding:.5rem .75rem;margin-left:-1px;line-height:1.25;color:#007bff;background-color:#fff;border:1px solid #dee2e6}.page-link:hover{z-index:2;color:#0056b3;text-decoration:none;background-color:#e9ecef;border-color:#dee2e6}.page-link:focus{z-index:2;outline:0;box-shadow:0 0 0 .2rem rgba(0,123,255,.25)}.page-link:not(:disabled):not(.disabled){cursor:pointer}.page-item:first-child .page-link{margin-left:0;border-top-left-radius:.25rem;border-bottom-left-radius:.25rem}.page-item:last-child .page-link{border-top-right-radius:.25rem;border-bottom-right-radius:.25rem}.page-item.active .page-link{z-index:1;color:#fff;background-color:#007bff;border-color:#007bff}.page-item.disabled .page-link{color:#6c757d;pointer-events:none;cursor:auto;background-color:#fff;border-color:#dee2e6}.pagination-lg .page-link{padding:.75rem 1.5rem;font-size:1.25rem;line-height:1.5}.pagination-lg .page-item:first-child .page-link{border-top-left-radius:.3rem;border-bottom-left-radius:.3rem}.pagination-lg .page-item:last-child .page-link{border-top-right-radius:.3rem;border-bottom-right-radius:.3rem}.pagination-sm .page-link{padding:.25rem .5rem;font-size:.875rem;line-height:1.5}.pagination-sm .page-item:first-child .page-link{border-top-left-radius:.2rem;border-bottom-left-radius:.2rem}.pagination-sm .page-item:last-child .page-link{border-top-right-radius:.2rem;border-bottom-right-radius:.2rem}.badge{display:inline-block;padding:.25em .4em;font-size:75%;font-weight:700;line-height:1;text-align:center;white-space:nowrap;vertical-align:baseline;border-radius:.25rem}.badge:empty{display:none}.btn .badge{position:relative;top:-1px}.badge-pill{padding-right:.6em;padding-left:.6em;border-radius:10rem}.badge-primary{color:#fff;background-color:#007bff}.badge-primary[href]:focus,.badge-primary[href]:hover{color:#fff;text-decoration:none;background-color:#0062cc}.badge-secondary{color:#fff;background-color:#6c757d}.badge-secondary[href]:focus,.badge-secondary[href]:hover{color:#fff;text-decoration:none;background-color:#545b62}.badge-success{color:#fff;background-color:#28a745}.badge-success[href]:focus,.badge-success[href]:hover{color:#fff;text-decoration:none;background-color:#1e7e34}.badge-info{color:#fff;background-color:#17a2b8}.badge-info[href]:focus,.badge-info[href]:hover{color:#fff;text-decoration:none;background-color:#117a8b}.badge-warning{color:#212529;background-color:#ffc107}.badge-warning[href]:focus,.badge-warning[href]:hover{color:#212529;text-decoration:none;background-color:#d39e00}.badge-danger{color:#fff;background-color:#dc3545}.badge-danger[href]:focus,.badge-danger[href]:hover{color:#fff;text-decoration:none;background-color:#bd2130}.badge-light{color:#212529;background-color:#f8f9fa}.badge-light[href]:focus,.badge-light[href]:hover{color:#212529;text-decoration:none;background-color:#dae0e5}.badge-dark{color:#fff;background-color:#343a40}.badge-dark[href]:focus,.badge-dark[href]:hover{color:#fff;text-decoration:none;background-color:#1d2124}.jumbotron{padding:2rem 1rem;margin-bottom:2rem;background-color:#e9ecef;border-radius:.3rem}@media (min-width:576px){.jumbotron{padding:4rem 2rem}}.jumbotron-fluid{padding-right:0;padding-left:0;border-radius:0}.alert{position:relative;padding:.75rem 1.25rem;margin-bottom:1rem;border:1px solid transparent;border-radius:.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:.75rem 1.25rem;color:inherit}.alert-primary{color:#004085;background-color:#cce5ff;border-color:#b8daff}.alert-primary hr{border-top-color:#9fcdff}.alert-primary .alert-link{color:#002752}.alert-secondary{color:#383d41;background-color:#e2e3e5;border-color:#d6d8db}.alert-secondary hr{border-top-color:#c8cbcf}.alert-secondary .alert-link{color:#202326}.alert-success{color:#155724;background-color:#d4edda;border-color:#c3e6cb}.alert-success hr{border-top-color:#b1dfbb}.alert-success .alert-link{color:#0b2e13}.alert-info{color:#0c5460;background-color:#d1ecf1;border-color:#bee5eb}.alert-info hr{border-top-color:#abdde5}.alert-info .alert-link{color:#062c33}.alert-warning{color:#856404;background-color:#fff3cd;border-color:#ffeeba}.alert-warning hr{border-top-color:#ffe8a1}.alert-warning .alert-link{color:#533f03}.alert-danger{color:#721c24;background-color:#f8d7da;border-color:#f5c6cb}.alert-danger hr{border-top-color:#f1b0b7}.alert-danger .alert-link{color:#491217}.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:-ms-flexbox;display:flex;height:1rem;overflow:hidden;font-size:.75rem;background-color:#e9ecef;border-radius:.25rem}.progress-bar{display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;-ms-flex-pack:center;justify-content:center;color:#fff;text-align:center;white-space:nowrap;background-color:#007bff;transition:width .6s ease}@media screen and (prefers-reduced-motion:reduce){.progress-bar{transition:none}}.progress-bar-striped{background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.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:-ms-flexbox;display:flex;-ms-flex-align:start;align-items:flex-start}.media-body{-ms-flex:1;flex:1}.list-group{display:-ms-flexbox;display:flex;-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:focus,.list-group-item-action:hover{color:#495057;text-decoration:none;background-color:#f8f9fa}.list-group-item-action:active{color:#212529;background-color:#e9ecef}.list-group-item{position:relative;display:block;padding:.75rem 1.25rem;margin-bottom:-1px;background-color:#fff;border:1px solid rgba(0,0,0,.125)}.list-group-item:first-child{border-top-left-radius:.25rem;border-top-right-radius:.25rem}.list-group-item:last-child{margin-bottom:0;border-bottom-right-radius:.25rem;border-bottom-left-radius:.25rem}.list-group-item:focus,.list-group-item:hover{z-index:1;text-decoration:none}.list-group-item.disabled,.list-group-item:disabled{color:#6c757d;background-color:#fff}.list-group-item.active{z-index:2;color:#fff;background-color:#007bff;border-color:#007bff}.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:#004085;background-color:#b8daff}.list-group-item-primary.list-group-item-action:focus,.list-group-item-primary.list-group-item-action:hover{color:#004085;background-color:#9fcdff}.list-group-item-primary.list-group-item-action.active{color:#fff;background-color:#004085;border-color:#004085}.list-group-item-secondary{color:#383d41;background-color:#d6d8db}.list-group-item-secondary.list-group-item-action:focus,.list-group-item-secondary.list-group-item-action:hover{color:#383d41;background-color:#c8cbcf}.list-group-item-secondary.list-group-item-action.active{color:#fff;background-color:#383d41;border-color:#383d41}.list-group-item-success{color:#155724;background-color:#c3e6cb}.list-group-item-success.list-group-item-action:focus,.list-group-item-success.list-group-item-action:hover{color:#155724;background-color:#b1dfbb}.list-group-item-success.list-group-item-action.active{color:#fff;background-color:#155724;border-color:#155724}.list-group-item-info{color:#0c5460;background-color:#bee5eb}.list-group-item-info.list-group-item-action:focus,.list-group-item-info.list-group-item-action:hover{color:#0c5460;background-color:#abdde5}.list-group-item-info.list-group-item-action.active{color:#fff;background-color:#0c5460;border-color:#0c5460}.list-group-item-warning{color:#856404;background-color:#ffeeba}.list-group-item-warning.list-group-item-action:focus,.list-group-item-warning.list-group-item-action:hover{color:#856404;background-color:#ffe8a1}.list-group-item-warning.list-group-item-action.active{color:#fff;background-color:#856404;border-color:#856404}.list-group-item-danger{color:#721c24;background-color:#f5c6cb}.list-group-item-danger.list-group-item-action:focus,.list-group-item-danger.list-group-item-action:hover{color:#721c24;background-color:#f1b0b7}.list-group-item-danger.list-group-item-action.active{color:#fff;background-color:#721c24;border-color:#721c24}.list-group-item-light{color:#818182;background-color:#fdfdfe}.list-group-item-light.list-group-item-action:focus,.list-group-item-light.list-group-item-action:hover{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:focus,.list-group-item-dark.list-group-item-action:hover{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):focus,.close:not(:disabled):not(.disabled):hover{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:.5rem;pointer-events:none}.modal.fade .modal-dialog{transition:-webkit-transform .3s ease-out;transition:transform .3s ease-out;transition:transform .3s ease-out,-webkit-transform .3s ease-out;-webkit-transform:translate(0,-25%);transform:translate(0,-25%)}@media screen and (prefers-reduced-motion:reduce){.modal.fade .modal-dialog{transition:none}}.modal.show .modal-dialog{-webkit-transform:translate(0,0);transform:translate(0,0)}.modal-dialog-centered{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;min-height:calc(100% - (.5rem * 2))}.modal-dialog-centered::before{display:block;height:calc(100vh - (.5rem * 2));content:""}.modal-content{position:relative;display:-ms-flexbox;display:flex;-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,.2);border-radius:.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:.5}.modal-header{display:-ms-flexbox;display:flex;-ms-flex-align:start;align-items:flex-start;-ms-flex-pack:justify;justify-content:space-between;padding:1rem;border-bottom:1px solid #e9ecef;border-top-left-radius:.3rem;border-top-right-radius:.3rem}.modal-header .close{padding:1rem;margin:-1rem -1rem -1rem auto}.modal-title{margin-bottom:0;line-height:1.5}.modal-body{position:relative;-ms-flex:1 1 auto;flex:1 1 auto;padding:1rem}.modal-footer{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-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:.875rem;word-wrap:break-word;opacity:0}.tooltip.show{opacity:.9}.tooltip .arrow{position:absolute;display:block;width:.8rem;height:.4rem}.tooltip .arrow::before{position:absolute;content:"";border-color:transparent;border-style:solid}.bs-tooltip-auto[x-placement^=top],.bs-tooltip-top{padding:.4rem 0}.bs-tooltip-auto[x-placement^=top] .arrow,.bs-tooltip-top .arrow{bottom:0}.bs-tooltip-auto[x-placement^=top] .arrow::before,.bs-tooltip-top .arrow::before{top:0;border-width:.4rem .4rem 0;border-top-color:#000}.bs-tooltip-auto[x-placement^=right],.bs-tooltip-right{padding:0 .4rem}.bs-tooltip-auto[x-placement^=right] .arrow,.bs-tooltip-right .arrow{left:0;width:.4rem;height:.8rem}.bs-tooltip-auto[x-placement^=right] .arrow::before,.bs-tooltip-right .arrow::before{right:0;border-width:.4rem .4rem .4rem 0;border-right-color:#000}.bs-tooltip-auto[x-placement^=bottom],.bs-tooltip-bottom{padding:.4rem 0}.bs-tooltip-auto[x-placement^=bottom] .arrow,.bs-tooltip-bottom .arrow{top:0}.bs-tooltip-auto[x-placement^=bottom] .arrow::before,.bs-tooltip-bottom .arrow::before{bottom:0;border-width:0 .4rem .4rem;border-bottom-color:#000}.bs-tooltip-auto[x-placement^=left],.bs-tooltip-left{padding:0 .4rem}.bs-tooltip-auto[x-placement^=left] .arrow,.bs-tooltip-left .arrow{right:0;width:.4rem;height:.8rem}.bs-tooltip-auto[x-placement^=left] .arrow::before,.bs-tooltip-left .arrow::before{left:0;border-width:.4rem 0 .4rem .4rem;border-left-color:#000}.tooltip-inner{max-width:200px;padding:.25rem .5rem;color:#fff;text-align:center;background-color:#000;border-radius:.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:.875rem;word-wrap:break-word;background-color:#fff;background-clip:padding-box;border:1px solid rgba(0,0,0,.2);border-radius:.3rem}.popover .arrow{position:absolute;display:block;width:1rem;height:.5rem;margin:0 .3rem}.popover .arrow::after,.popover .arrow::before{position:absolute;display:block;content:"";border-color:transparent;border-style:solid}.bs-popover-auto[x-placement^=top],.bs-popover-top{margin-bottom:.5rem}.bs-popover-auto[x-placement^=top] .arrow,.bs-popover-top .arrow{bottom:calc((.5rem + 1px) * -1)}.bs-popover-auto[x-placement^=top] .arrow::after,.bs-popover-auto[x-placement^=top] .arrow::before,.bs-popover-top .arrow::after,.bs-popover-top .arrow::before{border-width:.5rem .5rem 0}.bs-popover-auto[x-placement^=top] .arrow::before,.bs-popover-top .arrow::before{bottom:0;border-top-color:rgba(0,0,0,.25)}.bs-popover-auto[x-placement^=top] .arrow::after,.bs-popover-top .arrow::after{bottom:1px;border-top-color:#fff}.bs-popover-auto[x-placement^=right],.bs-popover-right{margin-left:.5rem}.bs-popover-auto[x-placement^=right] .arrow,.bs-popover-right .arrow{left:calc((.5rem + 1px) * -1);width:.5rem;height:1rem;margin:.3rem 0}.bs-popover-auto[x-placement^=right] .arrow::after,.bs-popover-auto[x-placement^=right] .arrow::before,.bs-popover-right .arrow::after,.bs-popover-right .arrow::before{border-width:.5rem .5rem .5rem 0}.bs-popover-auto[x-placement^=right] .arrow::before,.bs-popover-right .arrow::before{left:0;border-right-color:rgba(0,0,0,.25)}.bs-popover-auto[x-placement^=right] .arrow::after,.bs-popover-right .arrow::after{left:1px;border-right-color:#fff}.bs-popover-auto[x-placement^=bottom],.bs-popover-bottom{margin-top:.5rem}.bs-popover-auto[x-placement^=bottom] .arrow,.bs-popover-bottom .arrow{top:calc((.5rem + 1px) * -1)}.bs-popover-auto[x-placement^=bottom] .arrow::after,.bs-popover-auto[x-placement^=bottom] .arrow::before,.bs-popover-bottom .arrow::after,.bs-popover-bottom .arrow::before{border-width:0 .5rem .5rem .5rem}.bs-popover-auto[x-placement^=bottom] .arrow::before,.bs-popover-bottom .arrow::before{top:0;border-bottom-color:rgba(0,0,0,.25)}.bs-popover-auto[x-placement^=bottom] .arrow::after,.bs-popover-bottom .arrow::after{top:1px;border-bottom-color:#fff}.bs-popover-auto[x-placement^=bottom] .popover-header::before,.bs-popover-bottom .popover-header::before{position:absolute;top:0;left:50%;display:block;width:1rem;margin-left:-.5rem;content:"";border-bottom:1px solid #f7f7f7}.bs-popover-auto[x-placement^=left],.bs-popover-left{margin-right:.5rem}.bs-popover-auto[x-placement^=left] .arrow,.bs-popover-left .arrow{right:calc((.5rem + 1px) * -1);width:.5rem;height:1rem;margin:.3rem 0}.bs-popover-auto[x-placement^=left] .arrow::after,.bs-popover-auto[x-placement^=left] .arrow::before,.bs-popover-left .arrow::after,.bs-popover-left .arrow::before{border-width:.5rem 0 .5rem .5rem}.bs-popover-auto[x-placement^=left] .arrow::before,.bs-popover-left .arrow::before{right:0;border-left-color:rgba(0,0,0,.25)}.bs-popover-auto[x-placement^=left] .arrow::after,.bs-popover-left .arrow::after{right:1px;border-left-color:#fff}.popover-header{padding:.5rem .75rem;margin-bottom:0;font-size:1rem;color:inherit;background-color:#f7f7f7;border-bottom:1px solid #ebebeb;border-top-left-radius:calc(.3rem - 1px);border-top-right-radius:calc(.3rem - 1px)}.popover-header:empty{display:none}.popover-body{padding:.5rem .75rem;color:#212529}.carousel{position:relative}.carousel-inner{position:relative;width:100%;overflow:hidden}.carousel-item{position:relative;display:none;-ms-flex-align:center;align-items:center;width:100%;-webkit-backface-visibility:hidden;backface-visibility:hidden;-webkit-perspective:1000px;perspective:1000px}.carousel-item-next,.carousel-item-prev,.carousel-item.active{display:block;transition:-webkit-transform .6s ease;transition:transform .6s ease;transition:transform .6s ease,-webkit-transform .6s ease}@media screen and (prefers-reduced-motion:reduce){.carousel-item-next,.carousel-item-prev,.carousel-item.active{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)}}.active.carousel-item-right,.carousel-item-next{-webkit-transform:translateX(100%);transform:translateX(100%)}@supports ((-webkit-transform-style:preserve-3d) or (transform-style:preserve-3d)){.active.carousel-item-right,.carousel-item-next{-webkit-transform:translate3d(100%,0,0);transform:translate3d(100%,0,0)}}.active.carousel-item-left,.carousel-item-prev{-webkit-transform:translateX(-100%);transform:translateX(-100%)}@supports ((-webkit-transform-style:preserve-3d) or (transform-style:preserve-3d)){.active.carousel-item-left,.carousel-item-prev{-webkit-transform:translate3d(-100%,0,0);transform:translate3d(-100%,0,0)}}.carousel-fade .carousel-item{opacity:0;transition-duration:.6s;transition-property:opacity}.carousel-fade .carousel-item-next.carousel-item-left,.carousel-fade .carousel-item-prev.carousel-item-right,.carousel-fade .carousel-item.active{opacity:1}.carousel-fade .active.carousel-item-left,.carousel-fade .active.carousel-item-right{opacity:0}.carousel-fade .active.carousel-item-left,.carousel-fade .active.carousel-item-prev,.carousel-fade .carousel-item-next,.carousel-fade .carousel-item-prev,.carousel-fade .carousel-item.active{-webkit-transform:translateX(0);transform:translateX(0)}@supports ((-webkit-transform-style:preserve-3d) or (transform-style:preserve-3d)){.carousel-fade .active.carousel-item-left,.carousel-fade .active.carousel-item-prev,.carousel-fade .carousel-item-next,.carousel-fade .carousel-item-prev,.carousel-fade .carousel-item.active{-webkit-transform:translate3d(0,0,0);transform:translate3d(0,0,0)}}.carousel-control-next,.carousel-control-prev{position:absolute;top:0;bottom:0;display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center;width:15%;color:#fff;text-align:center;opacity:.5}.carousel-control-next:focus,.carousel-control-next:hover,.carousel-control-prev:focus,.carousel-control-prev:hover{color:#fff;text-decoration:none;outline:0;opacity:.9}.carousel-control-prev{left:0}.carousel-control-next{right:0}.carousel-control-next-icon,.carousel-control-prev-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:-ms-flexbox;display:flex;-ms-flex-pack:center;justify-content:center;padding-left:0;margin-right:15%;margin-left:15%;list-style:none}.carousel-indicators li{position:relative;-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,.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:#007bff!important}a.bg-primary:focus,a.bg-primary:hover,button.bg-primary:focus,button.bg-primary:hover{background-color:#0062cc!important}.bg-secondary{background-color:#6c757d!important}a.bg-secondary:focus,a.bg-secondary:hover,button.bg-secondary:focus,button.bg-secondary:hover{background-color:#545b62!important}.bg-success{background-color:#28a745!important}a.bg-success:focus,a.bg-success:hover,button.bg-success:focus,button.bg-success:hover{background-color:#1e7e34!important}.bg-info{background-color:#17a2b8!important}a.bg-info:focus,a.bg-info:hover,button.bg-info:focus,button.bg-info:hover{background-color:#117a8b!important}.bg-warning{background-color:#ffc107!important}a.bg-warning:focus,a.bg-warning:hover,button.bg-warning:focus,button.bg-warning:hover{background-color:#d39e00!important}.bg-danger{background-color:#dc3545!important}a.bg-danger:focus,a.bg-danger:hover,button.bg-danger:focus,button.bg-danger:hover{background-color:#bd2130!important}.bg-light{background-color:#f8f9fa!important}a.bg-light:focus,a.bg-light:hover,button.bg-light:focus,button.bg-light:hover{background-color:#dae0e5!important}.bg-dark{background-color:#343a40!important}a.bg-dark:focus,a.bg-dark:hover,button.bg-dark:focus,button.bg-dark:hover{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:#007bff!important}.border-secondary{border-color:#6c757d!important}.border-success{border-color:#28a745!important}.border-info{border-color:#17a2b8!important}.border-warning{border-color:#ffc107!important}.border-danger{border-color:#dc3545!important}.border-light{border-color:#f8f9fa!important}.border-dark{border-color:#343a40!important}.border-white{border-color:#fff!important}.rounded{border-radius:.25rem!important}.rounded-top{border-top-left-radius:.25rem!important;border-top-right-radius:.25rem!important}.rounded-right{border-top-right-radius:.25rem!important;border-bottom-right-radius:.25rem!important}.rounded-bottom{border-bottom-right-radius:.25rem!important;border-bottom-left-radius:.25rem!important}.rounded-left{border-top-left-radius:.25rem!important;border-bottom-left-radius:.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:-ms-flexbox!important;display:flex!important}.d-inline-flex{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:-ms-flexbox!important;display:flex!important}.d-sm-inline-flex{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:-ms-flexbox!important;display:flex!important}.d-md-inline-flex{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:-ms-flexbox!important;display:flex!important}.d-lg-inline-flex{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:-ms-flexbox!important;display:flex!important}.d-xl-inline-flex{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:-ms-flexbox!important;display:flex!important}.d-print-inline-flex{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 embed,.embed-responsive iframe,.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.857143%}.embed-responsive-16by9::before{padding-top:56.25%}.embed-responsive-4by3::before{padding-top:75%}.embed-responsive-1by1::before{padding-top:100%}.flex-row{-ms-flex-direction:row!important;flex-direction:row!important}.flex-column{-ms-flex-direction:column!important;flex-direction:column!important}.flex-row-reverse{-ms-flex-direction:row-reverse!important;flex-direction:row-reverse!important}.flex-column-reverse{-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{-ms-flex:1 1 auto!important;flex:1 1 auto!important}.flex-grow-0{-ms-flex-positive:0!important;flex-grow:0!important}.flex-grow-1{-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{-ms-flex-pack:start!important;justify-content:flex-start!important}.justify-content-end{-ms-flex-pack:end!important;justify-content:flex-end!important}.justify-content-center{-ms-flex-pack:center!important;justify-content:center!important}.justify-content-between{-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{-ms-flex-align:start!important;align-items:flex-start!important}.align-items-end{-ms-flex-align:end!important;align-items:flex-end!important}.align-items-center{-ms-flex-align:center!important;align-items:center!important}.align-items-baseline{-ms-flex-align:baseline!important;align-items:baseline!important}.align-items-stretch{-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{-ms-flex-direction:row!important;flex-direction:row!important}.flex-sm-column{-ms-flex-direction:column!important;flex-direction:column!important}.flex-sm-row-reverse{-ms-flex-direction:row-reverse!important;flex-direction:row-reverse!important}.flex-sm-column-reverse{-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{-ms-flex:1 1 auto!important;flex:1 1 auto!important}.flex-sm-grow-0{-ms-flex-positive:0!important;flex-grow:0!important}.flex-sm-grow-1{-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{-ms-flex-pack:start!important;justify-content:flex-start!important}.justify-content-sm-end{-ms-flex-pack:end!important;justify-content:flex-end!important}.justify-content-sm-center{-ms-flex-pack:center!important;justify-content:center!important}.justify-content-sm-between{-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{-ms-flex-align:start!important;align-items:flex-start!important}.align-items-sm-end{-ms-flex-align:end!important;align-items:flex-end!important}.align-items-sm-center{-ms-flex-align:center!important;align-items:center!important}.align-items-sm-baseline{-ms-flex-align:baseline!important;align-items:baseline!important}.align-items-sm-stretch{-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{-ms-flex-direction:row!important;flex-direction:row!important}.flex-md-column{-ms-flex-direction:column!important;flex-direction:column!important}.flex-md-row-reverse{-ms-flex-direction:row-reverse!important;flex-direction:row-reverse!important}.flex-md-column-reverse{-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{-ms-flex:1 1 auto!important;flex:1 1 auto!important}.flex-md-grow-0{-ms-flex-positive:0!important;flex-grow:0!important}.flex-md-grow-1{-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{-ms-flex-pack:start!important;justify-content:flex-start!important}.justify-content-md-end{-ms-flex-pack:end!important;justify-content:flex-end!important}.justify-content-md-center{-ms-flex-pack:center!important;justify-content:center!important}.justify-content-md-between{-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{-ms-flex-align:start!important;align-items:flex-start!important}.align-items-md-end{-ms-flex-align:end!important;align-items:flex-end!important}.align-items-md-center{-ms-flex-align:center!important;align-items:center!important}.align-items-md-baseline{-ms-flex-align:baseline!important;align-items:baseline!important}.align-items-md-stretch{-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{-ms-flex-direction:row!important;flex-direction:row!important}.flex-lg-column{-ms-flex-direction:column!important;flex-direction:column!important}.flex-lg-row-reverse{-ms-flex-direction:row-reverse!important;flex-direction:row-reverse!important}.flex-lg-column-reverse{-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{-ms-flex:1 1 auto!important;flex:1 1 auto!important}.flex-lg-grow-0{-ms-flex-positive:0!important;flex-grow:0!important}.flex-lg-grow-1{-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{-ms-flex-pack:start!important;justify-content:flex-start!important}.justify-content-lg-end{-ms-flex-pack:end!important;justify-content:flex-end!important}.justify-content-lg-center{-ms-flex-pack:center!important;justify-content:center!important}.justify-content-lg-between{-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{-ms-flex-align:start!important;align-items:flex-start!important}.align-items-lg-end{-ms-flex-align:end!important;align-items:flex-end!important}.align-items-lg-center{-ms-flex-align:center!important;align-items:center!important}.align-items-lg-baseline{-ms-flex-align:baseline!important;align-items:baseline!important}.align-items-lg-stretch{-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{-ms-flex-direction:row!important;flex-direction:row!important}.flex-xl-column{-ms-flex-direction:column!important;flex-direction:column!important}.flex-xl-row-reverse{-ms-flex-direction:row-reverse!important;flex-direction:row-reverse!important}.flex-xl-column-reverse{-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{-ms-flex:1 1 auto!important;flex:1 1 auto!important}.flex-xl-grow-0{-ms-flex-positive:0!important;flex-grow:0!important}.flex-xl-grow-1{-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{-ms-flex-pack:start!important;justify-content:flex-start!important}.justify-content-xl-end{-ms-flex-pack:end!important;justify-content:flex-end!important}.justify-content-xl-center{-ms-flex-pack:center!important;justify-content:center!important}.justify-content-xl-between{-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{-ms-flex-align:start!important;align-items:flex-start!important}.align-items-xl-end{-ms-flex-align:end!important;align-items:flex-end!important}.align-items-xl-center{-ms-flex-align:center!important;align-items:center!important}.align-items-xl-baseline{-ms-flex-align:baseline!important;align-items:baseline!important}.align-items-xl-stretch{-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{box-shadow:0 .125rem .25rem rgba(0,0,0,.075)!important}.shadow{box-shadow:0 .5rem 1rem rgba(0,0,0,.15)!important}.shadow-lg{box-shadow:0 1rem 3rem rgba(0,0,0,.175)!important}.shadow-none{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:.25rem!important}.mt-1,.my-1{margin-top:.25rem!important}.mr-1,.mx-1{margin-right:.25rem!important}.mb-1,.my-1{margin-bottom:.25rem!important}.ml-1,.mx-1{margin-left:.25rem!important}.m-2{margin:.5rem!important}.mt-2,.my-2{margin-top:.5rem!important}.mr-2,.mx-2{margin-right:.5rem!important}.mb-2,.my-2{margin-bottom:.5rem!important}.ml-2,.mx-2{margin-left:.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:.25rem!important}.pt-1,.py-1{padding-top:.25rem!important}.pr-1,.px-1{padding-right:.25rem!important}.pb-1,.py-1{padding-bottom:.25rem!important}.pl-1,.px-1{padding-left:.25rem!important}.p-2{padding:.5rem!important}.pt-2,.py-2{padding-top:.5rem!important}.pr-2,.px-2{padding-right:.5rem!important}.pb-2,.py-2{padding-bottom:.5rem!important}.pl-2,.px-2{padding-left:.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:.25rem!important}.mt-sm-1,.my-sm-1{margin-top:.25rem!important}.mr-sm-1,.mx-sm-1{margin-right:.25rem!important}.mb-sm-1,.my-sm-1{margin-bottom:.25rem!important}.ml-sm-1,.mx-sm-1{margin-left:.25rem!important}.m-sm-2{margin:.5rem!important}.mt-sm-2,.my-sm-2{margin-top:.5rem!important}.mr-sm-2,.mx-sm-2{margin-right:.5rem!important}.mb-sm-2,.my-sm-2{margin-bottom:.5rem!important}.ml-sm-2,.mx-sm-2{margin-left:.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:.25rem!important}.pt-sm-1,.py-sm-1{padding-top:.25rem!important}.pr-sm-1,.px-sm-1{padding-right:.25rem!important}.pb-sm-1,.py-sm-1{padding-bottom:.25rem!important}.pl-sm-1,.px-sm-1{padding-left:.25rem!important}.p-sm-2{padding:.5rem!important}.pt-sm-2,.py-sm-2{padding-top:.5rem!important}.pr-sm-2,.px-sm-2{padding-right:.5rem!important}.pb-sm-2,.py-sm-2{padding-bottom:.5rem!important}.pl-sm-2,.px-sm-2{padding-left:.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:.25rem!important}.mt-md-1,.my-md-1{margin-top:.25rem!important}.mr-md-1,.mx-md-1{margin-right:.25rem!important}.mb-md-1,.my-md-1{margin-bottom:.25rem!important}.ml-md-1,.mx-md-1{margin-left:.25rem!important}.m-md-2{margin:.5rem!important}.mt-md-2,.my-md-2{margin-top:.5rem!important}.mr-md-2,.mx-md-2{margin-right:.5rem!important}.mb-md-2,.my-md-2{margin-bottom:.5rem!important}.ml-md-2,.mx-md-2{margin-left:.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:.25rem!important}.pt-md-1,.py-md-1{padding-top:.25rem!important}.pr-md-1,.px-md-1{padding-right:.25rem!important}.pb-md-1,.py-md-1{padding-bottom:.25rem!important}.pl-md-1,.px-md-1{padding-left:.25rem!important}.p-md-2{padding:.5rem!important}.pt-md-2,.py-md-2{padding-top:.5rem!important}.pr-md-2,.px-md-2{padding-right:.5rem!important}.pb-md-2,.py-md-2{padding-bottom:.5rem!important}.pl-md-2,.px-md-2{padding-left:.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:.25rem!important}.mt-lg-1,.my-lg-1{margin-top:.25rem!important}.mr-lg-1,.mx-lg-1{margin-right:.25rem!important}.mb-lg-1,.my-lg-1{margin-bottom:.25rem!important}.ml-lg-1,.mx-lg-1{margin-left:.25rem!important}.m-lg-2{margin:.5rem!important}.mt-lg-2,.my-lg-2{margin-top:.5rem!important}.mr-lg-2,.mx-lg-2{margin-right:.5rem!important}.mb-lg-2,.my-lg-2{margin-bottom:.5rem!important}.ml-lg-2,.mx-lg-2{margin-left:.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:.25rem!important}.pt-lg-1,.py-lg-1{padding-top:.25rem!important}.pr-lg-1,.px-lg-1{padding-right:.25rem!important}.pb-lg-1,.py-lg-1{padding-bottom:.25rem!important}.pl-lg-1,.px-lg-1{padding-left:.25rem!important}.p-lg-2{padding:.5rem!important}.pt-lg-2,.py-lg-2{padding-top:.5rem!important}.pr-lg-2,.px-lg-2{padding-right:.5rem!important}.pb-lg-2,.py-lg-2{padding-bottom:.5rem!important}.pl-lg-2,.px-lg-2{padding-left:.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:.25rem!important}.mt-xl-1,.my-xl-1{margin-top:.25rem!important}.mr-xl-1,.mx-xl-1{margin-right:.25rem!important}.mb-xl-1,.my-xl-1{margin-bottom:.25rem!important}.ml-xl-1,.mx-xl-1{margin-left:.25rem!important}.m-xl-2{margin:.5rem!important}.mt-xl-2,.my-xl-2{margin-top:.5rem!important}.mr-xl-2,.mx-xl-2{margin-right:.5rem!important}.mb-xl-2,.my-xl-2{margin-bottom:.5rem!important}.ml-xl-2,.mx-xl-2{margin-left:.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:.25rem!important}.pt-xl-1,.py-xl-1{padding-top:.25rem!important}.pr-xl-1,.px-xl-1{padding-right:.25rem!important}.pb-xl-1,.py-xl-1{padding-bottom:.25rem!important}.pl-xl-1,.px-xl-1{padding-left:.25rem!important}.p-xl-2{padding:.5rem!important}.pt-xl-2,.py-xl-2{padding-top:.5rem!important}.pr-xl-2,.px-xl-2{padding-right:.5rem!important}.pb-xl-2,.py-xl-2{padding-bottom:.5rem!important}.pl-xl-2,.px-xl-2{padding-left:.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:#007bff!important}a.text-primary:focus,a.text-primary:hover{color:#0062cc!important}.text-secondary{color:#6c757d!important}a.text-secondary:focus,a.text-secondary:hover{color:#545b62!important}.text-success{color:#28a745!important}a.text-success:focus,a.text-success:hover{color:#1e7e34!important}.text-info{color:#17a2b8!important}a.text-info:focus,a.text-info:hover{color:#117a8b!important}.text-warning{color:#ffc107!important}a.text-warning:focus,a.text-warning:hover{color:#d39e00!important}.text-danger{color:#dc3545!important}a.text-danger:focus,a.text-danger:hover{color:#bd2130!important}.text-light{color:#f8f9fa!important}a.text-light:focus,a.text-light:hover{color:#dae0e5!important}.text-dark{color:#343a40!important}a.text-dark:focus,a.text-dark:hover{color:#1d2124!important}.text-body{color:#212529!important}.text-muted{color:#6c757d!important}.text-black-50{color:rgba(0,0,0,.5)!important}.text-white-50{color:rgba(255,255,255,.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{*,::after,::before{text-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}blockquote,pre{border:1px solid #adb5bd;page-break-inside:avoid}thead{display:table-header-group}img,tr{page-break-inside:avoid}h2,h3,p{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 td,.table-bordered th{border:1px solid #dee2e6!important}.table-dark{color:inherit}.table-dark tbody+tbody,.table-dark td,.table-dark th,.table-dark thead th{border-color:#dee2e6}.table .thead-dark th{color:inherit;border-color:#dee2e6}} +/*# sourceMappingURL=bootstrap.min.css.map */ \ No newline at end of file diff --git a/demos/css/emojionearea.min.css b/demos/css/emojionearea.min.css new file mode 100644 index 0000000..f92213c --- /dev/null +++ b/demos/css/emojionearea.min.css @@ -0,0 +1 @@ +.dropdown-menu.textcomplete-dropdown[data-strategy=emojionearea]{position:absolute;z-index:1000;min-width:160px;padding:5px 0;margin:2px 0 0;font-size:14px;text-align:left;list-style:none;background-color:#fff;-webkit-background-clip:padding-box;background-clip:padding-box;border:1px solid #ccc;border:1px solid rgba(0,0,0,.15);-moz-border-radius:4px;-webkit-border-radius:4px;border-radius:4px;-moz-box-shadow:0 6px 12px rgba(0,0,0,.175);-webkit-box-shadow:0 6px 12px rgba(0,0,0,.175);box-shadow:0 6px 12px rgba(0,0,0,.175)}.dropdown-menu.textcomplete-dropdown[data-strategy=emojionearea] li.textcomplete-item{font-size:14px;padding:1px 3px;border:0}.dropdown-menu.textcomplete-dropdown[data-strategy=emojionearea] li.textcomplete-item a{text-decoration:none;display:block;height:100%;line-height:1.8em;padding:0 1.54em 0 .615em;color:#4f4f4f}.dropdown-menu.textcomplete-dropdown[data-strategy=emojionearea] li.textcomplete-item.active,.dropdown-menu.textcomplete-dropdown[data-strategy=emojionearea] li.textcomplete-item:hover{background-color:#e4e4e4}.dropdown-menu.textcomplete-dropdown[data-strategy=emojionearea] li.textcomplete-item.active a,.dropdown-menu.textcomplete-dropdown[data-strategy=emojionearea] li.textcomplete-item:hover a{color:#333}.dropdown-menu.textcomplete-dropdown[data-strategy=emojionearea] li.textcomplete-item .emojioneemoji{font-size:inherit;height:2ex;width:2.1ex;min-height:20px;min-width:20px;display:inline-block;margin:0 5px .2ex 0;line-height:normal;vertical-align:middle;max-width:100%;top:0}.emojionearea-text .emojioneemoji,.emojionearea-text [class*=emojione-]{font-size:inherit;height:2ex;width:2.1ex;min-height:20px;min-width:20px;display:inline-block;margin:-.2ex .15em .2ex;line-height:normal;vertical-align:middle;max-width:100%;top:0}.emojionearea,.emojionearea *{-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box}.emojionearea.emojionearea-disable{position:relative;background-color:#eee;-moz-user-select:-moz-none;-ms-user-select:none;-webkit-user-select:none;user-select:none}.emojionearea.emojionearea-disable:before{content:"";display:block;top:0;left:0;right:0;bottom:0;z-index:1;opacity:.3;position:absolute;background-color:#eee}.emojionearea,.emojionearea.form-control{display:block;position:relative!important;width:100%;height:auto;padding:0;font-size:14px;background-color:#FFF;border:1px solid #CCC;-moz-border-radius:3px;-webkit-border-radius:3px;border-radius:3px;-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075);-moz-transition:border-color .15s ease-in-out,-moz-box-shadow .15s ease-in-out;-o-transition:border-color .15s ease-in-out,box-shadow .15s ease-in-out;-webkit-transition:border-color .15s ease-in-out,-webkit-box-shadow .15s ease-in-out;transition:border-color .15s ease-in-out,box-shadow .15s ease-in-out}.emojionearea.focused{border-color:#66AFE9;outline:0;-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6);-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6);box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6)}.emojionearea .emojionearea-editor{display:block;height:auto;min-height:8em;max-height:15em;overflow:auto;padding:6px 24px 6px 12px;line-height:1.42857143;font-size:inherit;color:#555;background-color:transparent;border:0;cursor:text;margin-right:1px;-moz-border-radius:0;-webkit-border-radius:0;border-radius:0;-moz-box-shadow:none;-webkit-box-shadow:none;box-shadow:none}.emojionearea .emojionearea-editor:empty:before{content:attr(placeholder);display:block;color:#BBB}.emojionearea .emojionearea-editor:focus{border:0;outline:0;-moz-box-shadow:none;-webkit-box-shadow:none;box-shadow:none}.emojionearea .emojionearea-editor .emojioneemoji,.emojionearea .emojionearea-editor [class*=emojione-]{font-size:inherit;height:2ex;width:2.1ex;min-height:20px;min-width:20px;display:inline-block;margin:-.2ex .15em .2ex;line-height:normal;vertical-align:middle;max-width:100%;top:0}.emojionearea.emojionearea-inline{height:34px}.emojionearea.emojionearea-inline>.emojionearea-editor{height:32px;min-height:20px;overflow:hidden;white-space:nowrap;position:absolute;top:0;left:12px;right:24px;padding:6px 0}.emojionearea.emojionearea-inline>.emojionearea-button{top:4px}.emojionearea .emojionearea-button{z-index:5;position:absolute;right:3px;top:3px;width:24px;height:24px;opacity:.6;cursor:pointer;-moz-transition:opacity .3s ease-in-out;-o-transition:opacity .3s ease-in-out;-webkit-transition:opacity .3s ease-in-out;transition:opacity .3s ease-in-out}.emojionearea .emojionearea-button:hover{opacity:1}.emojionearea .emojionearea-button>div{display:block;width:24px;height:24px;position:absolute;-moz-transition:all .4s ease-in-out;-o-transition:all .4s ease-in-out;-webkit-transition:all .4s ease-in-out;transition:all .4s ease-in-out}.emojionearea .emojionearea-button>div.emojionearea-button-open{background-position:0 -24px;filter:alpha(enabled=false);opacity:1}.emojionearea .emojionearea-button>div.emojionearea-button-close{background-position:0 0;-webkit-transform:rotate(-45deg);-o-transform:rotate(-45deg);transform:rotate(-45deg);filter:alpha(Opacity=0);opacity:0}.emojionearea .emojionearea-button.active>div.emojionearea-button-open{-webkit-transform:rotate(45deg);-o-transform:rotate(45deg);transform:rotate(45deg);filter:alpha(Opacity=0);opacity:0}.emojionearea .emojionearea-button.active>div.emojionearea-button-close{-webkit-transform:rotate(0);-o-transform:rotate(0);transform:rotate(0);filter:alpha(enabled=false);opacity:1}.emojionearea .emojionearea-picker{background:#FFF;position:absolute;-moz-box-shadow:0 1px 5px rgba(0,0,0,.32);-webkit-box-shadow:0 1px 5px rgba(0,0,0,.32);box-shadow:0 1px 5px rgba(0,0,0,.32);-moz-border-radius:5px;-webkit-border-radius:5px;border-radius:5px;height:276px;width:316px;top:-15px;right:-15px;z-index:90;-moz-transition:all .25s ease-in-out;-o-transition:all .25s ease-in-out;-webkit-transition:all .25s ease-in-out;transition:all .25s ease-in-out;filter:alpha(Opacity=0);opacity:0;-moz-user-select:-moz-none;-ms-user-select:none;-webkit-user-select:none;user-select:none}.emojionearea .emojionearea-picker.hidden{display:none}.emojionearea .emojionearea-picker .emojionearea-wrapper{position:relative;height:276px;width:316px}.emojionearea .emojionearea-picker .emojionearea-wrapper:after{content:"";display:block;position:absolute;background-repeat:no-repeat;z-index:91}.emojionearea .emojionearea-picker .emojionearea-filters{width:100%;position:absolute;z-index:95;background:#F5F7F9;padding:0 0 0 7px;height:40px}.emojionearea .emojionearea-picker .emojionearea-filters .emojionearea-filter{display:block;float:left;height:40px;width:32px;padding:7px 1px 0;cursor:pointer;-webkit-filter:grayscale(1);filter:grayscale(1)}.emojionearea .emojionearea-picker .emojionearea-filters .emojionearea-filter.active{background:#fff}.emojionearea .emojionearea-picker .emojionearea-filters .emojionearea-filter.active,.emojionearea .emojionearea-picker .emojionearea-filters .emojionearea-filter:hover{-webkit-filter:grayscale(0);filter:grayscale(0)}.emojionearea .emojionearea-picker .emojionearea-filters .emojionearea-filter>i{width:24px;height:24px;top:0}.emojionearea .emojionearea-picker .emojionearea-filters .emojionearea-filter>img{width:24px;height:24px;margin:0 3px}.emojionearea .emojionearea-picker .emojionearea-search-panel{height:30px;position:absolute;z-index:95;top:40px;left:0;right:0;padding:5px 0 5px 8px}.emojionearea .emojionearea-picker .emojionearea-search-panel .emojionearea-tones{float:right;margin-right:10px;margin-top:-1px}.emojionearea .emojionearea-picker .emojionearea-tones-panel .emojionearea-tones{position:absolute;top:4px;left:171px}.emojionearea .emojionearea-picker .emojionearea-search{float:left;padding:0;height:20px;width:160px}.emojionearea .emojionearea-picker .emojionearea-search>input{outline:0;width:160px;min-width:160px;height:20px}.emojionearea .emojionearea-picker .emojionearea-tones{padding:0;width:120px;height:20px}.emojionearea .emojionearea-picker .emojionearea-tones>.btn-tone{display:inline-block;padding:0;border:0;vertical-align:middle;outline:0;background:0 0;cursor:pointer;position:relative}.emojionearea .emojionearea-picker .emojionearea-tones>.btn-tone.btn-tone-0,.emojionearea .emojionearea-picker .emojionearea-tones>.btn-tone.btn-tone-0:after{background-color:#ffcf3e}.emojionearea .emojionearea-picker .emojionearea-tones>.btn-tone.btn-tone-1,.emojionearea .emojionearea-picker .emojionearea-tones>.btn-tone.btn-tone-1:after{background-color:#fae3c5}.emojionearea .emojionearea-picker .emojionearea-tones>.btn-tone.btn-tone-2,.emojionearea .emojionearea-picker .emojionearea-tones>.btn-tone.btn-tone-2:after{background-color:#e2cfa5}.emojionearea .emojionearea-picker .emojionearea-tones>.btn-tone.btn-tone-3,.emojionearea .emojionearea-picker .emojionearea-tones>.btn-tone.btn-tone-3:after{background-color:#daa478}.emojionearea .emojionearea-picker .emojionearea-tones>.btn-tone.btn-tone-4,.emojionearea .emojionearea-picker .emojionearea-tones>.btn-tone.btn-tone-4:after{background-color:#a78058}.emojionearea .emojionearea-picker .emojionearea-tones>.btn-tone.btn-tone-5,.emojionearea .emojionearea-picker .emojionearea-tones>.btn-tone.btn-tone-5:after{background-color:#5e4d43}.emojionearea .emojionearea-picker .emojionearea-tones.emojionearea-tones-bullet>.btn-tone,.emojionearea .emojionearea-picker .emojionearea-tones.emojionearea-tones-square>.btn-tone{width:20px;height:20px;margin:0;background-color:transparent}.emojionearea .emojionearea-picker .emojionearea-tones.emojionearea-tones-bullet>.btn-tone:after,.emojionearea .emojionearea-picker .emojionearea-tones.emojionearea-tones-square>.btn-tone:after{content:"";position:absolute;display:block;top:4px;left:4px;width:12px;height:12px}.emojionearea .emojionearea-picker .emojionearea-tones.emojionearea-tones-bullet>.btn-tone.active:after,.emojionearea .emojionearea-picker .emojionearea-tones.emojionearea-tones-square>.btn-tone.active:after{top:0;left:0;width:20px;height:20px}.emojionearea .emojionearea-picker .emojionearea-tones.emojionearea-tones-checkbox>.btn-tone,.emojionearea .emojionearea-picker .emojionearea-tones.emojionearea-tones-radio>.btn-tone{width:16px;height:16px;margin:0 2px}.emojionearea .emojionearea-picker .emojionearea-tones.emojionearea-tones-checkbox>.btn-tone.active:after,.emojionearea .emojionearea-picker .emojionearea-tones.emojionearea-tones-radio>.btn-tone.active:after{content:"";position:absolute;display:block;background-color:transparent;border:2px solid #fff;width:8px;height:8px;top:2px;left:2px;box-sizing:initial}.emojionearea .emojionearea-picker .emojionearea-scroll-area .emojionearea-category-block:after,.emojionearea .emojionearea-picker .emojionearea-scroll-area .emojionearea-category-block:before,.emojionearea .emojionearea-picker .emojionearea-scroll-area .emojionearea-category-block>.emojionearea-category:after,.emojionearea .emojionearea-picker .emojionearea-scroll-area .emojionearea-category-block>.emojionearea-category:before,.emojionearea .emojionearea-picker .emojionearea-scroll-area .emojionearea-category-title:after,.emojionearea .emojionearea-picker .emojionearea-scroll-area .emojionearea-category-title:before{content:" ";clear:both;display:block}.emojionearea .emojionearea-picker .emojionearea-tones.emojionearea-tones-bullet>.btn-tone,.emojionearea .emojionearea-picker .emojionearea-tones.emojionearea-tones-bullet>.btn-tone:after,.emojionearea .emojionearea-picker .emojionearea-tones.emojionearea-tones-radio>.btn-tone,.emojionearea .emojionearea-picker .emojionearea-tones.emojionearea-tones-radio>.btn-tone:after{-moz-border-radius:100%;-webkit-border-radius:100%;border-radius:100%}.emojionearea .emojionearea-picker .emojionearea-tones.emojionearea-tones-checkbox>.btn-tone,.emojionearea .emojionearea-picker .emojionearea-tones.emojionearea-tones-checkbox>.btn-tone:after,.emojionearea .emojionearea-picker .emojionearea-tones.emojionearea-tones-square>.btn-tone,.emojionearea .emojionearea-picker .emojionearea-tones.emojionearea-tones-square>.btn-tone:after{-moz-border-radius:1px;-webkit-border-radius:1px;border-radius:1px}.emojionearea .emojionearea-picker .emojionearea-scroll-area{height:236px;overflow:auto;overflow-x:hidden;width:100%;position:absolute;padding:0 0 5px}.emojionearea .emojionearea-picker .emojionearea-search-panel+.emojionearea-scroll-area{height:206px}.emojionearea .emojionearea-picker .emojionearea-scroll-area .emojionearea-emojis-list{z-index:1}.emojionearea .emojionearea-picker .emojionearea-scroll-area .emojionearea-category-title{display:block;font-family:Arial,'Helvetica Neue',Helvetica,sans-serif;font-size:13px;font-weight:400;color:#b2b2b2;background:#FFF;line-height:20px;margin:0;padding:7px 0 5px 6px}.emojionearea .emojionearea-picker .emojionearea-scroll-area .emojionearea-category-block{padding:0 0 0 7px}.emojionearea .emojionearea-picker .emojionearea-scroll-area .emojionearea-category-block>.emojionearea-category{padding:0!important}.emojionearea .emojionearea-picker .emojionearea-scroll-area [class*=emojione-]{-moz-box-sizing:content-box;-webkit-box-sizing:content-box;box-sizing:content-box;margin:0;width:24px;height:24px;top:0}.emojionearea .emojionearea-picker .emojionearea-scroll-area .emojibtn{-moz-box-sizing:content-box;-webkit-box-sizing:content-box;box-sizing:content-box;width:24px;height:24px;float:left;display:block;margin:1px;padding:3px}.emojionearea .emojionearea-picker .emojionearea-scroll-area .emojibtn:hover{-moz-border-radius:4px;-webkit-border-radius:4px;border-radius:4px;background-color:#e4e4e4;cursor:pointer}.emojionearea .emojionearea-picker .emojionearea-scroll-area .emojibtn i,.emojionearea .emojionearea-picker .emojionearea-scroll-area .emojibtn img{float:left;display:block;width:24px;height:24px}.emojionearea .emojionearea-picker .emojionearea-scroll-area .emojibtn img.lazy-emoji{filter:alpha(Opacity=0);opacity:0}.emojionearea .emojionearea-picker.emojionearea-filters-position-top .emojionearea-filters{top:0;-moz-border-radius-topleft:5px;-webkit-border-top-left-radius:5px;border-top-left-radius:5px;-moz-border-radius-topright:5px;-webkit-border-top-right-radius:5px;border-top-right-radius:5px}.emojionearea .emojionearea-picker.emojionearea-filters-position-top.emojionearea-search-position-top .emojionearea-scroll-area{bottom:0}.emojionearea .emojionearea-picker.emojionearea-filters-position-top.emojionearea-search-position-bottom .emojionearea-scroll-area{top:40px}.emojionearea .emojionearea-picker.emojionearea-filters-position-top.emojionearea-search-position-bottom .emojionearea-search-panel{top:initial;bottom:0}.emojionearea .emojionearea-picker.emojionearea-filters-position-bottom .emojionearea-filters{bottom:0;-moz-border-radius-bottomleft:5px;-webkit-border-bottom-left-radius:5px;border-bottom-left-radius:5px;-moz-border-radius-bottomright:5px;-webkit-border-bottom-right-radius:5px;border-bottom-right-radius:5px}.emojionearea .emojionearea-picker.emojionearea-filters-position-bottom.emojionearea-search-position-bottom .emojionearea-scroll-area{top:0}.emojionearea .emojionearea-picker.emojionearea-filters-position-bottom.emojionearea-search-position-bottom .emojionearea-search-panel,.emojionearea .emojionearea-picker.emojionearea-filters-position-bottom.emojionearea-search-position-top .emojionearea-scroll-area{top:initial;bottom:40px}.emojionearea .emojionearea-picker.emojionearea-filters-position-bottom.emojionearea-search-position-top .emojionearea-search-panel{top:0}.emojionearea .emojionearea-picker.emojionearea-picker-position-top{margin-top:-286px;right:-14px}.emojionearea .emojionearea-picker.emojionearea-picker-position-top .emojionearea-wrapper:after{width:19px;height:10px;background-position:-2px -49px;bottom:-10px;right:20px}.emojionearea .emojionearea-picker.emojionearea-picker-position-top.emojionearea-filters-position-bottom .emojionearea-wrapper:after{background-position:-2px -80px}.emojionearea .emojionearea-picker.emojionearea-picker-position-left,.emojionearea .emojionearea-picker.emojionearea-picker-position-right{margin-right:-326px;top:-8px}.emojionearea .emojionearea-picker.emojionearea-picker-position-left .emojionearea-wrapper:after,.emojionearea .emojionearea-picker.emojionearea-picker-position-right .emojionearea-wrapper:after{width:10px;height:19px;background-position:0 -60px;top:13px;left:-10px}.emojionearea .emojionearea-picker.emojionearea-picker-position-left.emojionearea-filters-position-bottom .emojionearea-wrapper:after,.emojionearea .emojionearea-picker.emojionearea-picker-position-right.emojionearea-filters-position-bottom .emojionearea-wrapper:after{background-position:right -60px}.emojionearea .emojionearea-picker.emojionearea-picker-position-bottom{margin-top:10px;right:-14px;top:47px}.emojionearea .emojionearea-picker.emojionearea-picker-position-bottom .emojionearea-wrapper:after{width:19px;height:10px;background-position:-2px -100px;top:-10px;right:20px}.emojionearea .emojionearea-picker.emojionearea-picker-position-bottom.emojionearea-filters-position-bottom .emojionearea-wrapper:after{background-position:-2px -90px}.emojionearea .emojionearea-button.active+.emojionearea-picker{filter:alpha(enabled=false);opacity:1}.emojionearea .emojionearea-button.active+.emojionearea-picker-position-top{margin-top:-269px}.emojionearea .emojionearea-button.active+.emojionearea-picker-position-left,.emojionearea .emojionearea-button.active+.emojionearea-picker-position-right{margin-right:-309px}.emojionearea .emojionearea-button.active+.emojionearea-picker-position-bottom{margin-top:-7px}.emojionearea.emojionearea-standalone{display:inline-block;width:auto;box-shadow:none}.emojionearea.emojionearea-standalone .emojionearea-editor{min-height:33px;position:relative;padding:6px 42px 6px 6px}.emojionearea.emojionearea-standalone .emojionearea-editor::before{content:"";position:absolute;top:4px;left:50%;bottom:4px;border-left:1px solid #e6e6e6}.emojionearea.emojionearea-standalone .emojionearea-editor.has-placeholder .emojioneemoji{opacity:.4}.emojionearea.emojionearea-standalone .emojionearea-button{top:0;right:0;bottom:0;left:0;width:auto;height:auto}.emojionearea.emojionearea-standalone .emojionearea-button>div{right:6px;top:5px}.emojionearea.emojionearea-standalone .emojionearea-picker.emojionearea-picker-position-bottom .emojionearea-wrapper:after,.emojionearea.emojionearea-standalone .emojionearea-picker.emojionearea-picker-position-top .emojionearea-wrapper:after{right:23px}.emojionearea.emojionearea-standalone .emojionearea-picker.emojionearea-picker-position-left .emojionearea-wrapper:after,.emojionearea.emojionearea-standalone .emojionearea-picker.emojionearea-picker-position-right .emojionearea-wrapper:after{top:15px}.emojionearea .emojionearea-button>div,.emojionearea .emojionearea-picker .emojionearea-wrapper:after{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABcAAABuCAYAAADMB4ipAAAHfElEQVRo3u1XS1NT2Rb+9uOcQF4YlAJzLymFUHaLrdxKULvEUNpdTnRqD532f+AHMLMc94gqR1Zbt8rBnUh3YXipPGKwRDoWgXvrYiFUlEdIkPPYZ/dAkwox5yQCVt/bzRrBPnt9e+211/etFeDQDu3ArL+/X37OeqmRWoH7+vpItfWawStF1tfXR+zW9xW5ne0p8loOcAKuCdwpRft60C8a+X5zTvebCqcAvmidf1GGHtqhHdpf1qqKzsrKipyensbi4iKWl5cBAMFgEG1tbYhGo2hpadlbmxseHpaDg4MAgI6ODng8HgBAPp/H/Pw8AODatWvo7e2tvUHrui7v3r2L+fl5XL58GVeuXIHH49m1N5/Py0ePHmF0dBQdHR24desWVFXdtYdXAn/48CHm5+dx8+ZNRKPRigEUDpuenpb3799H4YaOnWh5eVmOj48jFoshGo0STdPkwMCAXF5elqV7BgYGpKZpMhqNklgshrGxMbx580Y6gicSCTDGEIvFAADpdBqpVArJZLK4J5lMIpVKIZ1OAwBisRgYY0gkEs6Rp1IphMNh+Hw+AgCGYQAANE0r7in8Xfjm8/lIOBzGq1evnMHX19fR1NRU/D8UCoFzjnA4XFwLh8PgnCMUChXXmpqakM1mUfVBS62xsZHk83lZWi1nz579ZA0AhBDO4A0NDchkMsWSJIRAURRiVy26rktVVUkmk0EgEHAGP3XqFKamppDP56Vpmrhz5w5u374t/X4/OP+w3TRNZLNZ6LoO0zSRz+dlf38/Ll686Jzz8+fPQwiBeDwOt9tNrl+/jkwmU6yaQpVkMhncuHEDbrebxONxCCEQiUScIw8Gg+TBgwdyZGQEyWRSdnV1kVQqJYeGhrC6ugrGGEKhEHp7e3Hy5EmSTCblvXv30NPTg2AwSA6M/vF4HCMjI7b0/yzh8vv9AIBsNrt34aokuQsLC7skt729varkHtqftUFf++FHsrq0QN3eBvp68Tfvf9Mv12oFCYU7G//e9nVuO7dpNbe2W4M//yQr0p8yRvyBo1Zr++lwLcCt7afD/sBRizJGavrB1dDYYh47Htrq+Kb7jBNwxzfdZ44dD201NLaYVUkU7ozQpuAJBkARwnRZpunN5zaa5hJjiXLH05GeiMd7JEM5zzHGNQBGZvk/Iv0yYVWMvK0zKk1Dl6ahW5RQobjqdjy+wEZn9PKF0n2d0csXPL7AhuKq26GECtPQLdPQZVtn1LlB69p7yRVVSEiDEGJwRd12e4+8PR3piRQidnuPvOWKuk0IMSSkwRVV6Np7WVVbSqvGsgSnlKkAFNPQXdrOtuKqcxtcUTUAhmUJnVJmlleJo3CVHmAaOlPUOmYJkxFKibQsSRkXhr4juKIKO2BHVSwcoLrqCVdUYho6K3YYRRWmoUtdey/tgKtK7rUffiQAsLq08MnbNLe2WwBgB/zHzueFyD8nwlIfbvdx8eU0WV1aKD1cVAMs9+F2j9gUPEEKemEJIe3AnXy4XfkBoNKSZHNthWfX31EA69VKttyHVyIOY1wRwmS6tqNsrr31vXo5k/bUu4gT2cp9lhbm0rzCJpeUUrE0vS63+c7/6uXMbDUWl/ssLczNFrVFddUT09AZpUy1LKvO0DVfPrfR9HxqfNbuEe185l9MFX3o6tIC5YpKFLWOfdQQ93Zu49j0+FDCDtjOp1yaOQCYhs4Y40wI05XfWj8yPT40Ua2ey33mEmMTtp2IUEq0nW3FKeJPGPjRp1Iz2QUuLUu66txG9NLVSK3gBZ+C1lcE54oqKOOCK6rm8QU2unu+u1ANuNynvFsBAG1ubbdMQ5eGviMAFDuP0w3sfMpvQEtb24fOQncU1bXl8R7JnOu+ZNv97XxKJwY6+PNPsrm13drObVqUMlMIU5OWpVHOc96Go5lTnV2fzC/VfAozD7HTCa6olBBa1Imlhbmq2lLuQ5xaW6nCPfnln0Yt7bDUhzhps8cfKH5//uTXmvS81OeLdqI/ZoROzSZrHqG/OvOPzxuhK5VgJTvV2bW3EdqJRABwrvvS/kfoSkoZvXT1YEbociHr7vnuYEfogpBFL109HKH/h0fomnXg3Lff79r7/MmvVbWG7gX4QObzc99+Tz7mHKah05KcW6ahQ9feS6cbMCdgt7eBWJagjCuUAC5tZzuouuo0Spm0hElc9R4cbf4bVl8v1p6WUmCuqEwIs34ruxaeeTy4uJVd67As08UVlVmWoG5vA7FLG3WMmHEupVTyW+vh2cn4DADMTsaTuc21LiGEhzHOnQ6gNtMrJSBMCKHkNt999WLi0S7hejEZH81n174WpukiIMw0dKq66p3Bw50RwhUVXFGJKUy28Xal48VkfKrSlWenhsc23q2cEB9SR7iiItwZIbbgHn8AlDFCCMW7laXjqZnHjkNpaubJzNuVpWZCKChjxOMPVH/QlaW0f/G3ZLqWWl6ce/bvlddp7yFD/w8Z+njoX1+GoZMjgzMAMDkyeLAMnRh+uKveJ0YGD4ahEyODFRk6OfrL/hj67GnckaHPng7vjaGzyYmaGDr77KktQ38H8tqx8Wja+WIAAAAASUVORK5CYII=)!important}.emojionearea.emojionearea-standalone .emojionearea-editor.has-placeholder{background-repeat:no-repeat;background-position:20px 4px;background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAMAQMAAABsu86kAAAABlBMVEUAAAC/v79T5hyIAAAAAXRSTlMAQObYZgAAABNJREFUCNdjYGNgQEb/P4AQqiAASiUEG6Vit44AAAAASUVORK5CYII=)!important} \ No newline at end of file diff --git a/demos/dashboard/canvas-designer-old.html b/demos/dashboard/canvas-designer-old.html new file mode 100644 index 0000000..d1e9e68 --- /dev/null +++ b/demos/dashboard/canvas-designer-old.html @@ -0,0 +1,805 @@ + + + + + + + + Dashboard + Video Conferencing + Chat + File Sharing | RTCMultiConnection + + + + + + + + + + + + + + + + + + + + + + +
+
+
+ +
+
+
+
+
+ +
+
+ + + + + +
+ + +
+
+ + + + diff --git a/demos/dashboard/canvas-designer.html b/demos/dashboard/canvas-designer.html new file mode 100644 index 0000000..6734b33 --- /dev/null +++ b/demos/dashboard/canvas-designer.html @@ -0,0 +1,794 @@ + + + + + + + + Dashboard + Video Conferencing + Chat + File Sharing | RTCMultiConnection + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + +
+ +
+
+
+
+
+ +
+
+ + + + + +
+ + +
+
+ + + + diff --git a/demos/dashboard/index-old.html b/demos/dashboard/index-old.html new file mode 100644 index 0000000..7c7af67 --- /dev/null +++ b/demos/dashboard/index-old.html @@ -0,0 +1,776 @@ + + + + + + + + Dashboard + Video Conferencing + Chat + File Sharing | RTCMultiConnection + + + + + + + + + + + + + + +
+ Dashboard Example + +
+ + + Active rooms: 0 +
+
+ + + + + + + + + + +
+ + + + + + + + + + + + + +
#Room IDOwner IDSessionExtraParticipantsJoin
No active room found for this demo.
+
+ + + + + + diff --git a/demos/dashboard/index.html b/demos/dashboard/index.html new file mode 100644 index 0000000..131b72c --- /dev/null +++ b/demos/dashboard/index.html @@ -0,0 +1,767 @@ + + + + + + + + Dashboard + Video Conferencing + Chat + File Sharing | RTCMultiConnection + + + + + + + + + + + + + + +
+ Dashboard Example + +
+ + + Active rooms: 0 +
+
+ + + + + + + + + + +
+ + + + + + + + + + + + + +
#Room IDOwner IDSessionExtraParticipantsJoin
No active room found for this demo.
+
+ + + + + + diff --git a/demos/file-sharing.html b/demos/file-sharing.html new file mode 100644 index 0000000..611d60f --- /dev/null +++ b/demos/file-sharing.html @@ -0,0 +1,769 @@ + + + + File Sharing using RTCMultiConnection + + + + + + + + + + + + + + + + +
+ + + + +
+

+ +

+
+ +
0
+
+

+ Peer-to-Peer (private) file sharing. +

+

+ You can share/receive files from any platform/device e.g. destkop operating systems, Android, iOS etc. +

+

+ Create or join a room & select file using "+" button. +

+
+ + + + + + + + + + + + + + + + diff --git a/demos/getStats.html b/demos/getStats.html new file mode 100644 index 0000000..f1e6433 --- /dev/null +++ b/demos/getStats.html @@ -0,0 +1,334 @@ + + + + + getStats using RTCMultiConnection + + + + + + +
+ + MenuMenu + +
+ +

+ getStats using RTCMultiConnection +

+ Using WebRTC getStats API to detect data sent/received, packets lost/success, ports/network, encryption and more. +

+

+ +
+ + + + + + + + +
+
+ + + + + + + + + + + + +
+

iOS or Android

+

+ You can write iOS or Android apps for this demo as well. +

+
+ + + + + + diff --git a/demos/index.html b/demos/index.html new file mode 100644 index 0000000..714ba34 --- /dev/null +++ b/demos/index.html @@ -0,0 +1,221 @@ + + + + + + RTCMultiConnection Demos + + + + + + + + + +
+ + MenuMenu + +
+ +

+ RTCMultiConnection Demos + +

+ RTCMultiConnection is a WebRTC JavaScript library for peer-to-peer applications (screen sharing, audio/video conferencing, file sharing, media streaming etc.) +

+

+ +
+

+ + Star + Issue + Fork + Follow @muaz-khan + +

+
+ +
+

+ Scalable Broadcast Demos +

+ + + + + + + + + + + + + + + +
RTCMultiConnection Demo TitleDemoSource
Scalable Audio/Video BroadcastDemoSource
+
+
+

+ How to install RTCMultiConnection? +

+

+ https://www.youtube.com/watch?v=EtsiYEW_T8Y +

+
+ + + + + + + diff --git a/demos/js/bootstrap.min.js b/demos/js/bootstrap.min.js new file mode 100644 index 0000000..00c895f --- /dev/null +++ b/demos/js/bootstrap.min.js @@ -0,0 +1,7 @@ +/*! + * Bootstrap v4.1.3 (https://getbootstrap.com/) + * Copyright 2011-2018 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.bootstrap={},t.jQuery,t.Popper)}(this,function(t,e,h){"use strict";function i(t,e){for(var n=0;nthis._items.length-1||t<0))if(this._isSliding)P(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:!(Ie={AUTO:"auto",TOP:"top",RIGHT:"right",BOTTOM:"bottom",LEFT:"left"}),selector:!(Se={animation:"boolean",template:"string",title:"(string|element|function)",trigger:"string",delay:"(number|object)",html:"boolean",selector:"(string|boolean)",placement:"(string|function)",offset:"(number|string)",container:"(string|element|boolean)",fallbackPlacement:"(string|array)",boundary:"(string|element)"}),placement:"top",offset:0,container:!1,fallbackPlacement:"flip",boundary:"scrollParent"},we="out",Ne={HIDE:"hide"+Ee,HIDDEN:"hidden"+Ee,SHOW:(De="show")+Ee,SHOWN:"shown"+Ee,INSERTED:"inserted"+Ee,CLICK:"click"+Ee,FOCUSIN:"focusin"+Ee,FOCUSOUT:"focusout"+Ee,MOUSEENTER:"mouseenter"+Ee,MOUSELEAVE:"mouseleave"+Ee},Oe="fade",ke="show",Pe=".tooltip-inner",je=".arrow",He="hover",Le="focus",Re="click",xe="manual",We=function(){function i(t,e){if("undefined"==typeof h)throw new TypeError("Bootstrap 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=pe(t.currentTarget).data(e);n||(n=new this.constructor(t.currentTarget,this._getDelegateConfig()),pe(t.currentTarget).data(e,n)),n._activeTrigger.click=!n._activeTrigger.click,n._isWithActiveTrigger()?n._enter(null,n):n._leave(null,n)}else{if(pe(this.getTipElement()).hasClass(ke))return void this._leave(null,this);this._enter(null,this)}},t.dispose=function(){clearTimeout(this._timeout),pe.removeData(this.element,this.constructor.DATA_KEY),pe(this.element).off(this.constructor.EVENT_KEY),pe(this.element).closest(".modal").off("hide.bs.modal"),this.tip&&pe(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"===pe(this.element).css("display"))throw new Error("Please use show on visible elements");var t=pe.Event(this.constructor.Event.SHOW);if(this.isWithContent()&&this._isEnabled){pe(this.element).trigger(t);var n=pe.contains(this.element.ownerDocument.documentElement,this.element);if(t.isDefaultPrevented()||!n)return;var i=this.getTipElement(),r=Fn.getUID(this.constructor.NAME);i.setAttribute("id",r),this.element.setAttribute("aria-describedby",r),this.setContent(),this.config.animation&&pe(i).addClass(Oe);var o="function"==typeof this.config.placement?this.config.placement.call(this,i,this.element):this.config.placement,s=this._getAttachment(o);this.addAttachmentClass(s);var a=!1===this.config.container?document.body:pe(document).find(this.config.container);pe(i).data(this.constructor.DATA_KEY,this),pe.contains(this.element.ownerDocument.documentElement,this.tip)||pe(i).appendTo(a),pe(this.element).trigger(this.constructor.Event.INSERTED),this._popper=new h(this.element,i,{placement:s,modifiers:{offset:{offset:this.config.offset},flip:{behavior:this.config.fallbackPlacement},arrow:{element:je},preventOverflow:{boundariesElement:this.config.boundary}},onCreate:function(t){t.originalPlacement!==t.placement&&e._handlePopperPlacementChange(t)},onUpdate:function(t){e._handlePopperPlacementChange(t)}}),pe(i).addClass(ke),"ontouchstart"in document.documentElement&&pe(document.body).children().on("mouseover",null,pe.noop);var l=function(){e.config.animation&&e._fixTransition();var t=e._hoverState;e._hoverState=null,pe(e.element).trigger(e.constructor.Event.SHOWN),t===we&&e._leave(null,e)};if(pe(this.tip).hasClass(Oe)){var c=Fn.getTransitionDurationFromElement(this.tip);pe(this.tip).one(Fn.TRANSITION_END,l).emulateTransitionEnd(c)}else l()}},t.hide=function(t){var e=this,n=this.getTipElement(),i=pe.Event(this.constructor.Event.HIDE),r=function(){e._hoverState!==De&&n.parentNode&&n.parentNode.removeChild(n),e._cleanTipClass(),e.element.removeAttribute("aria-describedby"),pe(e.element).trigger(e.constructor.Event.HIDDEN),null!==e._popper&&e._popper.destroy(),t&&t()};if(pe(this.element).trigger(i),!i.isDefaultPrevented()){if(pe(n).removeClass(ke),"ontouchstart"in document.documentElement&&pe(document.body).children().off("mouseover",null,pe.noop),this._activeTrigger[Re]=!1,this._activeTrigger[Le]=!1,this._activeTrigger[He]=!1,pe(this.tip).hasClass(Oe)){var o=Fn.getTransitionDurationFromElement(n);pe(n).one(Fn.TRANSITION_END,r).emulateTransitionEnd(o)}else r();this._hoverState=""}},t.update=function(){null!==this._popper&&this._popper.scheduleUpdate()},t.isWithContent=function(){return Boolean(this.getTitle())},t.addAttachmentClass=function(t){pe(this.getTipElement()).addClass(Te+"-"+t)},t.getTipElement=function(){return this.tip=this.tip||pe(this.config.template)[0],this.tip},t.setContent=function(){var t=this.getTipElement();this.setElementContent(pe(t.querySelectorAll(Pe)),this.getTitle()),pe(t).removeClass(Oe+" "+ke)},t.setElementContent=function(t,e){var n=this.config.html;"object"==typeof e&&(e.nodeType||e.jquery)?n?pe(e).parent().is(t)||t.empty().append(e):t.text(pe(e).text()):t[n?"html":"text"](e)},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._getAttachment=function(t){return Ie[t.toUpperCase()]},t._setListeners=function(){var i=this;this.config.trigger.split(" ").forEach(function(t){if("click"===t)pe(i.element).on(i.constructor.Event.CLICK,i.config.selector,function(t){return i.toggle(t)});else if(t!==xe){var e=t===He?i.constructor.Event.MOUSEENTER:i.constructor.Event.FOCUSIN,n=t===He?i.constructor.Event.MOUSELEAVE:i.constructor.Event.FOCUSOUT;pe(i.element).on(e,i.config.selector,function(t){return i._enter(t)}).on(n,i.config.selector,function(t){return i._leave(t)})}pe(i.element).closest(".modal").on("hide.bs.modal",function(){return 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||pe(t.currentTarget).data(n))||(e=new this.constructor(t.currentTarget,this._getDelegateConfig()),pe(t.currentTarget).data(n,e)),t&&(e._activeTrigger["focusin"===t.type?Le:He]=!0),pe(e.getTipElement()).hasClass(ke)||e._hoverState===De?e._hoverState=De:(clearTimeout(e._timeout),e._hoverState=De,e.config.delay&&e.config.delay.show?e._timeout=setTimeout(function(){e._hoverState===De&&e.show()},e.config.delay.show):e.show())},t._leave=function(t,e){var n=this.constructor.DATA_KEY;(e=e||pe(t.currentTarget).data(n))||(e=new this.constructor(t.currentTarget,this._getDelegateConfig()),pe(t.currentTarget).data(n,e)),t&&(e._activeTrigger["focusout"===t.type?Le:He]=!1),e._isWithActiveTrigger()||(clearTimeout(e._timeout),e._hoverState=we,e.config.delay&&e.config.delay.hide?e._timeout=setTimeout(function(){e._hoverState===we&&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){return"number"==typeof(t=l({},this.constructor.Default,pe(this.element).data(),"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()),Fn.typeCheckConfig(ve,t,this.constructor.DefaultType),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=pe(this.getTipElement()),e=t.attr("class").match(be);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")&&(pe(t).removeClass(Oe),this.config.animation=!1,this.hide(),this.show(),this.config.animation=e)},i._jQueryInterface=function(n){return this.each(function(){var t=pe(this).data(ye),e="object"==typeof n&&n;if((t||!/dispose|hide/.test(n))&&(t||(t=new i(this,e),pe(this).data(ye,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.1.3"}},{key:"Default",get:function(){return Ae}},{key:"NAME",get:function(){return ve}},{key:"DATA_KEY",get:function(){return ye}},{key:"Event",get:function(){return Ne}},{key:"EVENT_KEY",get:function(){return Ee}},{key:"DefaultType",get:function(){return Se}}]),i}(),pe.fn[ve]=We._jQueryInterface,pe.fn[ve].Constructor=We,pe.fn[ve].noConflict=function(){return pe.fn[ve]=Ce,We._jQueryInterface},We),Jn=(qe="popover",Ke="."+(Fe="bs.popover"),Me=(Ue=e).fn[qe],Qe="bs-popover",Be=new RegExp("(^|\\s)"+Qe+"\\S+","g"),Ve=l({},zn.Default,{placement:"right",trigger:"click",content:"",template:''}),Ye=l({},zn.DefaultType,{content:"(string|element|function)"}),ze="fade",Ze=".popover-header",Ge=".popover-body",$e={HIDE:"hide"+Ke,HIDDEN:"hidden"+Ke,SHOW:(Je="show")+Ke,SHOWN:"shown"+Ke,INSERTED:"inserted"+Ke,CLICK:"click"+Ke,FOCUSIN:"focusin"+Ke,FOCUSOUT:"focusout"+Ke,MOUSEENTER:"mouseenter"+Ke,MOUSELEAVE:"mouseleave"+Ke},Xe=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 r=i.prototype;return r.isWithContent=function(){return this.getTitle()||this._getContent()},r.addAttachmentClass=function(t){Ue(this.getTipElement()).addClass(Qe+"-"+t)},r.getTipElement=function(){return this.tip=this.tip||Ue(this.config.template)[0],this.tip},r.setContent=function(){var t=Ue(this.getTipElement());this.setElementContent(t.find(Ze),this.getTitle());var e=this._getContent();"function"==typeof e&&(e=e.call(this.element)),this.setElementContent(t.find(Ge),e),t.removeClass(ze+" "+Je)},r._getContent=function(){return this.element.getAttribute("data-content")||this.config.content},r._cleanTipClass=function(){var t=Ue(this.getTipElement()),e=t.attr("class").match(Be);null!==e&&0=this._offsets[r]&&("undefined"==typeof this._offsets[r+1]||t4?(h=b.uc_base,b=b.uc_output.toUpperCase()):h=b,a.replace("{name}",c||"").replace("{friendlyName}",g).replace("{img}",f+(k<2?h.toUpperCase():h)+"."+d).replace("{uni}",b).replace("{alt}",e.convert(b))}function p(a,b,c){return a.replace(/:?\+?[\w_\-]+:?/g,function(a){a=":"+a.replace(/:$/,"").replace(/^:/,"")+":";var d=e.emojioneList[a];return d?k>4?o(b,d,a):(k>3&&(d=d.unicode),o(b,d[d.length-1],a)):c?"":a})}function q(a){var b,c;if(window.getSelection){if(b=window.getSelection(),b.getRangeAt&&b.rangeCount){c=b.getRangeAt(0),c.deleteContents();var d=document.createElement("div");d.innerHTML=a;var e=document.createDocumentFragment(),f,g;while(f=d.firstChild)g=e.appendChild(f);c.insertNode(e),g&&(c=c.cloneRange(),c.setStartAfter(g),c.collapse(!0),b.removeAllRanges(),b.addRange(c))}}else document.selection&&"Control"!=document.selection.type&&document.selection.createRange().pasteHTML(a)}function r(){return window.emojioneVersion||"3.1.2"}function s(a){return"object"==typeof a}function t(a){var b;return a.cacheBustParam?(b=a.cacheBustParam,s(a.jsEscapeMap)?"?v=1.2.4"===b?"2.0.0":"?v=2.0.1"===b?"2.1.0":"?v=2.1.1"===b?"2.1.1":"?v=2.1.2"===b?"2.1.2":"?v=2.1.3"===b?"2.1.3":"?v=2.1.4"===b?"2.1.4":"2.2.7":"1.5.2"):a.emojiVersion}function u(a){switch(a){case"1.5.2":return 0;case"2.0.0":return 1;case"2.1.0":case"2.1.1":return 2;case"2.1.2":return 3;case"2.1.3":case"2.1.4":case"2.2.7":return 4;case"3.0.1":case"3.0.2":case"3.0.3":case"3.0":return 5;case"3.1.0":case"3.1.1":case"3.1.2":case"3.1":default:return 6}}function v(){if(a.fn.emojioneArea&&a.fn.emojioneArea.defaults)return a.fn.emojioneArea.defaults;var b={attributes:{dir:"ltr",spellcheck:!1,autocomplete:"off",autocorrect:"off",autocapitalize:"off"},search:!0,placeholder:null,emojiPlaceholder:":smiley:",searchPlaceholder:"SEARCH",container:null,hideSource:!0,shortnames:!0,sprite:!0,pickerPosition:"top",filtersPosition:"top",searchPosition:"top",hidePickerOnBlur:!0,buttonTitle:"Use the TAB key to insert emoji faster",tones:!0,tonesStyle:"bullet",inline:null,saveEmojisAs:"unicode",shortcuts:!0,autocomplete:!0,autocompleteTones:!1,standalone:!1,useInternalCDN:!0,imageType:"png",recentEmojis:!0,textcomplete:{maxCount:15,placement:null}},c=u(e?t(e):r());return c>4?b.filters={tones:{title:"Diversity",emoji:"open_hands raised_hands palms_up_together clap pray thumbsup thumbsdown punch fist left_facing_fist right_facing_fist fingers_crossed v metal love_you_gesture ok_hand point_left point_right point_up_2 point_down point_up raised_hand raised_back_of_hand hand_splayed vulcan wave call_me muscle middle_finger writing_hand selfie nail_care ear nose baby boy girl man woman blond-haired_woman blond-haired_man older_man older_woman man_with_chinese_cap woman_wearing_turban man_wearing_turban woman_police_officer man_police_officer woman_construction_worker man_construction_worker woman_guard man_guard woman_detective man_detective woman_health_worker man_health_worker woman_farmer man_farmer woman_cook man_cook woman_student man_student woman_singer man_singer woman_teacher man_teacher woman_factory_worker man_factory_worker woman_technologist man_technologist woman_office_worker man_office_worker woman_mechanic man_mechanic woman_scientist man_scientist woman_artist man_artist woman_firefighter man_firefighter woman_pilot man_pilot woman_astronaut man_astronaut woman_judge man_judge mrs_claus santa princess prince bride_with_veil man_in_tuxedo angel pregnant_woman breast_feeding woman_bowing man_bowing man_tipping_hand woman_tipping_hand man_gesturing_no woman_gesturing_no man_gesturing_ok woman_gesturing_ok man_raising_hand woman_raising_hand woman_facepalming man_facepalming woman_shrugging man_shrugging man_pouting woman_pouting man_frowning woman_frowning man_getting_haircut woman_getting_haircut man_getting_face_massage woman_getting_face_massage man_in_business_suit_levitating dancer man_dancing woman_walking man_walking woman_running man_running adult child older_adult bearded_person woman_with_headscarf woman_mage man_mage woman_fairy man_fairy woman_vampire man_vampire mermaid merman woman_elf man_elf snowboarder woman_lifting_weights man_lifting_weights woman_cartwheeling man_cartwheeling woman_bouncing_ball man_bouncing_ball woman_playing_handball man_playing_handball woman_golfing man_golfing woman_surfing man_surfing woman_swimming man_swimming woman_playing_water_polo man_playing_water_polo woman_rowing_boat man_rowing_boat horse_racing woman_biking man_biking woman_mountain_biking man_mountain_biking woman_juggling man_juggling woman_in_steamy_room man_in_steamy_room woman_climbing man_climbing woman_in_lotus_position man_in_lotus_position bath person_in_bed"},recent:{icon:"clock3",title:"Recent",emoji:""},smileys_people:{icon:"yum",title:"Smileys & People",emoji:"grinning smiley smile grin laughing sweat_smile joy rofl relaxed blush innocent slight_smile upside_down wink relieved crazy_face star_struck heart_eyes kissing_heart kissing kissing_smiling_eyes kissing_closed_eyes yum stuck_out_tongue_winking_eye stuck_out_tongue_closed_eyes stuck_out_tongue money_mouth hugging nerd sunglasses cowboy smirk unamused disappointed pensive worried face_with_raised_eyebrow face_with_monocle confused slight_frown frowning2 persevere confounded tired_face weary triumph angry rage face_with_symbols_over_mouth no_mouth neutral_face expressionless hushed frowning anguished open_mouth astonished dizzy_face exploding_head flushed scream fearful cold_sweat cry disappointed_relieved drooling_face sob sweat sleepy sleeping rolling_eyes thinking shushing_face face_with_hand_over_mouth lying_face grimacing zipper_mouth face_vomiting nauseated_face sneezing_face mask thermometer_face head_bandage smiling_imp imp japanese_ogre japanese_goblin poop ghost skull skull_crossbones alien space_invader robot jack_o_lantern clown smiley_cat smile_cat joy_cat heart_eyes_cat smirk_cat kissing_cat scream_cat crying_cat_face pouting_cat open_hands raised_hands palms_up_together clap pray handshake thumbsup thumbsdown punch fist left_facing_fist right_facing_fist fingers_crossed v metal love_you_gesture ok_hand point_left point_right point_up_2 point_down point_up raised_hand raised_back_of_hand hand_splayed vulcan wave call_me muscle middle_finger writing_hand selfie nail_care ring lipstick kiss lips tongue ear nose footprints eye eyes speaking_head bust_in_silhouette busts_in_silhouette baby boy girl man woman blond-haired_woman blond_haired_man older_man older_woman man_with_chinese_cap woman_wearing_turban man_wearing_turban woman_police_officer police_officer woman_construction_worker construction_worker woman_guard guard woman_detective detective woman_health_worker man_health_worker woman_farmer man_farmer woman_cook man_cook woman_student man_student woman_singer man_singer woman_teacher man_teacher woman_factory_worker man_factory_worker woman_technologist man_technologist woman_office_worker man_office_worker woman_mechanic man_mechanic woman_scientist man_scientist woman_artist man_artist woman_firefighter man_firefighter woman_pilot man_pilot woman_astronaut man_astronaut woman_judge man_judge mrs_claus santa princess prince bride_with_veil man_in_tuxedo angel pregnant_woman breast_feeding woman_bowing man_bowing woman_tipping_hand man_tipping_hand woman_gesturing_no man_gesturing_no woman_gesturing_ok man_gesturing_ok woman_raising_hand man_raising_hand woman_facepalming man_facepalming woman_shrugging man_shrugging woman_pouting man_pouting woman_frowning man_frowning woman_getting_haircut man_getting_haircut woman_getting_face_massage man_getting_face_massage man_in_business_suit_levitating dancer man_dancing women_with_bunny_ears_partying men_with_bunny_ears_partying woman_walking man_walking woman_running man_running couple two_women_holding_hands two_men_holding_hands couple_with_heart couple_ww couple_mm couplekiss kiss_ww kiss_mm family family_mwg family_mwgb family_mwbb family_mwgg family_wwb family_wwg family_wwgb family_wwbb family_wwgg family_mmb family_mmg family_mmgb family_mmbb family_mmgg family_woman_boy family_woman_girl family_woman_girl_boy family_woman_boy_boy family_woman_girl_girl family_man_boy family_man_girl family_man_girl_boy family_man_boy_boy family_man_girl_girl bearded_person woman_with_headscarf woman_mage man_mage woman_fairy man_fairy woman_vampire man_vampire mermaid merman woman_elf man_elf woman_genie man_genie woman_zombie man_zombie womans_clothes shirt jeans necktie dress bikini kimono high_heel sandal boot mans_shoe athletic_shoe womans_hat tophat mortar_board crown helmet_with_cross school_satchel pouch purse handbag briefcase eyeglasses dark_sunglasses closed_umbrella umbrella2 brain billed_cap scarf gloves coat socks "},animals_nature:{icon:"hamster",title:"Animals & Nature",emoji:"dog cat mouse hamster rabbit fox bear panda_face koala tiger lion_face cow pig pig_nose frog monkey_face see_no_evil hear_no_evil speak_no_evil monkey chicken penguin bird baby_chick hatching_chick hatched_chick duck eagle owl bat wolf boar horse unicorn bee bug butterfly snail shell beetle ant spider spider_web turtle snake lizard scorpion crab squid octopus shrimp tropical_fish fish blowfish dolphin shark whale whale2 crocodile leopard tiger2 water_buffalo ox cow2 deer dromedary_camel camel elephant rhino gorilla racehorse pig2 goat ram sheep dog2 poodle cat2 rooster turkey dove rabbit2 mouse2 rat chipmunk dragon giraffe zebra hedgehog sauropod t_rex cricket dragon_face feet cactus christmas_tree evergreen_tree deciduous_tree palm_tree seedling herb shamrock four_leaf_clover bamboo tanabata_tree leaves fallen_leaf maple_leaf mushroom ear_of_rice bouquet tulip rose wilted_rose sunflower blossom cherry_blossom hibiscus earth_americas earth_africa earth_asia full_moon waning_gibbous_moon last_quarter_moon waning_crescent_moon new_moon waxing_crescent_moon first_quarter_moon waxing_gibbous_moon new_moon_with_face full_moon_with_face sun_with_face first_quarter_moon_with_face last_quarter_moon_with_face crescent_moon dizzy star star2 sparkles zap fire boom comet sunny white_sun_small_cloud partly_sunny white_sun_cloud white_sun_rain_cloud rainbow cloud cloud_rain thunder_cloud_rain cloud_lightning cloud_snow snowman2 snowman snowflake wind_blowing_face dash cloud_tornado fog ocean droplet sweat_drops umbrella "},food_drink:{icon:"pizza",title:"Food & Drink",emoji:"green_apple apple pear tangerine lemon banana watermelon grapes strawberry melon cherries peach pineapple kiwi avocado tomato eggplant cucumber carrot corn hot_pepper potato sweet_potato chestnut peanuts honey_pot croissant bread french_bread cheese egg cooking bacon pancakes fried_shrimp poultry_leg meat_on_bone pizza hotdog hamburger fries stuffed_flatbread taco burrito salad shallow_pan_of_food spaghetti ramen stew fish_cake sushi bento curry rice_ball rice rice_cracker oden dango shaved_ice ice_cream icecream cake birthday custard lollipop candy chocolate_bar popcorn doughnut cookie milk baby_bottle coffee tea sake beer beers champagne_glass wine_glass tumbler_glass cocktail tropical_drink champagne spoon fork_and_knife fork_knife_plate dumpling fortune_cookie takeout_box chopsticks bowl_with_spoon cup_with_straw coconut broccoli pie pretzel cut_of_meat sandwich canned_food"},activity:{icon:"basketball",title:"Activity",emoji:"soccer basketball football baseball tennis volleyball rugby_football 8ball ping_pong badminton goal hockey field_hockey cricket_game golf bow_and_arrow fishing_pole_and_fish boxing_glove martial_arts_uniform ice_skate ski skier snowboarder woman_lifting_weights man_lifting_weights person_fencing women_wrestling men_wrestling woman_cartwheeling man_cartwheeling woman_bouncing_ball man_bouncing_ball woman_playing_handball man_playing_handball woman_golfing man_golfing woman_surfing man_surfing woman_swimming man_swimming woman_playing_water_polo man_playing_water_polo woman_rowing_boat man_rowing_boat horse_racing woman_biking man_biking woman_mountain_biking man_mountain_biking woman_in_steamy_room man_in_steamy_room woman_climbing man_climbing woman_in_lotus_position man_in_lotus_position running_shirt_with_sash medal military_medal first_place second_place third_place trophy rosette reminder_ribbon ticket tickets circus_tent woman_juggling man_juggling performing_arts art clapper microphone headphones musical_score musical_keyboard drum saxophone trumpet guitar violin game_die dart bowling video_game slot_machine sled curling_stone "},travel_places:{icon:"rocket",title:"Travel & Places",emoji:"red_car taxi blue_car bus trolleybus race_car police_car ambulance fire_engine minibus truck articulated_lorry tractor scooter bike motor_scooter motorcycle rotating_light oncoming_police_car oncoming_bus oncoming_automobile oncoming_taxi aerial_tramway mountain_cableway suspension_railway railway_car train mountain_railway monorail bullettrain_side bullettrain_front light_rail steam_locomotive train2 metro tram station helicopter airplane_small airplane airplane_departure airplane_arriving rocket satellite_orbital seat canoe sailboat motorboat speedboat cruise_ship ferry ship anchor construction fuelpump busstop vertical_traffic_light traffic_light map moyai statue_of_liberty fountain tokyo_tower european_castle japanese_castle stadium ferris_wheel roller_coaster carousel_horse beach_umbrella beach island mountain mountain_snow mount_fuji volcano desert camping tent railway_track motorway construction_site factory house house_with_garden homes house_abandoned office department_store post_office european_post_office hospital bank hotel convenience_store school love_hotel wedding classical_building church mosque synagogue kaaba shinto_shrine japan rice_scene park sunrise sunrise_over_mountains stars sparkler fireworks city_sunset city_dusk cityscape night_with_stars milky_way bridge_at_night foggy flying_saucer"},objects:{icon:"bulb",title:"Objects",emoji:"watch iphone calling computer keyboard desktop printer mouse_three_button trackball joystick compression minidisc floppy_disk cd dvd vhs camera camera_with_flash video_camera movie_camera projector film_frames telephone_receiver telephone pager fax tv radio microphone2 level_slider control_knobs stopwatch timer alarm_clock clock hourglass hourglass_flowing_sand satellite battery electric_plug bulb flashlight candle wastebasket oil money_with_wings dollar yen euro pound moneybag credit_card gem scales wrench hammer hammer_pick tools pick nut_and_bolt gear chains gun bomb knife dagger crossed_swords shield smoking coffin urn amphora crystal_ball prayer_beads barber alembic telescope microscope hole pill syringe thermometer toilet potable_water shower bathtub bath bellhop key key2 door couch bed sleeping_accommodation frame_photo shopping_bags shopping_cart gift balloon flags ribbon confetti_ball tada dolls izakaya_lantern wind_chime envelope envelope_with_arrow incoming_envelope e-mail love_letter inbox_tray outbox_tray package label mailbox_closed mailbox mailbox_with_mail mailbox_with_no_mail postbox postal_horn scroll page_with_curl page_facing_up bookmark_tabs bar_chart chart_with_upwards_trend chart_with_downwards_trend notepad_spiral calendar_spiral calendar date card_index card_box ballot_box file_cabinet clipboard file_folder open_file_folder dividers newspaper2 newspaper notebook notebook_with_decorative_cover ledger closed_book green_book blue_book orange_book books book bookmark link paperclip paperclips triangular_ruler straight_ruler pushpin round_pushpin scissors pen_ballpoint pen_fountain black_nib paintbrush crayon pencil pencil2 mag mag_right lock_with_ink_pen closed_lock_with_key lock unlock"},symbols:{icon:"heartpulse",title:"Symbols",emoji:"heart orange_heart yellow_heart green_heart blue_heart purple_heart black_heart broken_heart heart_exclamation two_hearts revolving_hearts heartbeat heartpulse sparkling_heart cupid gift_heart heart_decoration peace cross star_and_crescent om_symbol wheel_of_dharma star_of_david six_pointed_star menorah yin_yang orthodox_cross place_of_worship ophiuchus aries taurus gemini cancer leo virgo libra scorpius sagittarius capricorn aquarius pisces id atom accept radioactive biohazard mobile_phone_off vibration_mode u6709 u7121 u7533 u55b6 u6708 eight_pointed_black_star vs white_flower ideograph_advantage secret congratulations u5408 u6e80 u5272 u7981 a b ab cl o2 sos x o octagonal_sign no_entry name_badge no_entry_sign 100 anger hotsprings no_pedestrians do_not_litter no_bicycles non-potable_water underage no_mobile_phones no_smoking exclamation grey_exclamation question grey_question bangbang interrobang low_brightness high_brightness part_alternation_mark warning children_crossing trident fleur-de-lis beginner recycle white_check_mark u6307 chart sparkle eight_spoked_asterisk negative_squared_cross_mark globe_with_meridians diamond_shape_with_a_dot_inside m cyclone zzz atm wc wheelchair parking u7a7a sa passport_control customs baggage_claim left_luggage mens womens baby_symbol restroom put_litter_in_its_place cinema signal_strength koko symbols information_source abc abcd capital_abcd ng ok up cool new free zero one two three four five six seven eight nine keycap_ten 1234 hash asterisk arrow_forward pause_button play_pause stop_button record_button eject track_next track_previous fast_forward rewind arrow_double_up arrow_double_down arrow_backward arrow_up_small arrow_down_small arrow_right arrow_left arrow_up arrow_down arrow_upper_right arrow_lower_right arrow_lower_left arrow_upper_left arrow_up_down left_right_arrow arrow_right_hook leftwards_arrow_with_hook arrow_heading_up arrow_heading_down twisted_rightwards_arrows repeat repeat_one arrows_counterclockwise arrows_clockwise musical_note notes heavy_plus_sign heavy_minus_sign heavy_division_sign heavy_multiplication_x heavy_dollar_sign currency_exchange tm copyright registered wavy_dash curly_loop loop end back on top soon heavy_check_mark ballot_box_with_check radio_button white_circle black_circle red_circle blue_circle small_red_triangle small_red_triangle_down small_orange_diamond small_blue_diamond large_orange_diamond large_blue_diamond white_square_button black_square_button black_small_square white_small_square black_medium_small_square white_medium_small_square black_medium_square white_medium_square black_large_square white_large_square speaker mute sound loud_sound bell no_bell mega loudspeaker speech_left eye_in_speech_bubble speech_balloon thought_balloon anger_right spades clubs hearts diamonds black_joker flower_playing_cards mahjong clock1 clock2 clock3 clock4 clock5 clock6 clock7 clock8 clock9 clock10 clock11 clock12 clock130 clock230 clock330 clock430 clock530 clock630 clock730 clock830 clock930 clock1030 clock1130 clock1230"},flags:{icon:"flag_gb",title:"Flags",emoji:"flag_white flag_black checkered_flag triangular_flag_on_post rainbow_flag flag_af flag_ax flag_al flag_dz flag_as flag_ad flag_ao flag_ai flag_aq flag_ag flag_ar flag_am flag_aw flag_au flag_at flag_az flag_bs flag_bh flag_bd flag_bb flag_by flag_be flag_bz flag_bj flag_bm flag_bt flag_bo flag_ba flag_bw flag_br flag_io flag_vg flag_bn flag_bg flag_bf flag_bi flag_kh flag_cm flag_ca flag_ic flag_cv flag_bq flag_ky flag_cf flag_td flag_cl flag_cn flag_cx flag_cc flag_co flag_km flag_cg flag_cd flag_ck flag_cr flag_ci flag_hr flag_cu flag_cw flag_cy flag_cz flag_dk flag_dj flag_dm flag_do flag_ec flag_eg flag_sv flag_gq flag_er flag_ee flag_et flag_eu flag_fk flag_fo flag_fj flag_fi flag_fr flag_gf flag_pf flag_tf flag_ga flag_gm flag_ge flag_de flag_gh flag_gi flag_gr flag_gl flag_gd flag_gp flag_gu flag_gt flag_gg flag_gn flag_gw flag_gy flag_ht flag_hn flag_hk flag_hu flag_is flag_in flag_id flag_ir flag_iq flag_ie flag_im flag_il flag_it flag_jm flag_jp crossed_flags flag_je flag_jo flag_kz flag_ke flag_ki flag_xk flag_kw flag_kg flag_la flag_lv flag_lb flag_ls flag_lr flag_ly flag_li flag_lt flag_lu flag_mo flag_mk flag_mg flag_mw flag_my flag_mv flag_ml flag_mt flag_mh flag_mq flag_mr flag_mu flag_yt flag_mx flag_fm flag_md flag_mc flag_mn flag_me flag_ms flag_ma flag_mz flag_mm flag_na flag_nr flag_np flag_nl flag_nc flag_nz flag_ni flag_ne flag_ng flag_nu flag_nf flag_kp flag_mp flag_no flag_om flag_pk flag_pw flag_ps flag_pa flag_pg flag_py flag_pe flag_ph flag_pn flag_pl flag_pt flag_pr flag_qa flag_re flag_ro flag_ru flag_rw flag_ws flag_sm flag_st flag_sa flag_sn flag_rs flag_sc flag_sl flag_sg flag_sx flag_sk flag_si flag_gs flag_sb flag_so flag_za flag_kr flag_ss flag_es flag_lk flag_bl flag_sh flag_kn flag_lc flag_pm flag_vc flag_sd flag_sr flag_sz flag_se flag_ch flag_sy flag_tw flag_tj flag_tz flag_th flag_tl flag_tg flag_tk flag_to flag_tt flag_tn flag_tr flag_tm flag_tc flag_tv flag_vi flag_ug flag_ua flag_ae flag_gb flag_us flag_uy flag_uz flag_vu flag_va flag_ve flag_vn flag_wf flag_eh flag_ye flag_zm flag_zw flag_ac flag_ta flag_bv flag_hm flag_sj flag_um flag_ea flag_cp flag_dg flag_mf united_nations england scotland wales"}}:b.filters={tones:{title:"Diversity",emoji:"santa runner surfer swimmer lifter ear nose point_up_2 point_down point_left point_right punch wave ok_hand thumbsup thumbsdown clap open_hands boy girl man woman cop bride_with_veil person_with_blond_hair man_with_gua_pi_mao man_with_turban older_man grandma baby construction_worker princess angel information_desk_person guardsman dancer nail_care massage haircut muscle spy hand_splayed middle_finger vulcan no_good ok_woman bow raising_hand raised_hands person_frowning person_with_pouting_face pray rowboat bicyclist mountain_bicyclist walking bath metal point_up basketball_player fist raised_hand v writing_hand"},recent:{icon:"clock3",title:"Recent",emoji:""},smileys_people:{icon:"yum",title:"Smileys & People",emoji:"grinning grimacing grin joy smiley smile sweat_smile laughing innocent wink blush slight_smile upside_down relaxed yum relieved heart_eyes kissing_heart kissing kissing_smiling_eyes kissing_closed_eyes stuck_out_tongue_winking_eye stuck_out_tongue_closed_eyes stuck_out_tongue money_mouth nerd sunglasses hugging smirk no_mouth neutral_face expressionless unamused rolling_eyes thinking flushed disappointed worried angry rage pensive confused slight_frown frowning2 persevere confounded tired_face weary triumph open_mouth scream fearful cold_sweat hushed frowning anguished cry disappointed_relieved sleepy sweat sob dizzy_face astonished zipper_mouth mask thermometer_face head_bandage sleeping zzz poop smiling_imp imp japanese_ogre japanese_goblin skull ghost alien robot smiley_cat smile_cat joy_cat heart_eyes_cat smirk_cat kissing_cat scream_cat crying_cat_face pouting_cat raised_hands clap wave thumbsup thumbsdown punch fist v ok_hand raised_hand open_hands muscle pray point_up point_up_2 point_down point_left point_right middle_finger hand_splayed metal vulcan writing_hand nail_care lips tongue ear nose eye eyes bust_in_silhouette busts_in_silhouette speaking_head baby boy girl man woman person_with_blond_hair older_man older_woman man_with_gua_pi_mao man_with_turban cop construction_worker guardsman spy santa angel princess bride_with_veil walking runner dancer dancers couple two_men_holding_hands two_women_holding_hands bow information_desk_person no_good ok_woman raising_hand person_with_pouting_face person_frowning haircut massage couple_with_heart couple_ww couple_mm couplekiss kiss_ww kiss_mm family family_mwg family_mwgb family_mwbb family_mwgg family_wwb family_wwg family_wwgb family_wwbb family_wwgg family_mmb family_mmg family_mmgb family_mmbb family_mmgg womans_clothes shirt jeans necktie dress bikini kimono lipstick kiss footprints high_heel sandal boot mans_shoe athletic_shoe womans_hat tophat helmet_with_cross mortar_board crown school_satchel pouch purse handbag briefcase eyeglasses dark_sunglasses ring closed_umbrella"},animals_nature:{icon:"hamster",title:"Animals & Nature",emoji:"dog cat mouse hamster rabbit bear panda_face koala tiger lion_face cow pig pig_nose frog octopus monkey_face see_no_evil hear_no_evil speak_no_evil monkey chicken penguin bird baby_chick hatching_chick hatched_chick wolf boar horse unicorn bee bug snail beetle ant spider scorpion crab snake turtle tropical_fish fish blowfish dolphin whale whale2 crocodile leopard tiger2 water_buffalo ox cow2 dromedary_camel camel elephant goat ram sheep racehorse pig2 rat mouse2 rooster turkey dove dog2 poodle cat2 rabbit2 chipmunk feet dragon dragon_face cactus christmas_tree evergreen_tree deciduous_tree palm_tree seedling herb shamrock four_leaf_clover bamboo tanabata_tree leaves fallen_leaf maple_leaf ear_of_rice hibiscus sunflower rose tulip blossom cherry_blossom bouquet mushroom chestnut jack_o_lantern shell spider_web earth_americas earth_africa earth_asia full_moon waning_gibbous_moon last_quarter_moon waning_crescent_moon new_moon waxing_crescent_moon first_quarter_moon waxing_gibbous_moon new_moon_with_face full_moon_with_face first_quarter_moon_with_face last_quarter_moon_with_face sun_with_face crescent_moon star star2 dizzy sparkles comet sunny white_sun_small_cloud partly_sunny white_sun_cloud white_sun_rain_cloud cloud cloud_rain thunder_cloud_rain cloud_lightning zap fire boom snowflake cloud_snow snowman2 snowman wind_blowing_face dash cloud_tornado fog umbrella2 umbrella droplet sweat_drops ocean"},food_drink:{icon:"pizza",title:"Food & Drink",emoji:"green_apple apple pear tangerine lemon banana watermelon grapes strawberry melon cherries peach pineapple tomato eggplant hot_pepper corn sweet_potato honey_pot bread cheese poultry_leg meat_on_bone fried_shrimp egg hamburger fries hotdog pizza spaghetti taco burrito ramen stew fish_cake sushi bento curry rice_ball rice rice_cracker oden dango shaved_ice ice_cream icecream cake birthday custard candy lollipop chocolate_bar popcorn doughnut cookie beer beers wine_glass cocktail tropical_drink champagne sake tea coffee baby_bottle fork_and_knife fork_knife_plate"},activity:{icon:"basketball",title:"Activity",emoji:"soccer basketball football baseball tennis volleyball rugby_football 8ball golf golfer ping_pong badminton hockey field_hockey cricket ski skier snowboarder ice_skate bow_and_arrow fishing_pole_and_fish rowboat swimmer surfer bath basketball_player lifter bicyclist mountain_bicyclist horse_racing levitate trophy running_shirt_with_sash medal military_medal reminder_ribbon rosette ticket tickets performing_arts art circus_tent microphone headphones musical_score musical_keyboard saxophone trumpet guitar violin clapper video_game space_invader dart game_die slot_machine bowling"},travel_places:{icon:"rocket",title:"Travel & Places",emoji:"red_car taxi blue_car bus trolleybus race_car police_car ambulance fire_engine minibus truck articulated_lorry tractor motorcycle bike rotating_light oncoming_police_car oncoming_bus oncoming_automobile oncoming_taxi aerial_tramway mountain_cableway suspension_railway railway_car train monorail bullettrain_side bullettrain_front light_rail mountain_railway steam_locomotive train2 metro tram station helicopter airplane_small airplane airplane_departure airplane_arriving sailboat motorboat speedboat ferry cruise_ship rocket satellite_orbital seat anchor construction fuelpump busstop vertical_traffic_light traffic_light checkered_flag ship ferris_wheel roller_coaster carousel_horse construction_site foggy tokyo_tower factory fountain rice_scene mountain mountain_snow mount_fuji volcano japan camping tent park motorway railway_track sunrise sunrise_over_mountains desert beach island city_sunset city_dusk cityscape night_with_stars bridge_at_night milky_way stars sparkler fireworks rainbow homes european_castle japanese_castle stadium statue_of_liberty house house_with_garden house_abandoned office department_store post_office european_post_office hospital bank hotel convenience_store school love_hotel wedding classical_building church mosque synagogue kaaba shinto_shrine"},objects:{icon:"bulb",title:"Objects",emoji:"watch iphone calling computer keyboard desktop printer mouse_three_button trackball joystick compression minidisc floppy_disk cd dvd vhs camera camera_with_flash video_camera movie_camera projector film_frames telephone_receiver telephone pager fax tv radio microphone2 level_slider control_knobs stopwatch timer alarm_clock clock hourglass_flowing_sand hourglass satellite battery electric_plug bulb flashlight candle wastebasket oil money_with_wings dollar yen euro pound moneybag credit_card gem scales wrench hammer hammer_pick tools pick nut_and_bolt gear chains gun bomb knife dagger crossed_swords shield smoking skull_crossbones coffin urn amphora crystal_ball prayer_beads barber alembic telescope microscope hole pill syringe thermometer label bookmark toilet shower bathtub key key2 couch sleeping_accommodation bed door bellhop frame_photo map beach_umbrella moyai shopping_bags balloon flags ribbon gift confetti_ball tada dolls wind_chime crossed_flags izakaya_lantern envelope envelope_with_arrow incoming_envelope e-mail love_letter postbox mailbox_closed mailbox mailbox_with_mail mailbox_with_no_mail package postal_horn inbox_tray outbox_tray scroll page_with_curl bookmark_tabs bar_chart chart_with_upwards_trend chart_with_downwards_trend page_facing_up date calendar calendar_spiral card_index card_box ballot_box file_cabinet clipboard notepad_spiral file_folder open_file_folder dividers newspaper2 newspaper notebook closed_book green_book blue_book orange_book notebook_with_decorative_cover ledger books book link paperclip paperclips scissors triangular_ruler straight_ruler pushpin round_pushpin triangular_flag_on_post flag_white flag_black closed_lock_with_key lock unlock lock_with_ink_pen pen_ballpoint pen_fountain black_nib pencil pencil2 crayon paintbrush mag mag_right"},symbols:{icon:"heartpulse",title:"Symbols",emoji:"heart yellow_heart green_heart blue_heart purple_heart broken_heart heart_exclamation two_hearts revolving_hearts heartbeat heartpulse sparkling_heart cupid gift_heart heart_decoration peace cross star_and_crescent om_symbol wheel_of_dharma star_of_david six_pointed_star menorah yin_yang orthodox_cross place_of_worship ophiuchus aries taurus gemini cancer leo virgo libra scorpius sagittarius capricorn aquarius pisces id atom u7a7a u5272 radioactive biohazard mobile_phone_off vibration_mode u6709 u7121 u7533 u55b6 u6708 eight_pointed_black_star vs accept white_flower ideograph_advantage secret congratulations u5408 u6e80 u7981 a b ab cl o2 sos no_entry name_badge no_entry_sign x o anger hotsprings no_pedestrians do_not_litter no_bicycles non-potable_water underage no_mobile_phones exclamation grey_exclamation question grey_question bangbang interrobang 100 low_brightness high_brightness trident fleur-de-lis part_alternation_mark warning children_crossing beginner recycle u6307 chart sparkle eight_spoked_asterisk negative_squared_cross_mark white_check_mark diamond_shape_with_a_dot_inside cyclone loop globe_with_meridians m atm sa passport_control customs baggage_claim left_luggage wheelchair no_smoking wc parking potable_water mens womens baby_symbol restroom put_litter_in_its_place cinema signal_strength koko ng ok up cool new free zero one two three four five six seven eight nine ten 1234 arrow_forward pause_button play_pause stop_button record_button track_next track_previous fast_forward rewind twisted_rightwards_arrows repeat repeat_one arrow_backward arrow_up_small arrow_down_small arrow_double_up arrow_double_down arrow_right arrow_left arrow_up arrow_down arrow_upper_right arrow_lower_right arrow_lower_left arrow_upper_left arrow_up_down left_right_arrow arrows_counterclockwise arrow_right_hook leftwards_arrow_with_hook arrow_heading_up arrow_heading_down hash asterisk information_source abc abcd capital_abcd symbols musical_note notes wavy_dash curly_loop heavy_check_mark arrows_clockwise heavy_plus_sign heavy_minus_sign heavy_division_sign heavy_multiplication_x heavy_dollar_sign currency_exchange copyright registered tm end back on top soon ballot_box_with_check radio_button white_circle black_circle red_circle large_blue_circle small_orange_diamond small_blue_diamond large_orange_diamond large_blue_diamond small_red_triangle black_small_square white_small_square black_large_square white_large_square small_red_triangle_down black_medium_square white_medium_square black_medium_small_square white_medium_small_square black_square_button white_square_button speaker sound loud_sound mute mega loudspeaker bell no_bell black_joker mahjong spades clubs hearts diamonds flower_playing_cards thought_balloon anger_right speech_balloon clock1 clock2 clock3 clock4 clock5 clock6 clock7 clock8 clock9 clock10 clock11 clock12 clock130 clock230 clock330 clock430 clock530 clock630 clock730 clock830 clock930 clock1030 clock1130 clock1230 eye_in_speech_bubble" +},flags:{icon:"flag_gb",title:"Flags",emoji:"ac af al dz ad ao ai ag ar am aw au at az bs bh bd bb by be bz bj bm bt bo ba bw br bn bg bf bi cv kh cm ca ky cf td flag_cl cn co km cg flag_cd cr hr cu cy cz dk dj dm do ec eg sv gq er ee et fk fo fj fi fr pf ga gm ge de gh gi gr gl gd gu gt gn gw gy ht hn hk hu is in flag_id ir iq ie il it ci jm jp je jo kz ke ki xk kw kg la lv lb ls lr ly li lt lu mo mk mg mw my mv ml mt mh mr mu mx fm md mc mn me ms ma mz mm na nr np nl nc nz ni ne flag_ng nu kp no om pk pw ps pa pg py pe ph pl pt pr qa ro ru rw sh kn lc vc ws sm st flag_sa sn rs sc sl sg sk si sb so za kr es lk sd sr sz se ch sy tw tj tz th tl tg to tt tn tr flag_tm flag_tm ug ua ae gb us vi uy uz vu va ve vn wf eh ye zm zw re ax ta io bq cx cc gg im yt nf pn bl pm gs tk bv hm sj um ic ea cp dg as aq vg ck cw eu gf tf gp mq mp sx ss tc "}},b}function w(b){var c=v();if(b&&b.filters){var d=c.filters;a.each(b.filters,function(b,c){return!s(c)||a.isEmptyObject(c)?void delete d[b]:void a.each(c,function(a,c){d[b][a]=c})}),b.filters=d}return a.extend({},c,b)}var x,y;window.getSelection&&document.createRange?(x=function(a){var b=window.getSelection&&window.getSelection();if(b&&b.rangeCount>0)return b.getRangeAt(0)},y=function(a,b){var c=document.createRange();c.setStart(b.startContainer,b.startOffset),c.setEnd(b.endContainer,b.endOffset),b=window.getSelection(),b.removeAllRanges(),b.addRange(c)}):document.selection&&document.body.createTextRange&&(x=function(a){return document.selection.createRange()},y=function(a,b){var c=document.body.createTextRange();c.moveToElementText(a),c.setStart(b.startContanier,b.startOffset),c.setEnd(b.endContainer,b.endOffset),c.select()});var z;function A(a,b){return a.replace(z,function(a){var c=e[0===k?"jsecapeMap":"jsEscapeMap"];return"undefined"!=typeof a&&a in c?o(b,c[a]):a})}function B(a,b){return a=a.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'").replace(/`/g,"`").replace(/(?:\r\n|\r|\n)/g,"\n").replace(/(\n+)/g,"
$1
").replace(/\n/g,"
").replace(/<\/div>/g,""),b.shortnames&&(a=e.shortnameToUnicode(a)),A(a,b.emojiTemplate).replace(/\t/g,"    ").replace(/ /g,"  ")}function C(a,b){switch(a=a.replace(/ /g,"\n").replace(/ /g,"\t").replace(/]*alt="([^"]+)"[^>]*>/gi,"$1").replace(/\n|\r/g,"").replace(/]*>/gi,"\n").replace(/(?:<(?:div|p|ol|ul|li|pre|code|object)[^>]*>)+/gi,"
").replace(/(?:<\/(?:div|p|ol|ul|li|pre|code|object)>)+/gi,"
").replace(/\n
<\/div>/gi,"\n").replace(/
<\/div>\n/gi,"\n").replace(/(?:
)+<\/div>/gi,"\n").replace(/([^\n])<\/div>
/gi,"$1\n").replace(/(?:<\/div>)+/gi,"
").replace(/([^\n])<\/div>([^\n])/gi,"$1\n$2").replace(/<\/div>/gi,"").replace(/([^\n])
/gi,"$1\n").replace(/\n
/gi,"\n").replace(/
\n/gi,"\n\n").replace(/<(?:[^>]+)?>/g,"").replace(new RegExp(l,"g"),"").replace(/ /g," ").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/`/g,"`").replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&"),b.saveEmojisAs){case"image":a=A(a,b.emojiTemplate);break;case"shortname":a=e.toShort(a)}return a}function D(){var a=this,b=a.editor[0].offsetWidth-a.editor[0].clientWidth,c=parseInt(a.button.css("marginRight"));c!==b&&(a.button.css({marginRight:b}),a.floatingPicker&&a.picker.css({right:parseInt(a.picker.css("right"))-c+b}))}function E(){var b=this;if(!b.sprite&&b.lasyEmoji[0]&&b.lasyEmoji.eq(0).is(".lazy-emoji")){var c=b.picker.offset().top,d=c+b.picker.height()+20;b.lasyEmoji.each(function(){var b=a(this),e=b.offset().top;if(e>c&&ed)return!1}),b.lasyEmoji=b.lasyEmoji.filter(".lazy-emoji")}}function F(a,b){return(b?"":".")+j+(a?"-"+a:"")}function G(b){var c=a("
",s(b)?b:{"class":F(b,!0)});return a.each(i.call(arguments).slice(1),function(b,d){a.isFunction(d)&&(d=d.call(c)),d&&a(d).appendTo(c)}),c}function H(){return localStorage.getItem("recent_emojis")||""}function I(b,c){var d=H();if(!b.recent||b.recent!==d||c){if(d.length){var e=b.scrollArea.is(".skinnable"),f,g;e||(f=b.scrollArea.scrollTop(),c&&b.recentCategory.show(),g=b.recentCategory.is(":visible")?b.recentCategory.height():0);var h=p(d,b.emojiBtnTemplate,!0).split("|").join("");if(b.recentCategory.children(".emojibtn").remove(),a(h).insertAfter(b.recentCategory.children(".emojionearea-category-title")),b.recentCategory.children(".emojibtn").on("click",function(){b.trigger("emojibtn.click",a(this))}),b.recentFilter.show(),!e){b.recentCategory.show();var i=b.recentCategory.height();g!==i&&b.scrollArea.scrollTop(f+i-g)}}else b.recentFilter.hasClass("active")&&b.recentFilter.removeClass("active").next().addClass("active"),b.recentCategory.hide(),b.recentFilter.hide();b.recent=d}}function J(a,b){var c=H(),d=c.split("|"),e=d.indexOf(b);e!==-1&&d.splice(e,1),d.unshift(b),d.length>9&&d.pop(),localStorage.setItem("recent_emojis",d.join("|")),I(a)}function K(){var a="test";try{return localStorage.setItem(a,a),localStorage.removeItem(a),!0}catch(b){return!1}}function L(b,c,d){b.options=d=w(d),b.sprite=d.sprite&&k<3,b.inline=null===d.inline?c.is("INPUT"):d.inline,b.shortnames=d.shortnames,b.saveEmojisAs=d.saveEmojisAs,b.standalone=d.standalone,b.emojiTemplate='{alt}':'emoji" src="{img}"/>'),b.emojiTemplateAlt=b.sprite?'':'',b.emojiBtnTemplate=''+b.emojiTemplateAlt+"",b.recentEmojis=d.recentEmojis&&K();var f=d.pickerPosition;b.floatingPicker="top"===f||"bottom"===f,b.source=c,(c.is(":disabled")||c.is(".disabled"))&&b.disable();var g=c.is("TEXTAREA")||c.is("INPUT")?"val":"text",i,o,r,t,u,v,z,A,L,M,N=G("tones",d.tones?function(){this.addClass(F("tones-"+d.tonesStyle,!0));for(var b=0;b<=5;b++)this.append(a("",{"class":"btn-tone btn-tone-"+b+(b?"":" active"),"data-skin":b,role:"button"}))}:null),O=G({"class":j+(b.standalone?" "+j+"-standalone ":" ")+(c.attr("class")||""),role:"application"},i=b.editor=G("editor").attr({contenteditable:!b.standalone,placeholder:d.placeholder||c.data("placeholder")||c.attr("placeholder")||"",tabindex:0}),o=b.button=G("button",G("button-open"),G("button-close")).attr("title",d.buttonTitle),r=b.picker=G("picker",G("wrapper",t=G("filters"),d.search?v=G("search-panel",G("search",d.search?function(){b.search=a("",{placeholder:d.searchPlaceholder||"",type:"text","class":"search"}),this.append(b.search)}:null),N):null,M=G("scroll-area",d.tones&&!d.search?G("tones-panel",N):null,z=G("emojis-list")))).addClass(F("picker-position-"+d.pickerPosition,!0)).addClass(F("filters-position-"+d.filtersPosition,!0)).addClass(F("search-position-"+d.searchPosition,!0)).addClass("hidden"));d.search&&v.addClass(F("with-search",!0)),b.searchSel=null,i.data(c.data()),a.each(d.attributes,function(a,b){i.attr(a,b)});var P=G("category-block").attr({"data-tone":0}).prependTo(z);if(a.each(d.filters,function(c,e){var f=0;if("recent"!==c||b.recentEmojis){if("tones"!==c)a("",{"class":F("filter",!0)+" "+F("filter-"+c,!0),"data-filter":c,title:e.title}).wrapInner(p(e.icon,b.emojiTemplateAlt)).appendTo(t);else{if(!d.tones)return;f=5}do{var g,h=e.emoji.replace(/[\s,;]+/g,"|");g=0===f?G("category").attr({name:c,"data-tone":f}).appendTo(P):G("category-block").attr({name:c,"data-tone":f}).appendTo(z),f>0&&(g.hide(),h=h.split("|").join("_tone"+f+"|")+"_tone"+f),"recent"===c&&(h=H()),h=p(h,b.sprite?'':'',!0).split("|").join(""),g.html(h),a('
').text(e.title).prependTo(g)}while(--f>0)}}),d.filters=null,b.sprite||(b.lasyEmoji=z.find(".lazy-emoji")),u=t.find(F("filter")),u.eq(0).addClass("active"),L=z.find(F("category-block")),A=z.find(F("category")),b.recentFilter=u.filter('[data-filter="recent"]'),b.recentCategory=A.filter("[name=recent]"),b.scrollArea=M,d.container?a(d.container).wrapInner(O):O.insertAfter(c),d.hideSource&&c.hide(),b.setText(c[g]()),c[g](b.getText()),D.apply(b),b.standalone&&!b.getText().length){var Q=a(c).data("emoji-placeholder")||d.emojiPlaceholder;b.setText(Q),i.addClass("has-placeholder")}n(b,z.find(".emojibtn"),{click:"emojibtn.click"}),n(b,window,{resize:"!resize"}),n(b,N.children(),{click:"tone.click"}),n(b,[r,o],{mousedown:"!mousedown"},i),n(b,o,{click:"button.click"}),n(b,i,{paste:"!paste"},i),n(b,i,["focus","blur"],function(){return!b.stayFocused&&i}),n(b,r,{mousedown:"picker.mousedown",mouseup:"picker.mouseup",click:"picker.click",keyup:"picker.keyup",keydown:"picker.keydown",keypress:"picker.keypress"}),n(b,i,["mousedown","mouseup","click","keyup","keydown","keypress"]),n(b,r.find(".emojionearea-filter"),{click:"filter.click"}),n(b,c,{change:"source.change"}),d.search&&n(b,b.search,{keyup:"search.keypress",focus:"search.focus",blur:"search.blur"});var R=!1;if(M.on("scroll",function(){if(!R&&(E.call(b),M.is(":not(.skinnable)"))){var c=A.eq(0),d=M.offset().top;A.each(function(b,e){return!(a(e).offset().top-d>=10)&&void(c=a(e))});var e=u.filter('[data-filter="'+c.attr("name")+'"]');e[0]&&!e.is(".active")&&(u.removeClass("active"),e.addClass("active"))}}),b.on("@filter.click",function(a){var c=a.is(".active");if(M.is(".skinnable")){if(c)return;N.children().eq(0).click()}R=!0,c||(u.filter(".active").removeClass("active"),a.addClass("active"));var d=A.filter('[name="'+a.data("filter")+'"]').offset().top,e=M.scrollTop(),f=M.offset().top;M.stop().animate({scrollTop:d+e-f-2},200,"swing",function(){E.call(b),R=!1})}).on("@picker.show",function(){b.recentEmojis&&I(b),E.call(b)}).on("@tone.click",function(a){N.children().removeClass("active");var c=a.addClass("active").data("skin");c?(M.addClass("skinnable"),L.hide().filter("[data-tone="+c+"]").show(),u.removeClass("active")):(M.removeClass("skinnable"),L.hide().filter("[data-tone=0]").show(),u.eq(0).click()),E.call(b),d.search&&b.trigger("search.keypress")}).on("@button.click",function(a){a.is(".active")?b.hidePicker():(b.showPicker(),b.searchSel=null)}).on("@!paste",function(c,d){var e=function(d){var e="caret-"+(new Date).getTime(),f=B(d,b);q(f),q(''),c.scrollTop(h);var g=a("#"+e),i=g.offset().top-c.offset().top,j=c.height();(h+i>=j||h>i)&&c.scrollTop(h+i-2*j/3),g.remove(),b.stayFocused=!1,D.apply(b),m(b,"paste",[c,d,f])};if(d.originalEvent.clipboardData){var f=d.originalEvent.clipboardData.getData("text/plain");return e(f),d.preventDefault?d.preventDefault():d.stop(),d.returnValue=!1,d.stopPropagation(),!1}b.stayFocused=!0,q(""+l+"");var g=x(c[0]),h=c.scrollTop(),i=a("
",{contenteditable:!0}).css({position:"fixed",left:"-999px",width:"1px",height:"1px",top:"20px",overflow:"hidden"}).appendTo(a("BODY")).focus();window.setTimeout(function(){c.focus(),y(c[0],g);var a=C(i.html().replace(/\r\n|\n|\r/g,"
"),b);i.remove(),e(a)},200)}).on("@emojibtn.click",function(a){i.removeClass("has-placeholder"),null!==b.searchSel&&(i.focus(),y(i[0],b.searchSel),b.searchSel=null),b.standalone?(i.html(p(a.data("name"),b.emojiTemplate)),b.trigger("blur")):(x(i[0]),q(p(a.data("name"),b.emojiTemplate))),b.recentEmojis&&J(b,a.data("name")),b.trigger("search.keypress")}).on("@!resize @keyup @emojibtn.click",D).on("@!mousedown",function(c,d){return a(d.target).hasClass("search")?(b.stayFocused=!0,null===b.searchSel&&(b.searchSel=x(c[0]))):(O.is(".focused")||c.trigger("focus"),d.preventDefault()),!1}).on("@change",function(){var a=b.editor.html().replace(/<\/?(?:div|span|p)[^>]*>/gi,"");a.length&&!/^]*>$/i.test(a)||b.editor.html(b.content=""),c[g](b.getText())}).on("@source.change",function(){b.setText(c[g]()),m("change")}).on("@focus",function(){O.addClass("focused")}).on("@blur",function(){O.removeClass("focused"),d.hidePickerOnBlur&&b.hidePicker();var a=b.editor.html();b.content!==a?(b.content=a,m(b,"change",[b.editor]),c.trigger("blur").trigger("change")):c.trigger("blur"),d.search&&(b.search.val(""),b.trigger("search.keypress",!0))}),d.search&&b.on("@search.focus",function(){b.stayFocused=!0,b.search.addClass("focused")}).on("@search.keypress",function(c){var e=r.find(".emojionearea-filter"),f=d.tones?N.find("i.active").data("skin"):0,g=b.search.val().replace(/ /g,"_").replace(/"/g,'\\"');g&&g.length?(b.recentFilter.hasClass("active")&&b.recentFilter.removeClass("active").next().addClass("active"),b.recentCategory.hide(),b.recentFilter.hide(),L.each(function(){var b=function(a,b){var c=a.find('.emojibtn[data-name*="'+g+'"]');if(0===c.length)a.data("tone")===b&&a.hide(),e.filter('[data-filter="'+a.attr("name")+'"]').hide();else{var d=a.find('.emojibtn:not([data-name*="'+g+'"])');d.hide(),c.show(),a.data("tone")===b&&a.show(),e.filter('[data-filter="'+a.attr("name")+'"]').show()}},c=a(this);0===c.data("tone")?A.filter(':not([name="recent"])').each(function(){b(a(this),0)}):b(c,f)}),R?E.call(b):M.trigger("scroll")):(I(b,!0),L.filter('[data-tone="'+N.find("i.active").data("skin")+'"]:not([name="recent"])').show(),a(".emojibtn",L).show(),e.show(),E.call(b))}).on("@search.blur",function(){b.stayFocused=!1,b.search.removeClass("focused"),b.trigger("blur")}),d.shortcuts&&b.on("@keydown",function(a,c){c.ctrlKey||(9==c.which?(c.preventDefault(),o.click()):27==c.which&&(c.preventDefault(),o.is(".active")&&b.hidePicker()))}),s(d.events)&&!a.isEmptyObject(d.events)&&a.each(d.events,function(a,c){b.on(a.replace(/_/g,"."),c)}),d.autocomplete){var S=function(){var c={maxCount:d.textcomplete.maxCount,placement:d.textcomplete.placement};d.shortcuts&&(c.onKeydown=function(a,b){if(!a.ctrlKey&&13==a.which)return b.KEY_ENTER});var f=a.map(e.emojioneList,function(a,b){return d.autocompleteTones?b:/_tone[12345]/.test(b)?null:b});f.sort(),i.textcomplete([{id:j,match:/\B(:[\-+\w]*)$/,search:function(b,c){c(a.map(f,function(a){return 0===a.indexOf(b)?a:null}))},template:function(a){return p(a,b.emojiTemplate)+" "+a.replace(/:/g,"")},replace:function(a){return p(a,b.emojiTemplate)},cache:!0,index:1}],c),d.textcomplete.placement&&"static"==a(i.data("textComplete").option.appendTo).css("position")&&a(i.data("textComplete").option.appendTo).css("position","relative")},T=function(){if(b.disabled){var a=function(){b.off("enabled",a),S()};b.on("enabled",a)}else S()};a.fn.textcomplete?T():a.ajax({url:"https://cdn.rawgit.com/yuku-t/jquery-textcomplete/v1.3.4/dist/jquery.textcomplete.js",dataType:"script",cache:!0,success:T})}b.inline&&(O.addClass(F("inline",!0)),b.on("@keydown",function(a,b){13==b.which&&b.preventDefault()})),/firefox/i.test(navigator.userAgent)&&document.execCommand("enableObjectResizing",!1,!1),b.isReady=!0,b.trigger("onLoad",i),b.trigger("ready",i)}var M={defaultBase:"https://cdnjs.cloudflare.com/ajax/libs/emojione/",defaultBase3:"https://cdn.jsdelivr.net/",base:null,isLoading:!1};function N(b){var c=r();if(b=w(b),!M.isLoading)if(!e||u(t(e))<2){M.isLoading=!0;var d;d=u(c)>5?M.defaultBase3+"npm/emojione@"+c:u(c)>4?M.defaultBase3+"emojione/"+c:M.defaultBase+"/"+c,a.ajax({url:d+"/lib/js/emojione.min.js",dataType:"script",cache:!0,success:function(){e=window.emojione,c=t(e),k=u(c);var d;k>4?(M.base=M.defaultBase3+"emojione/assets/"+c,d=M.base+"/sprites/emojione-sprite-"+e.emojiSize+".css"):(M.base=M.defaultBase+c+"/assets",d=M.base+"/sprites/emojione.sprites.css"),b.sprite&&(document.createStyleSheet?document.createStyleSheet(d):a("",{rel:"stylesheet",href:d}).appendTo("head"));while(f.length)f.shift().call();M.isLoading=!1}})}else c=t(e),k=u(c),k>4?M.base=M.defaultBase3+"emojione/assets/"+c:M.base=M.defaultBase+c+"/assets";g(function(){var a="";b.useInternalCDN&&(k>4&&(a=e.emojiSize+"/"),e.imagePathPNG=M.base+"/png/"+a,e.imagePathSVG=M.base+"/svg/"+a,e.imagePathSVGSprites=M.base+"/sprites/emojione.sprites.svg",e.imageType=b.imageType),u(c)>4?(z=e.regUnicode,e.imageType=b.imageType||"png"):z=new RegExp("]*>.*?|]*>.*?|<(?:object|embed|svg|img|div|span|p|a)[^>]*>|("+e.unicodeRegexp+")","gi")})}var O=function(a,e){var f=this;N(e),c[f.id=++b]={},d[f.id]={},g(function(){L(f,a,e)})};function P(b,c){c=c.replace(/^@/,"");var e=b.id;d[e][c]&&(a.each(d[e][c],function(d,e){a.each(a.isArray(e[0])?e[0]:[e[0]],function(d,f){a(f).on(e[1],function(){var d=i.call(arguments),f=a.isFunction(e[2])?e[2].apply(b,[c].concat(d)):e[2];f&&m(b,c,[f].concat(d))})})}),d[e][c]=null)}O.prototype.on=function(b,d){if(b&&a.isFunction(d)){var e=this;a.each(b.toLowerCase().split(" "),function(a,b){P(e,b),(c[e.id][b]||(c[e.id][b]=[])).push(d)})}return this},O.prototype.off=function(b,d){if(b){var e=this.id;a.each(b.toLowerCase().replace(/_/g,".").split(" "),function(b,f){c[e][f]&&!/^@/.test(f)&&(d?a.each(c[e][f],function(a,b){b===d&&(c[e][f]=c[e][f].splice(a,1))}):c[e][f]=[])})}return this},O.prototype.trigger=function(){var a=i.call(arguments),b=[this].concat(a.slice(0,1));return b.push(a.slice(1)),m.apply(this,b)},O.prototype.setFocus=function(){var a=this;return g(function(){a.editor.focus()}),a},O.prototype.setText=function(a){var b=this;return g(function(){b.editor.html(B(a,b)),b.content=b.editor.html(),m(b,"change",[b.editor]),D.apply(b)}),b},O.prototype.getText=function(){return C(this.editor.html(),this)},O.prototype.showPicker=function(){var a=this;return a._sh_timer&&window.clearTimeout(a._sh_timer),a.picker.removeClass("hidden"),a._sh_timer=window.setTimeout(function(){a.button.addClass("active")},50),m(a,"picker.show",[a.picker]),a},O.prototype.hidePicker=function(){var a=this;return a._sh_timer&&window.clearTimeout(a._sh_timer),a.button.removeClass("active"),a._sh_timer=window.setTimeout(function(){a.picker.addClass("hidden")},500),m(a,"picker.hide",[a.picker]),a},O.prototype.enable=function(){var a=this,b=function(){a.disabled=!1,a.editor.prop("contenteditable",!0),a.button.show();var b=a[a.standalone?"button":"editor"];b.parent().removeClass("emojionearea-disable"),m(a,"enabled",[b])};return a.isReady?b():a.on("ready",b),a},O.prototype.disable=function(){var a=this;a.disabled=!0;var b=function(){a.editor.prop("contenteditable",!1),a.hidePicker(),a.button.hide();var b=a[a.standalone?"button":"editor"];b.parent().addClass("emojionearea-disable"),m(a,"disabled",[b])};return a.isReady?b():a.on("ready",b),a},a.fn.emojioneArea=function(b){return this.each(function(){return this.emojioneArea?this.emojioneArea:(a.data(this,"emojioneArea",this.emojioneArea=new O(a(this),b)),this.emojioneArea)})},a.fn.emojioneArea.defaults=v(),a.fn.emojioneAreaText=function(b){b=w(b);var c=this,d={shortnames:!b||"undefined"==typeof b.shortnames||b.shortnames,emojiTemplate:'{alt}'};return N(b),g(function(){c.each(function(){var b=a(this);return b.hasClass("emojionearea-text")||b.addClass("emojionearea-text").html(B(b.is("TEXTAREA")||b.is("INPUT")?b.val():b.text(),d)),b})}),this}},window); +//# sourceMappingURL=emojionearea.min.map \ No newline at end of file diff --git a/demos/js/jquery-3.3.1.slim.min.js b/demos/js/jquery-3.3.1.slim.min.js new file mode 100644 index 0000000..f4ca9b2 --- /dev/null +++ b/demos/js/jquery-3.3.1.slim.min.js @@ -0,0 +1,2 @@ +/*! jQuery v3.3.1 -ajax,-ajax/jsonp,-ajax/load,-ajax/parseXML,-ajax/script,-ajax/var/location,-ajax/var/nonce,-ajax/var/rquery,-ajax/xhr,-manipulation/_evalUrl,-event/ajax,-effects,-effects/Tween,-effects/animatedSelector | (c) JS Foundation and other contributors | jquery.org/license */ +!function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(e,t){"use strict";var n=[],r=e.document,i=Object.getPrototypeOf,o=n.slice,a=n.concat,u=n.push,s=n.indexOf,l={},c=l.toString,f=l.hasOwnProperty,d=f.toString,p=d.call(Object),h={},g=function e(t){return"function"==typeof t&&"number"!=typeof t.nodeType},v=function e(t){return null!=t&&t===t.window},y={type:!0,src:!0,noModule:!0};function m(e,t,n){var i,o=(t=t||r).createElement("script");if(o.text=e,n)for(i in y)n[i]&&(o[i]=n[i]);t.head.appendChild(o).parentNode.removeChild(o)}function b(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?l[c.call(e)]||"object":typeof e}var x="3.3.1 -ajax,-ajax/jsonp,-ajax/load,-ajax/parseXML,-ajax/script,-ajax/var/location,-ajax/var/nonce,-ajax/var/rquery,-ajax/xhr,-manipulation/_evalUrl,-event/ajax,-effects,-effects/Tween,-effects/animatedSelector",w=function(e,t){return new w.fn.init(e,t)},C=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;w.fn=w.prototype={jquery:x,constructor:w,length:0,toArray:function(){return o.call(this)},get:function(e){return null==e?o.call(this):e<0?this[e+this.length]:this[e]},pushStack:function(e){var t=w.merge(this.constructor(),e);return t.prevObject=this,t},each:function(e){return w.each(this,e)},map:function(e){return this.pushStack(w.map(this,function(t,n){return e.call(t,n,t)}))},slice:function(){return this.pushStack(o.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(e<0?t:0);return this.pushStack(n>=0&&n0&&t-1 in e)}var E=function(e){var t,n,r,i,o,a,u,s,l,c,f,d,p,h,g,v,y,m,b,x="sizzle"+1*new Date,w=e.document,C=0,T=0,E=ae(),N=ae(),k=ae(),A=function(e,t){return e===t&&(f=!0),0},D={}.hasOwnProperty,S=[],L=S.pop,j=S.push,q=S.push,O=S.slice,P=function(e,t){for(var n=0,r=e.length;n+~]|"+I+")"+I+"*"),_=new RegExp("="+I+"*([^\\]'\"]*?)"+I+"*\\]","g"),U=new RegExp(M),V=new RegExp("^"+R+"$"),X={ID:new RegExp("^#("+R+")"),CLASS:new RegExp("^\\.("+R+")"),TAG:new RegExp("^("+R+"|[*])"),ATTR:new RegExp("^"+B),PSEUDO:new RegExp("^"+M),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+I+"*(even|odd|(([+-]|)(\\d*)n|)"+I+"*(?:([+-]|)"+I+"*(\\d+)|))"+I+"*\\)|)","i"),bool:new RegExp("^(?:"+H+")$","i"),needsContext:new RegExp("^"+I+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+I+"*((?:-\\d)?\\d*)"+I+"*\\)|)(?=[^-]|$)","i")},Q=/^(?:input|select|textarea|button)$/i,Y=/^h\d$/i,G=/^[^{]+\{\s*\[native \w/,K=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,J=/[+~]/,Z=new RegExp("\\\\([\\da-f]{1,6}"+I+"?|("+I+")|.)","ig"),ee=function(e,t,n){var r="0x"+t-65536;return r!==r||n?t:r<0?String.fromCharCode(r+65536):String.fromCharCode(r>>10|55296,1023&r|56320)},te=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ne=function(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},re=function(){d()},ie=me(function(e){return!0===e.disabled&&("form"in e||"label"in e)},{dir:"parentNode",next:"legend"});try{q.apply(S=O.call(w.childNodes),w.childNodes),S[w.childNodes.length].nodeType}catch(e){q={apply:S.length?function(e,t){j.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function oe(e,t,r,i){var o,u,l,c,f,h,y,m=t&&t.ownerDocument,C=t?t.nodeType:9;if(r=r||[],"string"!=typeof e||!e||1!==C&&9!==C&&11!==C)return r;if(!i&&((t?t.ownerDocument||t:w)!==p&&d(t),t=t||p,g)){if(11!==C&&(f=K.exec(e)))if(o=f[1]){if(9===C){if(!(l=t.getElementById(o)))return r;if(l.id===o)return r.push(l),r}else if(m&&(l=m.getElementById(o))&&b(t,l)&&l.id===o)return r.push(l),r}else{if(f[2])return q.apply(r,t.getElementsByTagName(e)),r;if((o=f[3])&&n.getElementsByClassName&&t.getElementsByClassName)return q.apply(r,t.getElementsByClassName(o)),r}if(n.qsa&&!k[e+" "]&&(!v||!v.test(e))){if(1!==C)m=t,y=e;else if("object"!==t.nodeName.toLowerCase()){(c=t.getAttribute("id"))?c=c.replace(te,ne):t.setAttribute("id",c=x),u=(h=a(e)).length;while(u--)h[u]="#"+c+" "+ye(h[u]);y=h.join(","),m=J.test(e)&&ge(t.parentNode)||t}if(y)try{return q.apply(r,m.querySelectorAll(y)),r}catch(e){}finally{c===x&&t.removeAttribute("id")}}}return s(e.replace($,"$1"),t,r,i)}function ae(){var e=[];function t(n,i){return e.push(n+" ")>r.cacheLength&&delete t[e.shift()],t[n+" "]=i}return t}function ue(e){return e[x]=!0,e}function se(e){var t=p.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function le(e,t){var n=e.split("|"),i=n.length;while(i--)r.attrHandle[n[i]]=t}function ce(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 fe(e){return function(t){return"input"===t.nodeName.toLowerCase()&&t.type===e}}function de(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function pe(e){return function(t){return"form"in t?t.parentNode&&!1===t.disabled?"label"in t?"label"in t.parentNode?t.parentNode.disabled===e:t.disabled===e:t.isDisabled===e||t.isDisabled!==!e&&ie(t)===e:t.disabled===e:"label"in t&&t.disabled===e}}function he(e){return ue(function(t){return t=+t,ue(function(n,r){var i,o=e([],n.length,t),a=o.length;while(a--)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}function ge(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}n=oe.support={},o=oe.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return!!t&&"HTML"!==t.nodeName},d=oe.setDocument=function(e){var t,i,a=e?e.ownerDocument||e:w;return a!==p&&9===a.nodeType&&a.documentElement?(p=a,h=p.documentElement,g=!o(p),w!==p&&(i=p.defaultView)&&i.top!==i&&(i.addEventListener?i.addEventListener("unload",re,!1):i.attachEvent&&i.attachEvent("onunload",re)),n.attributes=se(function(e){return e.className="i",!e.getAttribute("className")}),n.getElementsByTagName=se(function(e){return e.appendChild(p.createComment("")),!e.getElementsByTagName("*").length}),n.getElementsByClassName=G.test(p.getElementsByClassName),n.getById=se(function(e){return h.appendChild(e).id=x,!p.getElementsByName||!p.getElementsByName(x).length}),n.getById?(r.filter.ID=function(e){var t=e.replace(Z,ee);return function(e){return e.getAttribute("id")===t}},r.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&g){var n=t.getElementById(e);return n?[n]:[]}}):(r.filter.ID=function(e){var t=e.replace(Z,ee);return function(e){var n="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return n&&n.value===t}},r.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&g){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[]}}),r.find.TAG=n.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):n.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},r.find.CLASS=n.getElementsByClassName&&function(e,t){if("undefined"!=typeof t.getElementsByClassName&&g)return t.getElementsByClassName(e)},y=[],v=[],(n.qsa=G.test(p.querySelectorAll))&&(se(function(e){h.appendChild(e).innerHTML="",e.querySelectorAll("[msallowcapture^='']").length&&v.push("[*^$]="+I+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||v.push("\\["+I+"*(?:value|"+H+")"),e.querySelectorAll("[id~="+x+"-]").length||v.push("~="),e.querySelectorAll(":checked").length||v.push(":checked"),e.querySelectorAll("a#"+x+"+*").length||v.push(".#.+[+~]")}),se(function(e){e.innerHTML="";var t=p.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&v.push("name"+I+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&v.push(":enabled",":disabled"),h.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&v.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),v.push(",.*:")})),(n.matchesSelector=G.test(m=h.matches||h.webkitMatchesSelector||h.mozMatchesSelector||h.oMatchesSelector||h.msMatchesSelector))&&se(function(e){n.disconnectedMatch=m.call(e,"*"),m.call(e,"[s!='']:x"),y.push("!=",M)}),v=v.length&&new RegExp(v.join("|")),y=y.length&&new RegExp(y.join("|")),t=G.test(h.compareDocumentPosition),b=t||G.test(h.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},A=t?function(e,t){if(e===t)return f=!0,0;var r=!e.compareDocumentPosition-!t.compareDocumentPosition;return r||(1&(r=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!n.sortDetached&&t.compareDocumentPosition(e)===r?e===p||e.ownerDocument===w&&b(w,e)?-1:t===p||t.ownerDocument===w&&b(w,t)?1:c?P(c,e)-P(c,t):0:4&r?-1:1)}:function(e,t){if(e===t)return f=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,a=[e],u=[t];if(!i||!o)return e===p?-1:t===p?1:i?-1:o?1:c?P(c,e)-P(c,t):0;if(i===o)return ce(e,t);n=e;while(n=n.parentNode)a.unshift(n);n=t;while(n=n.parentNode)u.unshift(n);while(a[r]===u[r])r++;return r?ce(a[r],u[r]):a[r]===w?-1:u[r]===w?1:0},p):p},oe.matches=function(e,t){return oe(e,null,null,t)},oe.matchesSelector=function(e,t){if((e.ownerDocument||e)!==p&&d(e),t=t.replace(_,"='$1']"),n.matchesSelector&&g&&!k[t+" "]&&(!y||!y.test(t))&&(!v||!v.test(t)))try{var r=m.call(e,t);if(r||n.disconnectedMatch||e.document&&11!==e.document.nodeType)return r}catch(e){}return oe(t,p,null,[e]).length>0},oe.contains=function(e,t){return(e.ownerDocument||e)!==p&&d(e),b(e,t)},oe.attr=function(e,t){(e.ownerDocument||e)!==p&&d(e);var i=r.attrHandle[t.toLowerCase()],o=i&&D.call(r.attrHandle,t.toLowerCase())?i(e,t,!g):void 0;return void 0!==o?o:n.attributes||!g?e.getAttribute(t):(o=e.getAttributeNode(t))&&o.specified?o.value:null},oe.escape=function(e){return(e+"").replace(te,ne)},oe.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},oe.uniqueSort=function(e){var t,r=[],i=0,o=0;if(f=!n.detectDuplicates,c=!n.sortStable&&e.slice(0),e.sort(A),f){while(t=e[o++])t===e[o]&&(i=r.push(o));while(i--)e.splice(r[i],1)}return c=null,e},i=oe.getText=function(e){var t,n="",r=0,o=e.nodeType;if(o){if(1===o||9===o||11===o){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=i(e)}else if(3===o||4===o)return e.nodeValue}else while(t=e[r++])n+=i(t);return n},(r=oe.selectors={cacheLength:50,createPseudo:ue,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(Z,ee),e[3]=(e[3]||e[4]||e[5]||"").replace(Z,ee),"~="===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]||oe.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]&&oe.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return X.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&U.test(n)&&(t=a(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(Z,ee).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=E[e+" "];return t||(t=new RegExp("(^|"+I+")"+e+"("+I+"|$)"))&&E(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=oe.attr(r,e);return null==i?"!="===t:!t||(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i.replace(W," ")+" ").indexOf(n)>-1:"|="===t&&(i===n||i.slice(0,n.length+1)===n+"-"))}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),u="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,s){var l,c,f,d,p,h,g=o!==a?"nextSibling":"previousSibling",v=t.parentNode,y=u&&t.nodeName.toLowerCase(),m=!s&&!u,b=!1;if(v){if(o){while(g){d=t;while(d=d[g])if(u?d.nodeName.toLowerCase()===y:1===d.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?v.firstChild:v.lastChild],a&&m){b=(p=(l=(c=(f=(d=v)[x]||(d[x]={}))[d.uniqueID]||(f[d.uniqueID]={}))[e]||[])[0]===C&&l[1])&&l[2],d=p&&v.childNodes[p];while(d=++p&&d&&d[g]||(b=p=0)||h.pop())if(1===d.nodeType&&++b&&d===t){c[e]=[C,p,b];break}}else if(m&&(b=p=(l=(c=(f=(d=t)[x]||(d[x]={}))[d.uniqueID]||(f[d.uniqueID]={}))[e]||[])[0]===C&&l[1]),!1===b)while(d=++p&&d&&d[g]||(b=p=0)||h.pop())if((u?d.nodeName.toLowerCase()===y:1===d.nodeType)&&++b&&(m&&((c=(f=d[x]||(d[x]={}))[d.uniqueID]||(f[d.uniqueID]={}))[e]=[C,b]),d===t))break;return(b-=i)===r||b%r==0&&b/r>=0}}},PSEUDO:function(e,t){var n,i=r.pseudos[e]||r.setFilters[e.toLowerCase()]||oe.error("unsupported pseudo: "+e);return i[x]?i(t):i.length>1?(n=[e,e,"",t],r.setFilters.hasOwnProperty(e.toLowerCase())?ue(function(e,n){var r,o=i(e,t),a=o.length;while(a--)e[r=P(e,o[a])]=!(n[r]=o[a])}):function(e){return i(e,0,n)}):i}},pseudos:{not:ue(function(e){var t=[],n=[],r=u(e.replace($,"$1"));return r[x]?ue(function(e,t,n,i){var o,a=r(e,null,i,[]),u=e.length;while(u--)(o=a[u])&&(e[u]=!(t[u]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),t[0]=null,!n.pop()}}),has:ue(function(e){return function(t){return oe(e,t).length>0}}),contains:ue(function(e){return e=e.replace(Z,ee),function(t){return(t.textContent||t.innerText||i(t)).indexOf(e)>-1}}),lang:ue(function(e){return V.test(e||"")||oe.error("unsupported lang: "+e),e=e.replace(Z,ee).toLowerCase(),function(t){var n;do{if(n=g?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return(n=n.toLowerCase())===e||0===n.indexOf(e+"-")}while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===h},focus:function(e){return e===p.activeElement&&(!p.hasFocus||p.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:pe(!1),disabled:pe(!0),checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,!0===e.selected},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!r.pseudos.empty(e)},header:function(e){return Y.test(e.nodeName)},input:function(e){return Q.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||"text"===t.toLowerCase())},first:he(function(){return[0]}),last:he(function(e,t){return[t-1]}),eq:he(function(e,t,n){return[n<0?n+t:n]}),even:he(function(e,t){for(var n=0;n=0;)e.push(r);return e}),gt:he(function(e,t,n){for(var r=n<0?n+t:n;++r1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function xe(e,t,n){for(var r=0,i=t.length;r-1&&(o[l]=!(a[l]=f))}}else y=we(y===a?y.splice(h,y.length):y),i?i(null,a,y,s):q.apply(a,y)})}function Te(e){for(var t,n,i,o=e.length,a=r.relative[e[0].type],u=a||r.relative[" "],s=a?1:0,c=me(function(e){return e===t},u,!0),f=me(function(e){return P(t,e)>-1},u,!0),d=[function(e,n,r){var i=!a&&(r||n!==l)||((t=n).nodeType?c(e,n,r):f(e,n,r));return t=null,i}];s1&&be(d),s>1&&ye(e.slice(0,s-1).concat({value:" "===e[s-2].type?"*":""})).replace($,"$1"),n,s0,i=e.length>0,o=function(o,a,u,s,c){var f,h,v,y=0,m="0",b=o&&[],x=[],w=l,T=o||i&&r.find.TAG("*",c),E=C+=null==w?1:Math.random()||.1,N=T.length;for(c&&(l=a===p||a||c);m!==N&&null!=(f=T[m]);m++){if(i&&f){h=0,a||f.ownerDocument===p||(d(f),u=!g);while(v=e[h++])if(v(f,a||p,u)){s.push(f);break}c&&(C=E)}n&&((f=!v&&f)&&y--,o&&b.push(f))}if(y+=m,n&&m!==y){h=0;while(v=t[h++])v(b,x,a,u);if(o){if(y>0)while(m--)b[m]||x[m]||(x[m]=L.call(s));x=we(x)}q.apply(s,x),c&&!o&&x.length>0&&y+t.length>1&&oe.uniqueSort(s)}return c&&(C=E,l=w),b};return n?ue(o):o}return u=oe.compile=function(e,t){var n,r=[],i=[],o=k[e+" "];if(!o){t||(t=a(e)),n=t.length;while(n--)(o=Te(t[n]))[x]?r.push(o):i.push(o);(o=k(e,Ee(i,r))).selector=e}return o},s=oe.select=function(e,t,n,i){var o,s,l,c,f,d="function"==typeof e&&e,p=!i&&a(e=d.selector||e);if(n=n||[],1===p.length){if((s=p[0]=p[0].slice(0)).length>2&&"ID"===(l=s[0]).type&&9===t.nodeType&&g&&r.relative[s[1].type]){if(!(t=(r.find.ID(l.matches[0].replace(Z,ee),t)||[])[0]))return n;d&&(t=t.parentNode),e=e.slice(s.shift().value.length)}o=X.needsContext.test(e)?0:s.length;while(o--){if(l=s[o],r.relative[c=l.type])break;if((f=r.find[c])&&(i=f(l.matches[0].replace(Z,ee),J.test(s[0].type)&&ge(t.parentNode)||t))){if(s.splice(o,1),!(e=i.length&&ye(s)))return q.apply(n,i),n;break}}}return(d||u(e,p))(i,t,!g,n,!t||J.test(e)&&ge(t.parentNode)||t),n},n.sortStable=x.split("").sort(A).join("")===x,n.detectDuplicates=!!f,d(),n.sortDetached=se(function(e){return 1&e.compareDocumentPosition(p.createElement("fieldset"))}),se(function(e){return e.innerHTML="","#"===e.firstChild.getAttribute("href")})||le("type|href|height|width",function(e,t,n){if(!n)return e.getAttribute(t,"type"===t.toLowerCase()?1:2)}),n.attributes&&se(function(e){return e.innerHTML="",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||le("value",function(e,t,n){if(!n&&"input"===e.nodeName.toLowerCase())return e.defaultValue}),se(function(e){return null==e.getAttribute("disabled")})||le(H,function(e,t,n){var r;if(!n)return!0===e[t]?t.toLowerCase():(r=e.getAttributeNode(t))&&r.specified?r.value:null}),oe}(e);w.find=E,w.expr=E.selectors,w.expr[":"]=w.expr.pseudos,w.uniqueSort=w.unique=E.uniqueSort,w.text=E.getText,w.isXMLDoc=E.isXML,w.contains=E.contains,w.escapeSelector=E.escape;var N=function(e,t,n){var r=[],i=void 0!==n;while((e=e[t])&&9!==e.nodeType)if(1===e.nodeType){if(i&&w(e).is(n))break;r.push(e)}return r},k=function(e,t){for(var n=[];e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n},A=w.expr.match.needsContext;function D(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()}var S=/^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function L(e,t,n){return g(t)?w.grep(e,function(e,r){return!!t.call(e,r,e)!==n}):t.nodeType?w.grep(e,function(e){return e===t!==n}):"string"!=typeof t?w.grep(e,function(e){return s.call(t,e)>-1!==n}):w.filter(t,e,n)}w.filter=function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?w.find.matchesSelector(r,e)?[r]:[]:w.find.matches(e,w.grep(t,function(e){return 1===e.nodeType}))},w.fn.extend({find:function(e){var t,n,r=this.length,i=this;if("string"!=typeof e)return this.pushStack(w(e).filter(function(){for(t=0;t1?w.uniqueSort(n):n},filter:function(e){return this.pushStack(L(this,e||[],!1))},not:function(e){return this.pushStack(L(this,e||[],!0))},is:function(e){return!!L(this,"string"==typeof e&&A.test(e)?w(e):e||[],!1).length}});var j,q=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/;(w.fn.init=function(e,t,n){var i,o;if(!e)return this;if(n=n||j,"string"==typeof e){if(!(i="<"===e[0]&&">"===e[e.length-1]&&e.length>=3?[null,e,null]:q.exec(e))||!i[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(i[1]){if(t=t instanceof w?t[0]:t,w.merge(this,w.parseHTML(i[1],t&&t.nodeType?t.ownerDocument||t:r,!0)),S.test(i[1])&&w.isPlainObject(t))for(i in t)g(this[i])?this[i](t[i]):this.attr(i,t[i]);return this}return(o=r.getElementById(i[2]))&&(this[0]=o,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):g(e)?void 0!==n.ready?n.ready(e):e(w):w.makeArray(e,this)}).prototype=w.fn,j=w(r);var O=/^(?:parents|prev(?:Until|All))/,P={children:!0,contents:!0,next:!0,prev:!0};w.fn.extend({has:function(e){var t=w(e,this),n=t.length;return this.filter(function(){for(var e=0;e-1:1===n.nodeType&&w.find.matchesSelector(n,e))){o.push(n);break}return this.pushStack(o.length>1?w.uniqueSort(o):o)},index:function(e){return e?"string"==typeof e?s.call(w(e),this[0]):s.call(this,e.jquery?e[0]:e):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){return this.pushStack(w.uniqueSort(w.merge(this.get(),w(e,t))))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}});function H(e,t){while((e=e[t])&&1!==e.nodeType);return e}w.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return N(e,"parentNode")},parentsUntil:function(e,t,n){return N(e,"parentNode",n)},next:function(e){return H(e,"nextSibling")},prev:function(e){return H(e,"previousSibling")},nextAll:function(e){return N(e,"nextSibling")},prevAll:function(e){return N(e,"previousSibling")},nextUntil:function(e,t,n){return N(e,"nextSibling",n)},prevUntil:function(e,t,n){return N(e,"previousSibling",n)},siblings:function(e){return k((e.parentNode||{}).firstChild,e)},children:function(e){return k(e.firstChild)},contents:function(e){return D(e,"iframe")?e.contentDocument:(D(e,"template")&&(e=e.content||e),w.merge([],e.childNodes))}},function(e,t){w.fn[e]=function(n,r){var i=w.map(this,t,n);return"Until"!==e.slice(-5)&&(r=n),r&&"string"==typeof r&&(i=w.filter(r,i)),this.length>1&&(P[e]||w.uniqueSort(i),O.test(e)&&i.reverse()),this.pushStack(i)}});var I=/[^\x20\t\r\n\f]+/g;function R(e){var t={};return w.each(e.match(I)||[],function(e,n){t[n]=!0}),t}w.Callbacks=function(e){e="string"==typeof e?R(e):w.extend({},e);var t,n,r,i,o=[],a=[],u=-1,s=function(){for(i=i||e.once,r=t=!0;a.length;u=-1){n=a.shift();while(++u-1)o.splice(n,1),n<=u&&u--}),this},has:function(e){return e?w.inArray(e,o)>-1:o.length>0},empty:function(){return o&&(o=[]),this},disable:function(){return i=a=[],o=n="",this},disabled:function(){return!o},lock:function(){return i=a=[],n||t||(o=n=""),this},locked:function(){return!!i},fireWith:function(e,n){return i||(n=[e,(n=n||[]).slice?n.slice():n],a.push(n),t||s()),this},fire:function(){return l.fireWith(this,arguments),this},fired:function(){return!!r}};return l};function B(e){return e}function M(e){throw e}function W(e,t,n,r){var i;try{e&&g(i=e.promise)?i.call(e).done(t).fail(n):e&&g(i=e.then)?i.call(e,t,n):t.apply(void 0,[e].slice(r))}catch(e){n.apply(void 0,[e])}}w.extend({Deferred:function(t){var n=[["notify","progress",w.Callbacks("memory"),w.Callbacks("memory"),2],["resolve","done",w.Callbacks("once memory"),w.Callbacks("once memory"),0,"resolved"],["reject","fail",w.Callbacks("once memory"),w.Callbacks("once memory"),1,"rejected"]],r="pending",i={state:function(){return r},always:function(){return o.done(arguments).fail(arguments),this},"catch":function(e){return i.then(null,e)},pipe:function(){var e=arguments;return w.Deferred(function(t){w.each(n,function(n,r){var i=g(e[r[4]])&&e[r[4]];o[r[1]](function(){var e=i&&i.apply(this,arguments);e&&g(e.promise)?e.promise().progress(t.notify).done(t.resolve).fail(t.reject):t[r[0]+"With"](this,i?[e]:arguments)})}),e=null}).promise()},then:function(t,r,i){var o=0;function a(t,n,r,i){return function(){var u=this,s=arguments,l=function(){var e,l;if(!(t=o&&(r!==M&&(u=void 0,s=[e]),n.rejectWith(u,s))}};t?c():(w.Deferred.getStackHook&&(c.stackTrace=w.Deferred.getStackHook()),e.setTimeout(c))}}return w.Deferred(function(e){n[0][3].add(a(0,e,g(i)?i:B,e.notifyWith)),n[1][3].add(a(0,e,g(t)?t:B)),n[2][3].add(a(0,e,g(r)?r:M))}).promise()},promise:function(e){return null!=e?w.extend(e,i):i}},o={};return w.each(n,function(e,t){var a=t[2],u=t[5];i[t[1]]=a.add,u&&a.add(function(){r=u},n[3-e][2].disable,n[3-e][3].disable,n[0][2].lock,n[0][3].lock),a.add(t[3].fire),o[t[0]]=function(){return o[t[0]+"With"](this===o?void 0:this,arguments),this},o[t[0]+"With"]=a.fireWith}),i.promise(o),t&&t.call(o,o),o},when:function(e){var t=arguments.length,n=t,r=Array(n),i=o.call(arguments),a=w.Deferred(),u=function(e){return function(n){r[e]=this,i[e]=arguments.length>1?o.call(arguments):n,--t||a.resolveWith(r,i)}};if(t<=1&&(W(e,a.done(u(n)).resolve,a.reject,!t),"pending"===a.state()||g(i[n]&&i[n].then)))return a.then();while(n--)W(i[n],u(n),a.reject);return a.promise()}});var $=/^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;w.Deferred.exceptionHook=function(t,n){e.console&&e.console.warn&&t&&$.test(t.name)&&e.console.warn("jQuery.Deferred exception: "+t.message,t.stack,n)},w.readyException=function(t){e.setTimeout(function(){throw t})};var F=w.Deferred();w.fn.ready=function(e){return F.then(e)["catch"](function(e){w.readyException(e)}),this},w.extend({isReady:!1,readyWait:1,ready:function(e){(!0===e?--w.readyWait:w.isReady)||(w.isReady=!0,!0!==e&&--w.readyWait>0||F.resolveWith(r,[w]))}}),w.ready.then=F.then;function z(){r.removeEventListener("DOMContentLoaded",z),e.removeEventListener("load",z),w.ready()}"complete"===r.readyState||"loading"!==r.readyState&&!r.documentElement.doScroll?e.setTimeout(w.ready):(r.addEventListener("DOMContentLoaded",z),e.addEventListener("load",z));var _=function(e,t,n,r,i,o,a){var u=0,s=e.length,l=null==n;if("object"===b(n)){i=!0;for(u in n)_(e,t,u,n[u],!0,o,a)}else if(void 0!==r&&(i=!0,g(r)||(a=!0),l&&(a?(t.call(e,r),t=null):(l=t,t=function(e,t,n){return l.call(w(e),n)})),t))for(;u1,null,!0)},removeData:function(e){return this.each(function(){J.remove(this,e)})}}),w.extend({queue:function(e,t,n){var r;if(e)return t=(t||"fx")+"queue",r=K.get(e,t),n&&(!r||Array.isArray(n)?r=K.access(e,t,w.makeArray(n)):r.push(n)),r||[]},dequeue:function(e,t){t=t||"fx";var n=w.queue(e,t),r=n.length,i=n.shift(),o=w._queueHooks(e,t),a=function(){w.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return K.get(e,n)||K.access(e,n,{empty:w.Callbacks("once memory").add(function(){K.remove(e,[t+"queue",n])})})}}),w.fn.extend({queue:function(e,t){var n=2;return"string"!=typeof e&&(t=e,e="fx",n--),arguments.length\x20\t\r\n\f]+)/i,he=/^$|^module$|\/(?:java|ecma)script/i,ge={option:[1,""],thead:[1,"","
"],col:[2,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};ge.optgroup=ge.option,ge.tbody=ge.tfoot=ge.colgroup=ge.caption=ge.thead,ge.th=ge.td;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&&D(e,t)?w.merge([e],n):n}function ye(e,t){for(var n=0,r=e.length;n-1)i&&i.push(o);else if(l=w.contains(o.ownerDocument,o),a=ve(f.appendChild(o),"script"),l&&ye(a),n){c=0;while(o=a[c++])he.test(o.type||"")&&n.push(o)}return f}!function(){var e=r.createDocumentFragment().appendChild(r.createElement("div")),t=r.createElement("input");t.setAttribute("type","radio"),t.setAttribute("checked","checked"),t.setAttribute("name","t"),e.appendChild(t),h.checkClone=e.cloneNode(!0).cloneNode(!0).lastChild.checked,e.innerHTML="",h.noCloneChecked=!!e.cloneNode(!0).lastChild.defaultValue}();var xe=r.documentElement,we=/^key/,Ce=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,Te=/^([^.]*)(?:\.(.+)|)/;function Ee(){return!0}function Ne(){return!1}function ke(){try{return r.activeElement}catch(e){}}function Ae(e,t,n,r,i,o){var a,u;if("object"==typeof t){"string"!=typeof n&&(r=r||n,n=void 0);for(u in t)Ae(e,u,n,r,t[u],o);return e}if(null==r&&null==i?(i=n,r=n=void 0):null==i&&("string"==typeof n?(i=r,r=void 0):(i=r,r=n,n=void 0)),!1===i)i=Ne;else if(!i)return e;return 1===o&&(a=i,(i=function(e){return w().off(e),a.apply(this,arguments)}).guid=a.guid||(a.guid=w.guid++)),e.each(function(){w.event.add(this,t,i,r,n)})}w.event={global:{},add:function(e,t,n,r,i){var o,a,u,s,l,c,f,d,p,h,g,v=K.get(e);if(v){n.handler&&(n=(o=n).handler,i=o.selector),i&&w.find.matchesSelector(xe,i),n.guid||(n.guid=w.guid++),(s=v.events)||(s=v.events={}),(a=v.handle)||(a=v.handle=function(t){return"undefined"!=typeof w&&w.event.triggered!==t.type?w.event.dispatch.apply(e,arguments):void 0}),l=(t=(t||"").match(I)||[""]).length;while(l--)p=g=(u=Te.exec(t[l])||[])[1],h=(u[2]||"").split(".").sort(),p&&(f=w.event.special[p]||{},p=(i?f.delegateType:f.bindType)||p,f=w.event.special[p]||{},c=w.extend({type:p,origType:g,data:r,handler:n,guid:n.guid,selector:i,needsContext:i&&w.expr.match.needsContext.test(i),namespace:h.join(".")},o),(d=s[p])||((d=s[p]=[]).delegateCount=0,f.setup&&!1!==f.setup.call(e,r,h,a)||e.addEventListener&&e.addEventListener(p,a)),f.add&&(f.add.call(e,c),c.handler.guid||(c.handler.guid=n.guid)),i?d.splice(d.delegateCount++,0,c):d.push(c),w.event.global[p]=!0)}},remove:function(e,t,n,r,i){var o,a,u,s,l,c,f,d,p,h,g,v=K.hasData(e)&&K.get(e);if(v&&(s=v.events)){l=(t=(t||"").match(I)||[""]).length;while(l--)if(u=Te.exec(t[l])||[],p=g=u[1],h=(u[2]||"").split(".").sort(),p){f=w.event.special[p]||{},d=s[p=(r?f.delegateType:f.bindType)||p]||[],u=u[2]&&new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),a=o=d.length;while(o--)c=d[o],!i&&g!==c.origType||n&&n.guid!==c.guid||u&&!u.test(c.namespace)||r&&r!==c.selector&&("**"!==r||!c.selector)||(d.splice(o,1),c.selector&&d.delegateCount--,f.remove&&f.remove.call(e,c));a&&!d.length&&(f.teardown&&!1!==f.teardown.call(e,h,v.handle)||w.removeEvent(e,p,v.handle),delete s[p])}else for(p in s)w.event.remove(e,p+t[l],n,r,!0);w.isEmptyObject(s)&&K.remove(e,"handle events")}},dispatch:function(e){var t=w.event.fix(e),n,r,i,o,a,u,s=new Array(arguments.length),l=(K.get(this,"events")||{})[t.type]||[],c=w.event.special[t.type]||{};for(s[0]=t,n=1;n=1))for(;l!==this;l=l.parentNode||this)if(1===l.nodeType&&("click"!==e.type||!0!==l.disabled)){for(o=[],a={},n=0;n-1:w.find(i,this,null,[l]).length),a[i]&&o.push(r);o.length&&u.push({elem:l,handlers:o})}return l=this,s\x20\t\r\n\f]*)[^>]*)\/>/gi,Se=/\s*$/g;function qe(e,t){return D(e,"table")&&D(11!==t.nodeType?t:t.firstChild,"tr")?w(e).children("tbody")[0]||e:e}function Oe(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function Pe(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function He(e,t){var n,r,i,o,a,u,s,l;if(1===t.nodeType){if(K.hasData(e)&&(o=K.access(e),a=K.set(t,o),l=o.events)){delete a.handle,a.events={};for(i in l)for(n=0,r=l[i].length;n1&&"string"==typeof v&&!h.checkClone&&Le.test(v))return e.each(function(i){var o=e.eq(i);y&&(t[0]=v.call(this,i,o.html())),Re(o,t,n,r)});if(d&&(i=be(t,e[0].ownerDocument,!1,e,r),o=i.firstChild,1===i.childNodes.length&&(i=o),o||r)){for(s=(u=w.map(ve(i,"script"),Oe)).length;f")},clone:function(e,t,n){var r,i,o,a,u=e.cloneNode(!0),s=w.contains(e.ownerDocument,e);if(!(h.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||w.isXMLDoc(e)))for(a=ve(u),r=0,i=(o=ve(e)).length;r0&&ye(a,!s&&ve(e,"script")),u},cleanData:function(e){for(var t,n,r,i=w.event.special,o=0;void 0!==(n=e[o]);o++)if(Y(n)){if(t=n[K.expando]){if(t.events)for(r in t.events)i[r]?w.event.remove(n,r):w.removeEvent(n,r,t.handle);n[K.expando]=void 0}n[J.expando]&&(n[J.expando]=void 0)}}}),w.fn.extend({detach:function(e){return Be(this,e,!0)},remove:function(e){return Be(this,e)},text:function(e){return _(this,function(e){return void 0===e?w.text(this):this.empty().each(function(){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||(this.textContent=e)})},null,e,arguments.length)},append:function(){return Re(this,arguments,function(e){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||qe(this,e).appendChild(e)})},prepend:function(){return Re(this,arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=qe(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return Re(this,arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return Re(this,arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},empty:function(){for(var e,t=0;null!=(e=this[t]);t++)1===e.nodeType&&(w.cleanData(ve(e,!1)),e.textContent="");return this},clone:function(e,t){return e=null!=e&&e,t=null==t?e:t,this.map(function(){return w.clone(this,e,t)})},html:function(e){return _(this,function(e){var t=this[0]||{},n=0,r=this.length;if(void 0===e&&1===t.nodeType)return t.innerHTML;if("string"==typeof e&&!Se.test(e)&&!ge[(pe.exec(e)||["",""])[1].toLowerCase()]){e=w.htmlPrefilter(e);try{for(;n=0&&(s+=Math.max(0,Math.ceil(e["offset"+t[0].toUpperCase()+t.slice(1)]-o-s-u-.5))),s}function et(e,t,n){var r=We(e),i=Fe(e,t,r),o="border-box"===w.css(e,"boxSizing",!1,r),a=o;if(Me.test(i)){if(!n)return i;i="auto"}return a=a&&(h.boxSizingReliable()||i===e.style[t]),("auto"===i||!parseFloat(i)&&"inline"===w.css(e,"display",!1,r))&&(i=e["offset"+t[0].toUpperCase()+t.slice(1)],a=!0),(i=parseFloat(i)||0)+Ze(e,t,n||(o?"border":"content"),a,r,i)+"px"}w.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Fe(e,"opacity");return""===n?"1":n}}}},cssNumber:{animationIterationCount:!0,columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{},style:function(e,t,n,r){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var i,o,a,u=Q(t),s=Ue.test(t),l=e.style;if(s||(t=Ke(u)),a=w.cssHooks[t]||w.cssHooks[u],void 0===n)return a&&"get"in a&&void 0!==(i=a.get(e,!1,r))?i:l[t];"string"==(o=typeof n)&&(i=ie.exec(n))&&i[1]&&(n=se(e,t,i),o="number"),null!=n&&n===n&&("number"===o&&(n+=i&&i[3]||(w.cssNumber[u]?"":"px")),h.clearCloneStyle||""!==n||0!==t.indexOf("background")||(l[t]="inherit"),a&&"set"in a&&void 0===(n=a.set(e,n,r))||(s?l.setProperty(t,n):l[t]=n))}},css:function(e,t,n,r){var i,o,a,u=Q(t);return Ue.test(t)||(t=Ke(u)),(a=w.cssHooks[t]||w.cssHooks[u])&&"get"in a&&(i=a.get(e,!0,n)),void 0===i&&(i=Fe(e,t,r)),"normal"===i&&t in Xe&&(i=Xe[t]),""===n||n?(o=parseFloat(i),!0===n||isFinite(o)?o||0:i):i}}),w.each(["height","width"],function(e,t){w.cssHooks[t]={get:function(e,n,r){if(n)return!_e.test(w.css(e,"display"))||e.getClientRects().length&&e.getBoundingClientRect().width?et(e,t,r):ue(e,Ve,function(){return et(e,t,r)})},set:function(e,n,r){var i,o=We(e),a="border-box"===w.css(e,"boxSizing",!1,o),u=r&&Ze(e,t,r,a,o);return a&&h.scrollboxSize()===o.position&&(u-=Math.ceil(e["offset"+t[0].toUpperCase()+t.slice(1)]-parseFloat(o[t])-Ze(e,t,"border",!1,o)-.5)),u&&(i=ie.exec(n))&&"px"!==(i[3]||"px")&&(e.style[t]=n,n=w.css(e,t)),Je(e,n,u)}}}),w.cssHooks.marginLeft=ze(h.reliableMarginLeft,function(e,t){if(t)return(parseFloat(Fe(e,"marginLeft"))||e.getBoundingClientRect().left-ue(e,{marginLeft:0},function(){return e.getBoundingClientRect().left}))+"px"}),w.each({margin:"",padding:"",border:"Width"},function(e,t){w.cssHooks[e+t]={expand:function(n){for(var r=0,i={},o="string"==typeof n?n.split(" "):[n];r<4;r++)i[e+oe[r]+t]=o[r]||o[r-2]||o[0];return i}},"margin"!==e&&(w.cssHooks[e+t].set=Je)}),w.fn.extend({css:function(e,t){return _(this,function(e,t,n){var r,i,o={},a=0;if(Array.isArray(t)){for(r=We(e),i=t.length;a1)}}),w.fn.delay=function(t,n){return t=w.fx?w.fx.speeds[t]||t:t,n=n||"fx",this.queue(n,function(n,r){var i=e.setTimeout(n,t);r.stop=function(){e.clearTimeout(i)}})},function(){var e=r.createElement("input"),t=r.createElement("select").appendChild(r.createElement("option"));e.type="checkbox",h.checkOn=""!==e.value,h.optSelected=t.selected,(e=r.createElement("input")).value="t",e.type="radio",h.radioValue="t"===e.value}();var tt,nt=w.expr.attrHandle;w.fn.extend({attr:function(e,t){return _(this,w.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){w.removeAttr(this,e)})}}),w.extend({attr:function(e,t,n){var r,i,o=e.nodeType;if(3!==o&&8!==o&&2!==o)return"undefined"==typeof e.getAttribute?w.prop(e,t,n):(1===o&&w.isXMLDoc(e)||(i=w.attrHooks[t.toLowerCase()]||(w.expr.match.bool.test(t)?tt:void 0)),void 0!==n?null===n?void w.removeAttr(e,t):i&&"set"in i&&void 0!==(r=i.set(e,n,t))?r:(e.setAttribute(t,n+""),n):i&&"get"in i&&null!==(r=i.get(e,t))?r:null==(r=w.find.attr(e,t))?void 0:r)},attrHooks:{type:{set:function(e,t){if(!h.radioValue&&"radio"===t&&D(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},removeAttr:function(e,t){var n,r=0,i=t&&t.match(I);if(i&&1===e.nodeType)while(n=i[r++])e.removeAttribute(n)}}),tt={set:function(e,t,n){return!1===t?w.removeAttr(e,n):e.setAttribute(n,n),n}},w.each(w.expr.match.bool.source.match(/\w+/g),function(e,t){var n=nt[t]||w.find.attr;nt[t]=function(e,t,r){var i,o,a=t.toLowerCase();return r||(o=nt[a],nt[a]=i,i=null!=n(e,t,r)?a:null,nt[a]=o),i}});var rt=/^(?:input|select|textarea|button)$/i,it=/^(?:a|area)$/i;w.fn.extend({prop:function(e,t){return _(this,w.prop,e,t,arguments.length>1)},removeProp:function(e){return this.each(function(){delete this[w.propFix[e]||e]})}}),w.extend({prop:function(e,t,n){var r,i,o=e.nodeType;if(3!==o&&8!==o&&2!==o)return 1===o&&w.isXMLDoc(e)||(t=w.propFix[t]||t,i=w.propHooks[t]),void 0!==n?i&&"set"in i&&void 0!==(r=i.set(e,n,t))?r:e[t]=n:i&&"get"in i&&null!==(r=i.get(e,t))?r:e[t]},propHooks:{tabIndex:{get:function(e){var t=w.find.attr(e,"tabindex");return t?parseInt(t,10):rt.test(e.nodeName)||it.test(e.nodeName)&&e.href?0:-1}}},propFix:{"for":"htmlFor","class":"className"}}),h.optSelected||(w.propHooks.selected={get:function(e){var t=e.parentNode;return t&&t.parentNode&&t.parentNode.selectedIndex,null},set:function(e){var t=e.parentNode;t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex)}}),w.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){w.propFix[this.toLowerCase()]=this});function ot(e){return(e.match(I)||[]).join(" ")}function at(e){return e.getAttribute&&e.getAttribute("class")||""}function ut(e){return Array.isArray(e)?e:"string"==typeof e?e.match(I)||[]:[]}w.fn.extend({addClass:function(e){var t,n,r,i,o,a,u,s=0;if(g(e))return this.each(function(t){w(this).addClass(e.call(this,t,at(this)))});if((t=ut(e)).length)while(n=this[s++])if(i=at(n),r=1===n.nodeType&&" "+ot(i)+" "){a=0;while(o=t[a++])r.indexOf(" "+o+" ")<0&&(r+=o+" ");i!==(u=ot(r))&&n.setAttribute("class",u)}return this},removeClass:function(e){var t,n,r,i,o,a,u,s=0;if(g(e))return this.each(function(t){w(this).removeClass(e.call(this,t,at(this)))});if(!arguments.length)return this.attr("class","");if((t=ut(e)).length)while(n=this[s++])if(i=at(n),r=1===n.nodeType&&" "+ot(i)+" "){a=0;while(o=t[a++])while(r.indexOf(" "+o+" ")>-1)r=r.replace(" "+o+" "," ");i!==(u=ot(r))&&n.setAttribute("class",u)}return this},toggleClass:function(e,t){var n=typeof e,r="string"===n||Array.isArray(e);return"boolean"==typeof t&&r?t?this.addClass(e):this.removeClass(e):g(e)?this.each(function(n){w(this).toggleClass(e.call(this,n,at(this),t),t)}):this.each(function(){var t,i,o,a;if(r){i=0,o=w(this),a=ut(e);while(t=a[i++])o.hasClass(t)?o.removeClass(t):o.addClass(t)}else void 0!==e&&"boolean"!==n||((t=at(this))&&K.set(this,"__className__",t),this.setAttribute&&this.setAttribute("class",t||!1===e?"":K.get(this,"__className__")||""))})},hasClass:function(e){var t,n,r=0;t=" "+e+" ";while(n=this[r++])if(1===n.nodeType&&(" "+ot(at(n))+" ").indexOf(t)>-1)return!0;return!1}});var st=/\r/g;w.fn.extend({val:function(e){var t,n,r,i=this[0];{if(arguments.length)return r=g(e),this.each(function(n){var i;1===this.nodeType&&(null==(i=r?e.call(this,n,w(this).val()):e)?i="":"number"==typeof i?i+="":Array.isArray(i)&&(i=w.map(i,function(e){return null==e?"":e+""})),(t=w.valHooks[this.type]||w.valHooks[this.nodeName.toLowerCase()])&&"set"in t&&void 0!==t.set(this,i,"value")||(this.value=i))});if(i)return(t=w.valHooks[i.type]||w.valHooks[i.nodeName.toLowerCase()])&&"get"in t&&void 0!==(n=t.get(i,"value"))?n:"string"==typeof(n=i.value)?n.replace(st,""):null==n?"":n}}}),w.extend({valHooks:{option:{get:function(e){var t=w.find.attr(e,"value");return null!=t?t:ot(w.text(e))}},select:{get:function(e){var t,n,r,i=e.options,o=e.selectedIndex,a="select-one"===e.type,u=a?null:[],s=a?o+1:i.length;for(r=o<0?s:a?o:0;r-1)&&(n=!0);return n||(e.selectedIndex=-1),o}}}}),w.each(["radio","checkbox"],function(){w.valHooks[this]={set:function(e,t){if(Array.isArray(t))return e.checked=w.inArray(w(e).val(),t)>-1}},h.checkOn||(w.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})}),h.focusin="onfocusin"in e;var lt=/^(?:focusinfocus|focusoutblur)$/,ct=function(e){e.stopPropagation()};w.extend(w.event,{trigger:function(t,n,i,o){var a,u,s,l,c,d,p,h,y=[i||r],m=f.call(t,"type")?t.type:t,b=f.call(t,"namespace")?t.namespace.split("."):[];if(u=h=s=i=i||r,3!==i.nodeType&&8!==i.nodeType&&!lt.test(m+w.event.triggered)&&(m.indexOf(".")>-1&&(m=(b=m.split(".")).shift(),b.sort()),c=m.indexOf(":")<0&&"on"+m,t=t[w.expando]?t:new w.Event(m,"object"==typeof t&&t),t.isTrigger=o?2:3,t.namespace=b.join("."),t.rnamespace=t.namespace?new RegExp("(^|\\.)"+b.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,t.result=void 0,t.target||(t.target=i),n=null==n?[t]:w.makeArray(n,[t]),p=w.event.special[m]||{},o||!p.trigger||!1!==p.trigger.apply(i,n))){if(!o&&!p.noBubble&&!v(i)){for(l=p.delegateType||m,lt.test(l+m)||(u=u.parentNode);u;u=u.parentNode)y.push(u),s=u;s===(i.ownerDocument||r)&&y.push(s.defaultView||s.parentWindow||e)}a=0;while((u=y[a++])&&!t.isPropagationStopped())h=u,t.type=a>1?l:p.bindType||m,(d=(K.get(u,"events")||{})[t.type]&&K.get(u,"handle"))&&d.apply(u,n),(d=c&&u[c])&&d.apply&&Y(u)&&(t.result=d.apply(u,n),!1===t.result&&t.preventDefault());return t.type=m,o||t.isDefaultPrevented()||p._default&&!1!==p._default.apply(y.pop(),n)||!Y(i)||c&&g(i[m])&&!v(i)&&((s=i[c])&&(i[c]=null),w.event.triggered=m,t.isPropagationStopped()&&h.addEventListener(m,ct),i[m](),t.isPropagationStopped()&&h.removeEventListener(m,ct),w.event.triggered=void 0,s&&(i[c]=s)),t.result}},simulate:function(e,t,n){var r=w.extend(new w.Event,n,{type:e,isSimulated:!0});w.event.trigger(r,null,t)}}),w.fn.extend({trigger:function(e,t){return this.each(function(){w.event.trigger(e,t,this)})},triggerHandler:function(e,t){var n=this[0];if(n)return w.event.trigger(e,t,n,!0)}}),h.focusin||w.each({focus:"focusin",blur:"focusout"},function(e,t){var n=function(e){w.event.simulate(t,e.target,w.event.fix(e))};w.event.special[t]={setup:function(){var r=this.ownerDocument||this,i=K.access(r,t);i||r.addEventListener(e,n,!0),K.access(r,t,(i||0)+1)},teardown:function(){var r=this.ownerDocument||this,i=K.access(r,t)-1;i?K.access(r,t,i):(r.removeEventListener(e,n,!0),K.remove(r,t))}}});var ft=/\[\]$/,dt=/\r?\n/g,pt=/^(?:submit|button|image|reset|file)$/i,ht=/^(?:input|select|textarea|keygen)/i;function gt(e,t,n,r){var i;if(Array.isArray(t))w.each(t,function(t,i){n||ft.test(e)?r(e,i):gt(e+"["+("object"==typeof i&&null!=i?t:"")+"]",i,n,r)});else if(n||"object"!==b(t))r(e,t);else for(i in t)gt(e+"["+i+"]",t[i],n,r)}w.param=function(e,t){var n,r=[],i=function(e,t){var n=g(t)?t():t;r[r.length]=encodeURIComponent(e)+"="+encodeURIComponent(null==n?"":n)};if(Array.isArray(e)||e.jquery&&!w.isPlainObject(e))w.each(e,function(){i(this.name,this.value)});else for(n in e)gt(n,e[n],t,i);return r.join("&")},w.fn.extend({serialize:function(){return w.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=w.prop(this,"elements");return e?w.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!w(this).is(":disabled")&&ht.test(this.nodeName)&&!pt.test(e)&&(this.checked||!de.test(e))}).map(function(e,t){var n=w(this).val();return null==n?null:Array.isArray(n)?w.map(n,function(e){return{name:t.name,value:e.replace(dt,"\r\n")}}):{name:t.name,value:n.replace(dt,"\r\n")}}).get()}}),w.fn.extend({wrapAll:function(e){var t;return this[0]&&(g(e)&&(e=e.call(this[0])),t=w(e,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstElementChild)e=e.firstElementChild;return e}).append(this)),this},wrapInner:function(e){return g(e)?this.each(function(t){w(this).wrapInner(e.call(this,t))}):this.each(function(){var t=w(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=g(e);return this.each(function(n){w(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(e){return this.parent(e).not("body").each(function(){w(this).replaceWith(this.childNodes)}),this}}),w.expr.pseudos.hidden=function(e){return!w.expr.pseudos.visible(e)},w.expr.pseudos.visible=function(e){return!!(e.offsetWidth||e.offsetHeight||e.getClientRects().length)},h.createHTMLDocument=function(){var e=r.implementation.createHTMLDocument("").body;return e.innerHTML="
",2===e.childNodes.length}(),w.parseHTML=function(e,t,n){if("string"!=typeof e)return[];"boolean"==typeof t&&(n=t,t=!1);var i,o,a;return t||(h.createHTMLDocument?((i=(t=r.implementation.createHTMLDocument("")).createElement("base")).href=r.location.href,t.head.appendChild(i)):t=r),o=S.exec(e),a=!n&&[],o?[t.createElement(o[1])]:(o=be([e],t,a),a&&a.length&&w(a).remove(),w.merge([],o.childNodes))},w.offset={setOffset:function(e,t,n){var r,i,o,a,u,s,l,c=w.css(e,"position"),f=w(e),d={};"static"===c&&(e.style.position="relative"),u=f.offset(),o=w.css(e,"top"),s=w.css(e,"left"),(l=("absolute"===c||"fixed"===c)&&(o+s).indexOf("auto")>-1)?(a=(r=f.position()).top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(s)||0),g(t)&&(t=t.call(e,n,w.extend({},u))),null!=t.top&&(d.top=t.top-u.top+a),null!=t.left&&(d.left=t.left-u.left+i),"using"in t?t.using.call(e,d):f.css(d)}},w.fn.extend({offset:function(e){if(arguments.length)return void 0===e?this:this.each(function(t){w.offset.setOffset(this,e,t)});var t,n,r=this[0];if(r)return r.getClientRects().length?(t=r.getBoundingClientRect(),n=r.ownerDocument.defaultView,{top:t.top+n.pageYOffset,left:t.left+n.pageXOffset}):{top:0,left:0}},position:function(){if(this[0]){var e,t,n,r=this[0],i={top:0,left:0};if("fixed"===w.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"===w.css(e,"position"))e=e.parentNode;e&&e!==r&&1===e.nodeType&&((i=w(e).offset()).top+=w.css(e,"borderTopWidth",!0),i.left+=w.css(e,"borderLeftWidth",!0))}return{top:t.top-i.top-w.css(r,"marginTop",!0),left:t.left-i.left-w.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent;while(e&&"static"===w.css(e,"position"))e=e.offsetParent;return e||xe})}}),w.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,t){var n="pageYOffset"===t;w.fn[e]=function(r){return _(this,function(e,r,i){var o;if(v(e)?o=e:9===e.nodeType&&(o=e.defaultView),void 0===i)return o?o[t]:e[r];o?o.scrollTo(n?o.pageXOffset:i,n?i:o.pageYOffset):e[r]=i},e,r,arguments.length)}}),w.each(["top","left"],function(e,t){w.cssHooks[t]=ze(h.pixelPosition,function(e,n){if(n)return n=Fe(e,t),Me.test(n)?w(e).position()[t]+"px":n})}),w.each({Height:"height",Width:"width"},function(e,t){w.each({padding:"inner"+e,content:t,"":"outer"+e},function(n,r){w.fn[r]=function(i,o){var a=arguments.length&&(n||"boolean"!=typeof i),u=n||(!0===i||!0===o?"margin":"border");return _(this,function(t,n,i){var o;return v(t)?0===r.indexOf("outer")?t["inner"+e]:t.document.documentElement["client"+e]:9===t.nodeType?(o=t.documentElement,Math.max(t.body["scroll"+e],o["scroll"+e],t.body["offset"+e],o["offset"+e],o["client"+e])):void 0===i?w.css(t,n,u):w.style(t,n,i,u)},t,a?i:void 0,a)}})}),w.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,t){w.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),w.fn.extend({hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}}),w.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)}}),w.proxy=function(e,t){var n,r,i;if("string"==typeof t&&(n=e[t],t=e,e=n),g(e))return r=o.call(arguments,2),i=function(){return e.apply(t||this,r.concat(o.call(arguments)))},i.guid=e.guid=e.guid||w.guid++,i},w.holdReady=function(e){e?w.readyWait++:w.ready(!0)},w.isArray=Array.isArray,w.parseJSON=JSON.parse,w.nodeName=D,w.isFunction=g,w.isWindow=v,w.camelCase=Q,w.type=b,w.now=Date.now,w.isNumeric=function(e){var t=w.type(e);return("number"===t||"string"===t)&&!isNaN(e-parseFloat(e))},"function"==typeof define&&define.amd&&define("jquery",[],function(){return w});var vt=e.jQuery,yt=e.$;return w.noConflict=function(t){return e.$===w&&(e.$=yt),t&&e.jQuery===w&&(e.jQuery=vt),w},t||(e.jQuery=e.$=w),w}); diff --git a/demos/js/jquery-3.5.1.slim.min.js b/demos/js/jquery-3.5.1.slim.min.js new file mode 100644 index 0000000..36b4e1a --- /dev/null +++ b/demos/js/jquery-3.5.1.slim.min.js @@ -0,0 +1,2 @@ +/*! jQuery v3.5.1 -ajax,-ajax/jsonp,-ajax/load,-ajax/script,-ajax/var/location,-ajax/var/nonce,-ajax/var/rquery,-ajax/xhr,-manipulation/_evalUrl,-deprecated/ajax-event-alias,-effects,-effects/Tween,-effects/animatedSelector | (c) JS Foundation and other contributors | jquery.org/license */ +!function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(g,e){"use strict";var t=[],r=Object.getPrototypeOf,s=t.slice,v=t.flat?function(e){return t.flat.call(e)}:function(e){return t.concat.apply([],e)},u=t.push,i=t.indexOf,n={},o=n.toString,y=n.hasOwnProperty,a=y.toString,l=a.call(Object),m={},b=function(e){return"function"==typeof e&&"number"!=typeof e.nodeType},x=function(e){return null!=e&&e===e.window},w=g.document,c={type:!0,src:!0,nonce:!0,noModule:!0};function C(e,t,n){var r,i,o=(n=n||w).createElement("script");if(o.text=e,t)for(r in c)(i=t[r]||t.getAttribute&&t.getAttribute(r))&&o.setAttribute(r,i);n.head.appendChild(o).parentNode.removeChild(o)}function T(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?n[o.call(e)]||"object":typeof e}var f="3.5.1 -ajax,-ajax/jsonp,-ajax/load,-ajax/script,-ajax/var/location,-ajax/var/nonce,-ajax/var/rquery,-ajax/xhr,-manipulation/_evalUrl,-deprecated/ajax-event-alias,-effects,-effects/Tween,-effects/animatedSelector",E=function(e,t){return new E.fn.init(e,t)};function d(e){var t=!!e&&"length"in e&&e.length,n=T(e);return!b(e)&&!x(e)&&("array"===n||0===t||"number"==typeof t&&0+~]|"+R+")"+R+"*"),U=new RegExp(R+"|>"),V=new RegExp(W),X=new RegExp("^"+B+"$"),Q={ID:new RegExp("^#("+B+")"),CLASS:new RegExp("^\\.("+B+")"),TAG:new RegExp("^("+B+"|[*])"),ATTR:new RegExp("^"+M),PSEUDO:new RegExp("^"+W),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+R+"*(even|odd|(([+-]|)(\\d*)n|)"+R+"*(?:([+-]|)"+R+"*(\\d+)|))"+R+"*\\)|)","i"),bool:new RegExp("^(?:"+I+")$","i"),needsContext:new RegExp("^"+R+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+R+"*((?:-\\d)?\\d*)"+R+"*\\)|)(?=[^-]|$)","i")},Y=/HTML$/i,G=/^(?:input|select|textarea|button)$/i,K=/^h\d$/i,J=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ee=/[+~]/,te=new RegExp("\\\\[\\da-fA-F]{1,6}"+R+"?|\\\\([^\\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(){C()},ae=xe(function(e){return!0===e.disabled&&"fieldset"===e.nodeName.toLowerCase()},{dir:"parentNode",next:"legend"});try{O.apply(t=P.call(d.childNodes),d.childNodes),t[d.childNodes.length].nodeType}catch(e){O={apply:t.length?function(e,t){q.apply(e,P.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,d=e?e.nodeType:9;if(n=n||[],"string"!=typeof t||!t||1!==d&&9!==d&&11!==d)return n;if(!r&&(C(e),e=e||T,E)){if(11!==d&&(u=Z.exec(t)))if(i=u[1]){if(9===d){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 O.apply(n,e.getElementsByTagName(t)),n;if((i=u[3])&&p.getElementsByClassName&&e.getElementsByClassName)return O.apply(n,e.getElementsByClassName(i)),n}if(p.qsa&&!k[t+" "]&&(!v||!v.test(t))&&(1!==d||"object"!==e.nodeName.toLowerCase())){if(c=t,f=e,1===d&&(U.test(t)||_.test(t))){(f=ee.test(t)&&ye(e.parentNode)||e)===e&&p.scope||((s=e.getAttribute("id"))?s=s.replace(re,ie):e.setAttribute("id",s=A)),o=(l=h(t)).length;while(o--)l[o]=(s?"#"+s:":scope")+" "+be(l[o]);c=l.join(",")}try{return O.apply(n,f.querySelectorAll(c)),n}catch(e){k(t,!0)}finally{s===A&&e.removeAttribute("id")}}}return g(t.replace($,"$1"),e,n,r)}function ue(){var r=[];return function e(t,n){return r.push(t+" ")>x.cacheLength&&delete e[r.shift()],e[t+" "]=n}}function le(e){return e[A]=!0,e}function ce(e){var t=T.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--)x.attrHandle[n[r]]=t}function de(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 pe(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 p=se.support={},i=se.isXML=function(e){var t=e.namespaceURI,n=(e.ownerDocument||e).documentElement;return!Y.test(t||n&&n.nodeName||"HTML")},C=se.setDocument=function(e){var t,n,r=e?e.ownerDocument||e:d;return r!=T&&9===r.nodeType&&r.documentElement&&(a=(T=r).documentElement,E=!i(T),d!=T&&(n=T.defaultView)&&n.top!==n&&(n.addEventListener?n.addEventListener("unload",oe,!1):n.attachEvent&&n.attachEvent("onunload",oe)),p.scope=ce(function(e){return a.appendChild(e).appendChild(T.createElement("div")),"undefined"!=typeof e.querySelectorAll&&!e.querySelectorAll(":scope fieldset div").length}),p.attributes=ce(function(e){return e.className="i",!e.getAttribute("className")}),p.getElementsByTagName=ce(function(e){return e.appendChild(T.createComment("")),!e.getElementsByTagName("*").length}),p.getElementsByClassName=J.test(T.getElementsByClassName),p.getById=ce(function(e){return a.appendChild(e).id=A,!T.getElementsByName||!T.getElementsByName(A).length}),p.getById?(x.filter.ID=function(e){var t=e.replace(te,ne);return function(e){return e.getAttribute("id")===t}},x.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n=t.getElementById(e);return n?[n]:[]}}):(x.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}},x.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[]}}),x.find.TAG=p.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):p.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},x.find.CLASS=p.getElementsByClassName&&function(e,t){if("undefined"!=typeof t.getElementsByClassName&&E)return t.getElementsByClassName(e)},s=[],v=[],(p.qsa=J.test(T.querySelectorAll))&&(ce(function(e){var t;a.appendChild(e).innerHTML="",e.querySelectorAll("[msallowcapture^='']").length&&v.push("[*^$]="+R+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||v.push("\\["+R+"*(?:value|"+I+")"),e.querySelectorAll("[id~="+A+"-]").length||v.push("~="),(t=T.createElement("input")).setAttribute("name",""),e.appendChild(t),e.querySelectorAll("[name='']").length||v.push("\\["+R+"*name"+R+"*="+R+"*(?:''|\"\")"),e.querySelectorAll(":checked").length||v.push(":checked"),e.querySelectorAll("a#"+A+"+*").length||v.push(".#.+[+~]"),e.querySelectorAll("\\\f"),v.push("[\\r\\n\\f]")}),ce(function(e){e.innerHTML="";var t=T.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&v.push("name"+R+"*[*^$|!~]?="),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(",.*:")})),(p.matchesSelector=J.test(c=a.matches||a.webkitMatchesSelector||a.mozMatchesSelector||a.oMatchesSelector||a.msMatchesSelector))&&ce(function(e){p.disconnectedMatch=c.call(e,"*"),c.call(e,"[s!='']:x"),s.push("!=",W)}),v=v.length&&new RegExp(v.join("|")),s=s.length&&new RegExp(s.join("|")),t=J.test(a.compareDocumentPosition),y=t||J.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},D=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)||!p.sortDetached&&t.compareDocumentPosition(e)===n?e==T||e.ownerDocument==d&&y(d,e)?-1:t==T||t.ownerDocument==d&&y(d,t)?1:u?H(u,e)-H(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==T?-1:t==T?1:i?-1:o?1:u?H(u,e)-H(u,t):0;if(i===o)return de(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?de(a[r],s[r]):a[r]==d?-1:s[r]==d?1:0}),T},se.matches=function(e,t){return se(e,null,null,t)},se.matchesSelector=function(e,t){if(C(e),p.matchesSelector&&E&&!k[t+" "]&&(!s||!s.test(t))&&(!v||!v.test(t)))try{var n=c.call(e,t);if(n||p.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(e){k(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 Q.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&V.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("(^|"+R+")"+e+"("+R+"|$)"))&&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 D(e,n,r){return b(n)?E.grep(e,function(e,t){return!!n.call(e,t,e)!==r}):n.nodeType?E.grep(e,function(e){return e===n!==r}):"string"!=typeof n?E.grep(e,function(e){return-1)[^>]*|#([\w-]+))$/;(E.fn.init=function(e,t,n){var r,i;if(!e)return this;if(n=n||L,"string"==typeof e){if(!(r="<"===e[0]&&">"===e[e.length-1]&&3<=e.length?[null,e,null]:j.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 E?t[0]:t,E.merge(this,E.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:w,!0)),k.test(r[1])&&E.isPlainObject(t))for(r in t)b(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}return(i=w.getElementById(r[2]))&&(this[0]=i,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):b(e)?void 0!==n.ready?n.ready(e):e(E):E.makeArray(e,this)}).prototype=E.fn,L=E(w);var q=/^(?:parents|prev(?:Until|All))/,O={children:!0,contents:!0,next:!0,prev:!0};function P(e,t){while((e=e[t])&&1!==e.nodeType);return e}E.fn.extend({has:function(e){var t=E(e,this),n=t.length;return this.filter(function(){for(var e=0;e\x20\t\r\n\f]*)/i,pe=/^$|^module$|\/(?:java|ecma)script/i;le=w.createDocumentFragment().appendChild(w.createElement("div")),(ce=w.createElement("input")).setAttribute("type","radio"),ce.setAttribute("checked","checked"),ce.setAttribute("name","t"),le.appendChild(ce),m.checkClone=le.cloneNode(!0).cloneNode(!0).lastChild.checked,le.innerHTML="",m.noCloneChecked=!!le.cloneNode(!0).lastChild.defaultValue,le.innerHTML="",m.option=!!le.lastChild;var he={thead:[1,"","
"],col:[2,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};function ge(e,t){var n;return n="undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t||"*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&S(e,t)?E.merge([e],n):n}function ve(e,t){for(var n=0,r=e.length;n",""]);var ye=/<|&#?\w+;/;function me(e,t,n,r,i){for(var o,a,s,u,l,c,f=t.createDocumentFragment(),d=[],p=0,h=e.length;p\s*$/g;function Le(e,t){return S(e,"table")&&S(11!==t.nodeType?t:t.firstChild,"tr")&&E(e).children("tbody")[0]||e}function je(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 Oe(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
",2===ft.childNodes.length),E.parseHTML=function(e,t,n){return"string"!=typeof e?[]:("boolean"==typeof t&&(n=t,t=!1),t||(m.createHTMLDocument?((r=(t=w.implementation.createHTMLDocument("")).createElement("base")).href=w.location.href,t.head.appendChild(r)):t=w),o=!n&&[],(i=k.exec(e))?[t.createElement(i[1])]:(i=me([e],t,o),o&&o.length&&E(o).remove(),E.merge([],i.childNodes)));var r,i,o},E.offset={setOffset:function(e,t,n){var r,i,o,a,s,u,l=E.css(e,"position"),c=E(e),f={};"static"===l&&(e.style.position="relative"),s=c.offset(),o=E.css(e,"top"),u=E.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),b(t)&&(t=t.call(e,n,E.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):("number"==typeof f.top&&(f.top+="px"),"number"==typeof f.left&&(f.left+="px"),c.css(f))}},E.fn.extend({offset:function(t){if(arguments.length)return void 0===t?this:this.each(function(e){E.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"===E.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"===E.css(e,"position"))e=e.parentNode;e&&e!==r&&1===e.nodeType&&((i=E(e).offset()).top+=E.css(e,"borderTopWidth",!0),i.left+=E.css(e,"borderLeftWidth",!0))}return{top:t.top-i.top-E.css(r,"marginTop",!0),left:t.left-i.left-E.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent;while(e&&"static"===E.css(e,"position"))e=e.offsetParent;return e||re})}}),E.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,i){var o="pageYOffset"===i;E.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)}}),E.each(["top","left"],function(e,n){E.cssHooks[n]=Fe(m.pixelPosition,function(e,t){if(t)return t=We(e,n),Ie.test(t)?E(e).position()[n]+"px":t})}),E.each({Height:"height",Width:"width"},function(a,s){E.each({padding:"inner"+a,content:s,"":"outer"+a},function(r,o){E.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?E.css(e,t,i):E.style(e,t,n,i)},s,n?e:void 0,n)}})}),E.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)}}),E.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){E.fn[n]=function(e,t){return 0=0===n})}function lt(e){var t=ct.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}function Lt(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function At(e,t){if(t.nodeType!==1||!v.hasData(e))return;var n,r,i,s=v._data(e),o=v._data(t,s),u=s.events;if(u){delete o.handle,o.events={};for(n in u)for(r=0,i=u[n].length;r").appendTo(i.body),n=t.css("display");t.remove();if(n==="none"||n===""){Pt=i.body.appendChild(Pt||v.extend(i.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!Ht||!Pt.createElement)Ht=(Pt.contentWindow||Pt.contentDocument).document,Ht.write(""),Ht.close();t=Ht.body.appendChild(Ht.createElement(e)),n=Dt(t,"display"),i.body.removeChild(Pt)}return Wt[e]=n,n}function fn(e,t,n,r){var i;if(v.isArray(t))v.each(t,function(t,i){n||sn.test(e)?r(e,i):fn(e+"["+(typeof i=="object"?t:"")+"]",i,n,r)});else if(!n&&v.type(t)==="object")for(i in t)fn(e+"["+i+"]",t[i],n,r);else r(e,t)}function Cn(e){return function(t,n){typeof t!="string"&&(n=t,t="*");var r,i,s,o=t.toLowerCase().split(y),u=0,a=o.length;if(v.isFunction(n))for(;u)[^>]*$|#([\w\-]*)$)/,E=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,S=/^[\],:{}\s]*$/,x=/(?:^|:|,)(?:\s*\[)+/g,T=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,N=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,C=/^-ms-/,k=/-([\da-z])/gi,L=function(e,t){return(t+"").toUpperCase()},A=function(){i.addEventListener?(i.removeEventListener("DOMContentLoaded",A,!1),v.ready()):i.readyState==="complete"&&(i.detachEvent("onreadystatechange",A),v.ready())},O={};v.fn=v.prototype={constructor:v,init:function(e,n,r){var s,o,u,a;if(!e)return this;if(e.nodeType)return this.context=this[0]=e,this.length=1,this;if(typeof e=="string"){e.charAt(0)==="<"&&e.charAt(e.length-1)===">"&&e.length>=3?s=[null,e,null]:s=w.exec(e);if(s&&(s[1]||!n)){if(s[1])return n=n instanceof v?n[0]:n,a=n&&n.nodeType?n.ownerDocument||n:i,e=v.parseHTML(s[1],a,!0),E.test(s[1])&&v.isPlainObject(n)&&this.attr.call(e,n,!0),v.merge(this,e);o=i.getElementById(s[2]);if(o&&o.parentNode){if(o.id!==s[2])return r.find(e);this.length=1,this[0]=o}return this.context=i,this.selector=e,this}return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e)}return v.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),v.makeArray(e,this))},selector:"",jquery:"1.8.3",length:0,size:function(){return this.length},toArray:function(){return l.call(this)},get:function(e){return e==null?this.toArray():e<0?this[this.length+e]:this[e]},pushStack:function(e,t,n){var r=v.merge(this.constructor(),e);return r.prevObject=this,r.context=this.context,t==="find"?r.selector=this.selector+(this.selector?" ":"")+n:t&&(r.selector=this.selector+"."+t+"("+n+")"),r},each:function(e,t){return v.each(this,e,t)},ready:function(e){return v.ready.promise().done(e),this},eq:function(e){return e=+e,e===-1?this.slice(e):this.slice(e,e+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(l.apply(this,arguments),"slice",l.call(arguments).join(","))},map:function(e){return this.pushStack(v.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:[].sort,splice:[].splice},v.fn.init.prototype=v.fn,v.extend=v.fn.extend=function(){var e,n,r,i,s,o,u=arguments[0]||{},a=1,f=arguments.length,l=!1;typeof u=="boolean"&&(l=u,u=arguments[1]||{},a=2),typeof u!="object"&&!v.isFunction(u)&&(u={}),f===a&&(u=this,--a);for(;a0)return;r.resolveWith(i,[v]),v.fn.trigger&&v(i).trigger("ready").off("ready")},isFunction:function(e){return v.type(e)==="function"},isArray:Array.isArray||function(e){return v.type(e)==="array"},isWindow:function(e){return e!=null&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return e==null?String(e):O[h.call(e)]||"object"},isPlainObject:function(e){if(!e||v.type(e)!=="object"||e.nodeType||v.isWindow(e))return!1;try{if(e.constructor&&!p.call(e,"constructor")&&!p.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||p.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw new Error(e)},parseHTML:function(e,t,n){var r;return!e||typeof e!="string"?null:(typeof t=="boolean"&&(n=t,t=0),t=t||i,(r=E.exec(e))?[t.createElement(r[1])]:(r=v.buildFragment([e],t,n?null:[]),v.merge([],(r.cacheable?v.clone(r.fragment):r.fragment).childNodes)))},parseJSON:function(t){if(!t||typeof t!="string")return null;t=v.trim(t);if(e.JSON&&e.JSON.parse)return e.JSON.parse(t);if(S.test(t.replace(T,"@").replace(N,"]").replace(x,"")))return(new Function("return "+t))();v.error("Invalid JSON: "+t)},parseXML:function(n){var r,i;if(!n||typeof n!="string")return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(s){r=t}return(!r||!r.documentElement||r.getElementsByTagName("parsererror").length)&&v.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&g.test(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(C,"ms-").replace(k,L)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,n,r){var i,s=0,o=e.length,u=o===t||v.isFunction(e);if(r){if(u){for(i in e)if(n.apply(e[i],r)===!1)break}else for(;s0&&e[0]&&e[a-1]||a===0||v.isArray(e));if(f)for(;u-1)a.splice(n,1),i&&(n<=o&&o--,n<=u&&u--)}),this},has:function(e){return v.inArray(e,a)>-1},empty:function(){return a=[],this},disable:function(){return a=f=n=t,this},disabled:function(){return!a},lock:function(){return f=t,n||c.disable(),this},locked:function(){return!f},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],a&&(!r||f)&&(i?f.push(t):l(t)),this},fire:function(){return c.fireWith(this,arguments),this},fired:function(){return!!r}};return c},v.extend({Deferred:function(e){var t=[["resolve","done",v.Callbacks("once memory"),"resolved"],["reject","fail",v.Callbacks("once memory"),"rejected"],["notify","progress",v.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return v.Deferred(function(n){v.each(t,function(t,r){var s=r[0],o=e[t];i[r[1]](v.isFunction(o)?function(){var e=o.apply(this,arguments);e&&v.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[s+"With"](this===i?n:this,[e])}:n[s])}),e=null}).promise()},promise:function(e){return e!=null?v.extend(e,r):r}},i={};return r.pipe=r.then,v.each(t,function(e,s){var o=s[2],u=s[3];r[s[1]]=o.add,u&&o.add(function(){n=u},t[e^1][2].disable,t[2][2].lock),i[s[0]]=o.fire,i[s[0]+"With"]=o.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=l.call(arguments),r=n.length,i=r!==1||e&&v.isFunction(e.promise)?r:0,s=i===1?e:v.Deferred(),o=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?l.call(arguments):r,n===u?s.notifyWith(t,n):--i||s.resolveWith(t,n)}},u,a,f;if(r>1){u=new Array(r),a=new Array(r),f=new Array(r);for(;t
a",n=p.getElementsByTagName("*"),r=p.getElementsByTagName("a")[0];if(!n||!r||!n.length)return{};s=i.createElement("select"),o=s.appendChild(i.createElement("option")),u=p.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={leadingWhitespace:p.firstChild.nodeType===3,tbody:!p.getElementsByTagName("tbody").length,htmlSerialize:!!p.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:r.getAttribute("href")==="/a",opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:u.value==="on",optSelected:o.selected,getSetAttribute:p.className!=="t",enctype:!!i.createElement("form").enctype,html5Clone:i.createElement("nav").cloneNode(!0).outerHTML!=="<:nav>",boxModel:i.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},u.checked=!0,t.noCloneChecked=u.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!o.disabled;try{delete p.test}catch(d){t.deleteExpando=!1}!p.addEventListener&&p.attachEvent&&p.fireEvent&&(p.attachEvent("onclick",h=function(){t.noCloneEvent=!1}),p.cloneNode(!0).fireEvent("onclick"),p.detachEvent("onclick",h)),u=i.createElement("input"),u.value="t",u.setAttribute("type","radio"),t.radioValue=u.value==="t",u.setAttribute("checked","checked"),u.setAttribute("name","t"),p.appendChild(u),a=i.createDocumentFragment(),a.appendChild(p.lastChild),t.checkClone=a.cloneNode(!0).cloneNode(!0).lastChild.checked,t.appendChecked=u.checked,a.removeChild(u),a.appendChild(p);if(p.attachEvent)for(l in{submit:!0,change:!0,focusin:!0})f="on"+l,c=f in p,c||(p.setAttribute(f,"return;"),c=typeof p[f]=="function"),t[l+"Bubbles"]=c;return v(function(){var n,r,s,o,u="padding:0;margin:0;border:0;display:block;overflow:hidden;",a=i.getElementsByTagName("body")[0];if(!a)return;n=i.createElement("div"),n.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",a.insertBefore(n,a.firstChild),r=i.createElement("div"),n.appendChild(r),r.innerHTML="
t
",s=r.getElementsByTagName("td"),s[0].style.cssText="padding:0;margin:0;border:0;display:none",c=s[0].offsetHeight===0,s[0].style.display="",s[1].style.display="none",t.reliableHiddenOffsets=c&&s[0].offsetHeight===0,r.innerHTML="",r.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",t.boxSizing=r.offsetWidth===4,t.doesNotIncludeMarginInBodyOffset=a.offsetTop!==1,e.getComputedStyle&&(t.pixelPosition=(e.getComputedStyle(r,null)||{}).top!=="1%",t.boxSizingReliable=(e.getComputedStyle(r,null)||{width:"4px"}).width==="4px",o=i.createElement("div"),o.style.cssText=r.style.cssText=u,o.style.marginRight=o.style.width="0",r.style.width="1px",r.appendChild(o),t.reliableMarginRight=!parseFloat((e.getComputedStyle(o,null)||{}).marginRight)),typeof r.style.zoom!="undefined"&&(r.innerHTML="",r.style.cssText=u+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=r.offsetWidth===3,r.style.display="block",r.style.overflow="visible",r.innerHTML="
",r.firstChild.style.width="5px",t.shrinkWrapBlocks=r.offsetWidth!==3,n.style.zoom=1),a.removeChild(n),n=r=s=o=null}),a.removeChild(p),n=r=s=o=u=a=p=null,t}();var D=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,P=/([A-Z])/g;v.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(v.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?v.cache[e[v.expando]]:e[v.expando],!!e&&!B(e)},data:function(e,n,r,i){if(!v.acceptData(e))return;var s,o,u=v.expando,a=typeof n=="string",f=e.nodeType,l=f?v.cache:e,c=f?e[u]:e[u]&&u;if((!c||!l[c]||!i&&!l[c].data)&&a&&r===t)return;c||(f?e[u]=c=v.deletedIds.pop()||v.guid++:c=u),l[c]||(l[c]={},f||(l[c].toJSON=v.noop));if(typeof n=="object"||typeof n=="function")i?l[c]=v.extend(l[c],n):l[c].data=v.extend(l[c].data,n);return s=l[c],i||(s.data||(s.data={}),s=s.data),r!==t&&(s[v.camelCase(n)]=r),a?(o=s[n],o==null&&(o=s[v.camelCase(n)])):o=s,o},removeData:function(e,t,n){if(!v.acceptData(e))return;var r,i,s,o=e.nodeType,u=o?v.cache:e,a=o?e[v.expando]:v.expando;if(!u[a])return;if(t){r=n?u[a]:u[a].data;if(r){v.isArray(t)||(t in r?t=[t]:(t=v.camelCase(t),t in r?t=[t]:t=t.split(" ")));for(i=0,s=t.length;i1,null,!1))},removeData:function(e){return this.each(function(){v.removeData(this,e)})}}),v.extend({queue:function(e,t,n){var r;if(e)return t=(t||"fx")+"queue",r=v._data(e,t),n&&(!r||v.isArray(n)?r=v._data(e,t,v.makeArray(n)):r.push(n)),r||[]},dequeue:function(e,t){t=t||"fx";var n=v.queue(e,t),r=n.length,i=n.shift(),s=v._queueHooks(e,t),o=function(){v.dequeue(e,t)};i==="inprogress"&&(i=n.shift(),r--),i&&(t==="fx"&&n.unshift("inprogress"),delete s.stop,i.call(e,o,s)),!r&&s&&s.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return v._data(e,n)||v._data(e,n,{empty:v.Callbacks("once memory").add(function(){v.removeData(e,t+"queue",!0),v.removeData(e,n,!0)})})}}),v.fn.extend({queue:function(e,n){var r=2;return typeof e!="string"&&(n=e,e="fx",r--),arguments.length1)},removeAttr:function(e){return this.each(function(){v.removeAttr(this,e)})},prop:function(e,t){return v.access(this,v.prop,e,t,arguments.length>1)},removeProp:function(e){return e=v.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,s,o,u;if(v.isFunction(e))return this.each(function(t){v(this).addClass(e.call(this,t,this.className))});if(e&&typeof e=="string"){t=e.split(y);for(n=0,r=this.length;n=0)r=r.replace(" "+n[s]+" "," ");i.className=e?v.trim(r):""}}}return this},toggleClass:function(e,t){var n=typeof e,r=typeof t=="boolean";return v.isFunction(e)?this.each(function(n){v(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if(n==="string"){var i,s=0,o=v(this),u=t,a=e.split(y);while(i=a[s++])u=r?u:!o.hasClass(i),o[u?"addClass":"removeClass"](i)}else if(n==="undefined"||n==="boolean")this.className&&v._data(this,"__className__",this.className),this.className=this.className||e===!1?"":v._data(this,"__className__")||""})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;n=0)return!0;return!1},val:function(e){var n,r,i,s=this[0];if(!arguments.length){if(s)return n=v.valHooks[s.type]||v.valHooks[s.nodeName.toLowerCase()],n&&"get"in n&&(r=n.get(s,"value"))!==t?r:(r=s.value,typeof r=="string"?r.replace(R,""):r==null?"":r);return}return i=v.isFunction(e),this.each(function(r){var s,o=v(this);if(this.nodeType!==1)return;i?s=e.call(this,r,o.val()):s=e,s==null?s="":typeof s=="number"?s+="":v.isArray(s)&&(s=v.map(s,function(e){return e==null?"":e+""})),n=v.valHooks[this.type]||v.valHooks[this.nodeName.toLowerCase()];if(!n||!("set"in n)||n.set(this,s,"value")===t)this.value=s})}}),v.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,s=e.type==="select-one"||i<0,o=s?null:[],u=s?i+1:r.length,a=i<0?u:s?i:0;for(;a=0}),n.length||(e.selectedIndex=-1),n}}},attrFn:{},attr:function(e,n,r,i){var s,o,u,a=e.nodeType;if(!e||a===3||a===8||a===2)return;if(i&&v.isFunction(v.fn[n]))return v(e)[n](r);if(typeof e.getAttribute=="undefined")return v.prop(e,n,r);u=a!==1||!v.isXMLDoc(e),u&&(n=n.toLowerCase(),o=v.attrHooks[n]||(X.test(n)?F:j));if(r!==t){if(r===null){v.removeAttr(e,n);return}return o&&"set"in o&&u&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,r+""),r)}return o&&"get"in o&&u&&(s=o.get(e,n))!==null?s:(s=e.getAttribute(n),s===null?t:s)},removeAttr:function(e,t){var n,r,i,s,o=0;if(t&&e.nodeType===1){r=t.split(y);for(;o=0}})});var $=/^(?:textarea|input|select)$/i,J=/^([^\.]*|)(?:\.(.+)|)$/,K=/(?:^|\s)hover(\.\S+|)\b/,Q=/^key/,G=/^(?:mouse|contextmenu)|click/,Y=/^(?:focusinfocus|focusoutblur)$/,Z=function(e){return v.event.special.hover?e:e.replace(K,"mouseenter$1 mouseleave$1")};v.event={add:function(e,n,r,i,s){var o,u,a,f,l,c,h,p,d,m,g;if(e.nodeType===3||e.nodeType===8||!n||!r||!(o=v._data(e)))return;r.handler&&(d=r,r=d.handler,s=d.selector),r.guid||(r.guid=v.guid++),a=o.events,a||(o.events=a={}),u=o.handle,u||(o.handle=u=function(e){return typeof v=="undefined"||!!e&&v.event.triggered===e.type?t:v.event.dispatch.apply(u.elem,arguments)},u.elem=e),n=v.trim(Z(n)).split(" ");for(f=0;f=0&&(y=y.slice(0,-1),a=!0),y.indexOf(".")>=0&&(b=y.split("."),y=b.shift(),b.sort());if((!s||v.event.customEvent[y])&&!v.event.global[y])return;n=typeof n=="object"?n[v.expando]?n:new v.Event(y,n):new v.Event(y),n.type=y,n.isTrigger=!0,n.exclusive=a,n.namespace=b.join("."),n.namespace_re=n.namespace?new RegExp("(^|\\.)"+b.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,h=y.indexOf(":")<0?"on"+y:"";if(!s){u=v.cache;for(f in u)u[f].events&&u[f].events[y]&&v.event.trigger(n,r,u[f].handle.elem,!0);return}n.result=t,n.target||(n.target=s),r=r!=null?v.makeArray(r):[],r.unshift(n),p=v.event.special[y]||{};if(p.trigger&&p.trigger.apply(s,r)===!1)return;m=[[s,p.bindType||y]];if(!o&&!p.noBubble&&!v.isWindow(s)){g=p.delegateType||y,l=Y.test(g+y)?s:s.parentNode;for(c=s;l;l=l.parentNode)m.push([l,g]),c=l;c===(s.ownerDocument||i)&&m.push([c.defaultView||c.parentWindow||e,g])}for(f=0;f=0:v.find(h,this,null,[s]).length),u[h]&&f.push(c);f.length&&w.push({elem:s,matches:f})}d.length>m&&w.push({elem:this,matches:d.slice(m)});for(r=0;r0?this.on(t,null,e,n):this.trigger(t)},Q.test(t)&&(v.event.fixHooks[t]=v.event.keyHooks),G.test(t)&&(v.event.fixHooks[t]=v.event.mouseHooks)}),function(e,t){function nt(e,t,n,r){n=n||[],t=t||g;var i,s,a,f,l=t.nodeType;if(!e||typeof e!="string")return n;if(l!==1&&l!==9)return[];a=o(t);if(!a&&!r)if(i=R.exec(e))if(f=i[1]){if(l===9){s=t.getElementById(f);if(!s||!s.parentNode)return n;if(s.id===f)return n.push(s),n}else if(t.ownerDocument&&(s=t.ownerDocument.getElementById(f))&&u(t,s)&&s.id===f)return n.push(s),n}else{if(i[2])return S.apply(n,x.call(t.getElementsByTagName(e),0)),n;if((f=i[3])&&Z&&t.getElementsByClassName)return S.apply(n,x.call(t.getElementsByClassName(f),0)),n}return vt(e.replace(j,"$1"),t,n,r,a)}function rt(e){return function(t){var n=t.nodeName.toLowerCase();return n==="input"&&t.type===e}}function it(e){return function(t){var n=t.nodeName.toLowerCase();return(n==="input"||n==="button")&&t.type===e}}function st(e){return N(function(t){return t=+t,N(function(n,r){var i,s=e([],n.length,t),o=s.length;while(o--)n[i=s[o]]&&(n[i]=!(r[i]=n[i]))})})}function ot(e,t,n){if(e===t)return n;var r=e.nextSibling;while(r){if(r===t)return-1;r=r.nextSibling}return 1}function ut(e,t){var n,r,s,o,u,a,f,l=L[d][e+" "];if(l)return t?0:l.slice(0);u=e,a=[],f=i.preFilter;while(u){if(!n||(r=F.exec(u)))r&&(u=u.slice(r[0].length)||u),a.push(s=[]);n=!1;if(r=I.exec(u))s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=r[0].replace(j," ");for(o in i.filter)(r=J[o].exec(u))&&(!f[o]||(r=f[o](r)))&&(s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=o,n.matches=r);if(!n)break}return t?u.length:u?nt.error(e):L(e,a).slice(0)}function at(e,t,r){var i=t.dir,s=r&&t.dir==="parentNode",o=w++;return t.first?function(t,n,r){while(t=t[i])if(s||t.nodeType===1)return e(t,n,r)}:function(t,r,u){if(!u){var a,f=b+" "+o+" ",l=f+n;while(t=t[i])if(s||t.nodeType===1){if((a=t[d])===l)return t.sizset;if(typeof a=="string"&&a.indexOf(f)===0){if(t.sizset)return t}else{t[d]=l;if(e(t,r,u))return t.sizset=!0,t;t.sizset=!1}}}else while(t=t[i])if(s||t.nodeType===1)if(e(t,r,u))return t}}function ft(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function lt(e,t,n,r,i){var s,o=[],u=0,a=e.length,f=t!=null;for(;u-1&&(s[f]=!(o[f]=c))}}else g=lt(g===o?g.splice(d,g.length):g),i?i(null,o,g,a):S.apply(o,g)})}function ht(e){var t,n,r,s=e.length,o=i.relative[e[0].type],u=o||i.relative[" "],a=o?1:0,f=at(function(e){return e===t},u,!0),l=at(function(e){return T.call(t,e)>-1},u,!0),h=[function(e,n,r){return!o&&(r||n!==c)||((t=n).nodeType?f(e,n,r):l(e,n,r))}];for(;a1&&ft(h),a>1&&e.slice(0,a-1).join("").replace(j,"$1"),n,a0,s=e.length>0,o=function(u,a,f,l,h){var p,d,v,m=[],y=0,w="0",x=u&&[],T=h!=null,N=c,C=u||s&&i.find.TAG("*",h&&a.parentNode||a),k=b+=N==null?1:Math.E;T&&(c=a!==g&&a,n=o.el);for(;(p=C[w])!=null;w++){if(s&&p){for(d=0;v=e[d];d++)if(v(p,a,f)){l.push(p);break}T&&(b=k,n=++o.el)}r&&((p=!v&&p)&&y--,u&&x.push(p))}y+=w;if(r&&w!==y){for(d=0;v=t[d];d++)v(x,m,a,f);if(u){if(y>0)while(w--)!x[w]&&!m[w]&&(m[w]=E.call(l));m=lt(m)}S.apply(l,m),T&&!u&&m.length>0&&y+t.length>1&&nt.uniqueSort(l)}return T&&(b=k,c=N),x};return o.el=0,r?N(o):o}function dt(e,t,n){var r=0,i=t.length;for(;r2&&(f=u[0]).type==="ID"&&t.nodeType===9&&!s&&i.relative[u[1].type]){t=i.find.ID(f.matches[0].replace($,""),t,s)[0];if(!t)return n;e=e.slice(u.shift().length)}for(o=J.POS.test(e)?-1:u.length-1;o>=0;o--){f=u[o];if(i.relative[l=f.type])break;if(c=i.find[l])if(r=c(f.matches[0].replace($,""),z.test(u[0].type)&&t.parentNode||t,s)){u.splice(o,1),e=r.length&&u.join("");if(!e)return S.apply(n,x.call(r,0)),n;break}}}return a(e,h)(r,t,s,n,z.test(e)),n}function mt(){}var n,r,i,s,o,u,a,f,l,c,h=!0,p="undefined",d=("sizcache"+Math.random()).replace(".",""),m=String,g=e.document,y=g.documentElement,b=0,w=0,E=[].pop,S=[].push,x=[].slice,T=[].indexOf||function(e){var t=0,n=this.length;for(;ti.cacheLength&&delete e[t.shift()],e[n+" "]=r},e)},k=C(),L=C(),A=C(),O="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",_=M.replace("w","w#"),D="([*^$|!~]?=)",P="\\["+O+"*("+M+")"+O+"*(?:"+D+O+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+_+")|)|)"+O+"*\\]",H=":("+M+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:"+P+")|[^:]|\\\\.)*|.*))\\)|)",B=":(even|odd|eq|gt|lt|nth|first|last)(?:\\("+O+"*((?:-\\d)?\\d*)"+O+"*\\)|)(?=[^-]|$)",j=new RegExp("^"+O+"+|((?:^|[^\\\\])(?:\\\\.)*)"+O+"+$","g"),F=new RegExp("^"+O+"*,"+O+"*"),I=new RegExp("^"+O+"*([\\x20\\t\\r\\n\\f>+~])"+O+"*"),q=new RegExp(H),R=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,U=/^:not/,z=/[\x20\t\r\n\f]*[+~]/,W=/:not\($/,X=/h\d/i,V=/input|select|textarea|button/i,$=/\\(?!\\)/g,J={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),NAME:new RegExp("^\\[name=['\"]?("+M+")['\"]?\\]"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+H),POS:new RegExp(B,"i"),CHILD:new RegExp("^:(only|nth|first|last)-child(?:\\("+O+"*(even|odd|(([+-]|)(\\d*)n|)"+O+"*(?:([+-]|)"+O+"*(\\d+)|))"+O+"*\\)|)","i"),needsContext:new RegExp("^"+O+"*[>+~]|"+B,"i")},K=function(e){var t=g.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}},Q=K(function(e){return e.appendChild(g.createComment("")),!e.getElementsByTagName("*").length}),G=K(function(e){return e.innerHTML="",e.firstChild&&typeof e.firstChild.getAttribute!==p&&e.firstChild.getAttribute("href")==="#"}),Y=K(function(e){e.innerHTML="";var t=typeof e.lastChild.getAttribute("multiple");return t!=="boolean"&&t!=="string"}),Z=K(function(e){return e.innerHTML="",!e.getElementsByClassName||!e.getElementsByClassName("e").length?!1:(e.lastChild.className="e",e.getElementsByClassName("e").length===2)}),et=K(function(e){e.id=d+0,e.innerHTML="
",y.insertBefore(e,y.firstChild);var t=g.getElementsByName&&g.getElementsByName(d).length===2+g.getElementsByName(d+0).length;return r=!g.getElementById(d),y.removeChild(e),t});try{x.call(y.childNodes,0)[0].nodeType}catch(tt){x=function(e){var t,n=[];for(;t=this[e];e++)n.push(t);return n}}nt.matches=function(e,t){return nt(e,null,null,t)},nt.matchesSelector=function(e,t){return nt(t,null,null,[e]).length>0},s=nt.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(i===1||i===9||i===11){if(typeof e.textContent=="string")return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=s(e)}else if(i===3||i===4)return e.nodeValue}else for(;t=e[r];r++)n+=s(t);return n},o=nt.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?t.nodeName!=="HTML":!1},u=nt.contains=y.contains?function(e,t){var n=e.nodeType===9?e.documentElement:e,r=t&&t.parentNode;return e===r||!!(r&&r.nodeType===1&&n.contains&&n.contains(r))}:y.compareDocumentPosition?function(e,t){return t&&!!(e.compareDocumentPosition(t)&16)}:function(e,t){while(t=t.parentNode)if(t===e)return!0;return!1},nt.attr=function(e,t){var n,r=o(e);return r||(t=t.toLowerCase()),(n=i.attrHandle[t])?n(e):r||Y?e.getAttribute(t):(n=e.getAttributeNode(t),n?typeof e[t]=="boolean"?e[t]?t:null:n.specified?n.value:null:null)},i=nt.selectors={cacheLength:50,createPseudo:N,match:J,attrHandle:G?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},find:{ID:r?function(e,t,n){if(typeof t.getElementById!==p&&!n){var r=t.getElementById(e);return r&&r.parentNode?[r]:[]}}:function(e,n,r){if(typeof n.getElementById!==p&&!r){var i=n.getElementById(e);return i?i.id===e||typeof i.getAttributeNode!==p&&i.getAttributeNode("id").value===e?[i]:t:[]}},TAG:Q?function(e,t){if(typeof t.getElementsByTagName!==p)return t.getElementsByTagName(e)}:function(e,t){var n=t.getElementsByTagName(e);if(e==="*"){var r,i=[],s=0;for(;r=n[s];s++)r.nodeType===1&&i.push(r);return i}return n},NAME:et&&function(e,t){if(typeof t.getElementsByName!==p)return t.getElementsByName(name)},CLASS:Z&&function(e,t,n){if(typeof t.getElementsByClassName!==p&&!n)return t.getElementsByClassName(e)}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace($,""),e[3]=(e[4]||e[5]||"").replace($,""),e[2]==="~="&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),e[1]==="nth"?(e[2]||nt.error(e[0]),e[3]=+(e[3]?e[4]+(e[5]||1):2*(e[2]==="even"||e[2]==="odd")),e[4]=+(e[6]+e[7]||e[2]==="odd")):e[2]&&nt.error(e[0]),e},PSEUDO:function(e){var t,n;if(J.CHILD.test(e[0]))return null;if(e[3])e[2]=e[3];else if(t=e[4])q.test(t)&&(n=ut(t,!0))&&(n=t.indexOf(")",t.length-n)-t.length)&&(t=t.slice(0,n),e[0]=e[0].slice(0,n)),e[2]=t;return e.slice(0,3)}},filter:{ID:r?function(e){return e=e.replace($,""),function(t){return t.getAttribute("id")===e}}:function(e){return e=e.replace($,""),function(t){var n=typeof t.getAttributeNode!==p&&t.getAttributeNode("id");return n&&n.value===e}},TAG:function(e){return e==="*"?function(){return!0}:(e=e.replace($,"").toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=k[d][e+" "];return t||(t=new RegExp("(^|"+O+")"+e+"("+O+"|$)"))&&k(e,function(e){return t.test(e.className||typeof e.getAttribute!==p&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r,i){var s=nt.attr(r,e);return s==null?t==="!=":t?(s+="",t==="="?s===n:t==="!="?s!==n:t==="^="?n&&s.indexOf(n)===0:t==="*="?n&&s.indexOf(n)>-1:t==="$="?n&&s.substr(s.length-n.length)===n:t==="~="?(" "+s+" ").indexOf(n)>-1:t==="|="?s===n||s.substr(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r){return e==="nth"?function(e){var t,i,s=e.parentNode;if(n===1&&r===0)return!0;if(s){i=0;for(t=s.firstChild;t;t=t.nextSibling)if(t.nodeType===1){i++;if(e===t)break}}return i-=r,i===n||i%n===0&&i/n>=0}:function(t){var n=t;switch(e){case"only":case"first":while(n=n.previousSibling)if(n.nodeType===1)return!1;if(e==="first")return!0;n=t;case"last":while(n=n.nextSibling)if(n.nodeType===1)return!1;return!0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||nt.error("unsupported pseudo: "+e);return r[d]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?N(function(e,n){var i,s=r(e,t),o=s.length;while(o--)i=T.call(e,s[o]),e[i]=!(n[i]=s[o])}):function(e){return r(e,0,n)}):r}},pseudos:{not:N(function(e){var t=[],n=[],r=a(e.replace(j,"$1"));return r[d]?N(function(e,t,n,i){var s,o=r(e,null,i,[]),u=e.length;while(u--)if(s=o[u])e[u]=!(t[u]=s)}):function(e,i,s){return t[0]=e,r(t,null,s,n),!n.pop()}}),has:N(function(e){return function(t){return nt(e,t).length>0}}),contains:N(function(e){return function(t){return(t.textContent||t.innerText||s(t)).indexOf(e)>-1}}),enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&!!e.checked||t==="option"&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},parent:function(e){return!i.pseudos.empty(e)},empty:function(e){var t;e=e.firstChild;while(e){if(e.nodeName>"@"||(t=e.nodeType)===3||t===4)return!1;e=e.nextSibling}return!0},header:function(e){return X.test(e.nodeName)},text:function(e){var t,n;return e.nodeName.toLowerCase()==="input"&&(t=e.type)==="text"&&((n=e.getAttribute("type"))==null||n.toLowerCase()===t)},radio:rt("radio"),checkbox:rt("checkbox"),file:rt("file"),password:rt("password"),image:rt("image"),submit:it("submit"),reset:it("reset"),button:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&e.type==="button"||t==="button"},input:function(e){return V.test(e.nodeName)},focus:function(e){var t=e.ownerDocument;return e===t.activeElement&&(!t.hasFocus||t.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},active:function(e){return e===e.ownerDocument.activeElement},first:st(function(){return[0]}),last:st(function(e,t){return[t-1]}),eq:st(function(e,t,n){return[n<0?n+t:n]}),even:st(function(e,t){for(var n=0;n=0;)e.push(r);return e}),gt:st(function(e,t,n){for(var r=n<0?n+t:n;++r",e.querySelectorAll("[selected]").length||i.push("\\["+O+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||i.push(":checked")}),K(function(e){e.innerHTML="

",e.querySelectorAll("[test^='']").length&&i.push("[*^$]="+O+"*(?:\"\"|'')"),e.innerHTML="",e.querySelectorAll(":enabled").length||i.push(":enabled",":disabled")}),i=new RegExp(i.join("|")),vt=function(e,r,s,o,u){if(!o&&!u&&!i.test(e)){var a,f,l=!0,c=d,h=r,p=r.nodeType===9&&e;if(r.nodeType===1&&r.nodeName.toLowerCase()!=="object"){a=ut(e),(l=r.getAttribute("id"))?c=l.replace(n,"\\$&"):r.setAttribute("id",c),c="[id='"+c+"'] ",f=a.length;while(f--)a[f]=c+a[f].join("");h=z.test(e)&&r.parentNode||r,p=a.join(",")}if(p)try{return S.apply(s,x.call(h.querySelectorAll(p),0)),s}catch(v){}finally{l||r.removeAttribute("id")}}return t(e,r,s,o,u)},u&&(K(function(t){e=u.call(t,"div");try{u.call(t,"[test!='']:sizzle"),s.push("!=",H)}catch(n){}}),s=new RegExp(s.join("|")),nt.matchesSelector=function(t,n){n=n.replace(r,"='$1']");if(!o(t)&&!s.test(n)&&!i.test(n))try{var a=u.call(t,n);if(a||e||t.document&&t.document.nodeType!==11)return a}catch(f){}return nt(n,null,null,[t]).length>0})}(),i.pseudos.nth=i.pseudos.eq,i.filters=mt.prototype=i.pseudos,i.setFilters=new mt,nt.attr=v.attr,v.find=nt,v.expr=nt.selectors,v.expr[":"]=v.expr.pseudos,v.unique=nt.uniqueSort,v.text=nt.getText,v.isXMLDoc=nt.isXML,v.contains=nt.contains}(e);var nt=/Until$/,rt=/^(?:parents|prev(?:Until|All))/,it=/^.[^:#\[\.,]*$/,st=v.expr.match.needsContext,ot={children:!0,contents:!0,next:!0,prev:!0};v.fn.extend({find:function(e){var t,n,r,i,s,o,u=this;if(typeof e!="string")return v(e).filter(function(){for(t=0,n=u.length;t0)for(i=r;i=0:v.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,s=[],o=st.test(e)||typeof e!="string"?v(e,t||this.context):0;for(;r-1:v.find.matchesSelector(n,e)){s.push(n);break}n=n.parentNode}}return s=s.length>1?v.unique(s):s,this.pushStack(s,"closest",e)},index:function(e){return e?typeof e=="string"?v.inArray(this[0],v(e)):v.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(e,t){var n=typeof e=="string"?v(e,t):v.makeArray(e&&e.nodeType?[e]:e),r=v.merge(this.get(),n);return this.pushStack(ut(n[0])||ut(r[0])?r:v.unique(r))},addBack:function(e){return this.add(e==null?this.prevObject:this.prevObject.filter(e))}}),v.fn.andSelf=v.fn.addBack,v.each({parent:function(e){var t=e.parentNode;return t&&t.nodeType!==11?t:null},parents:function(e){return v.dir(e,"parentNode")},parentsUntil:function(e,t,n){return v.dir(e,"parentNode",n)},next:function(e){return at(e,"nextSibling")},prev:function(e){return at(e,"previousSibling")},nextAll:function(e){return v.dir(e,"nextSibling")},prevAll:function(e){return v.dir(e,"previousSibling")},nextUntil:function(e,t,n){return v.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return v.dir(e,"previousSibling",n)},siblings:function(e){return v.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return v.sibling(e.firstChild)},contents:function(e){return v.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:v.merge([],e.childNodes)}},function(e,t){v.fn[e]=function(n,r){var i=v.map(this,t,n);return nt.test(e)||(r=n),r&&typeof r=="string"&&(i=v.filter(r,i)),i=this.length>1&&!ot[e]?v.unique(i):i,this.length>1&&rt.test(e)&&(i=i.reverse()),this.pushStack(i,e,l.call(arguments).join(","))}}),v.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),t.length===1?v.find.matchesSelector(t[0],e)?[t[0]]:[]:v.find.matches(e,t)},dir:function(e,n,r){var i=[],s=e[n];while(s&&s.nodeType!==9&&(r===t||s.nodeType!==1||!v(s).is(r)))s.nodeType===1&&i.push(s),s=s[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)e.nodeType===1&&e!==t&&n.push(e);return n}});var ct="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",ht=/ jQuery\d+="(?:null|\d+)"/g,pt=/^\s+/,dt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,vt=/<([\w:]+)/,mt=/]","i"),Et=/^(?:checkbox|radio)$/,St=/checked\s*(?:[^=]|=\s*.checked.)/i,xt=/\/(java|ecma)script/i,Tt=/^\s*\s*$/g,Nt={option:[1,""],legend:[1,"
","
"],thead:[1,"","
"],tr:[2,"","
"],td:[3,"","
"],col:[2,"","
"],area:[1,"",""],_default:[0,"",""]},Ct=lt(i),kt=Ct.appendChild(i.createElement("div"));Nt.optgroup=Nt.option,Nt.tbody=Nt.tfoot=Nt.colgroup=Nt.caption=Nt.thead,Nt.th=Nt.td,v.support.htmlSerialize||(Nt._default=[1,"X
","
"]),v.fn.extend({text:function(e){return v.access(this,function(e){return e===t?v.text(this):this.empty().append((this[0]&&this[0].ownerDocument||i).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(v.isFunction(e))return this.each(function(t){v(this).wrapAll(e.call(this,t))});if(this[0]){var t=v(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&e.firstChild.nodeType===1)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return v.isFunction(e)?this.each(function(t){v(this).wrapInner(e.call(this,t))}):this.each(function(){var t=v(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=v.isFunction(e);return this.each(function(n){v(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){v.nodeName(this,"body")||v(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(e,this.firstChild)})},before:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(e,this),"before",this.selector)}},after:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this.nextSibling)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(this,e),"after",this.selector)}},remove:function(e,t){var n,r=0;for(;(n=this[r])!=null;r++)if(!e||v.filter(e,[n]).length)!t&&n.nodeType===1&&(v.cleanData(n.getElementsByTagName("*")),v.cleanData([n])),n.parentNode&&n.parentNode.removeChild(n);return this},empty:function(){var e,t=0;for(;(e=this[t])!=null;t++){e.nodeType===1&&v.cleanData(e.getElementsByTagName("*"));while(e.firstChild)e.removeChild(e.firstChild)}return this},clone:function(e,t){return e=e==null?!1:e,t=t==null?e:t,this.map(function(){return v.clone(this,e,t)})},html:function(e){return v.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return n.nodeType===1?n.innerHTML.replace(ht,""):t;if(typeof e=="string"&&!yt.test(e)&&(v.support.htmlSerialize||!wt.test(e))&&(v.support.leadingWhitespace||!pt.test(e))&&!Nt[(vt.exec(e)||["",""])[1].toLowerCase()]){e=e.replace(dt,"<$1>");try{for(;r1&&typeof f=="string"&&St.test(f))return this.each(function(){v(this).domManip(e,n,r)});if(v.isFunction(f))return this.each(function(i){var s=v(this);e[0]=f.call(this,i,n?s.html():t),s.domManip(e,n,r)});if(this[0]){i=v.buildFragment(e,this,l),o=i.fragment,s=o.firstChild,o.childNodes.length===1&&(o=s);if(s){n=n&&v.nodeName(s,"tr");for(u=i.cacheable||c-1;a0?this.clone(!0):this).get(),v(o[i])[t](r),s=s.concat(r);return this.pushStack(s,e,o.selector)}}),v.extend({clone:function(e,t,n){var r,i,s,o;v.support.html5Clone||v.isXMLDoc(e)||!wt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(kt.innerHTML=e.outerHTML,kt.removeChild(o=kt.firstChild));if((!v.support.noCloneEvent||!v.support.noCloneChecked)&&(e.nodeType===1||e.nodeType===11)&&!v.isXMLDoc(e)){Ot(e,o),r=Mt(e),i=Mt(o);for(s=0;r[s];++s)i[s]&&Ot(r[s],i[s])}if(t){At(e,o);if(n){r=Mt(e),i=Mt(o);for(s=0;r[s];++s)At(r[s],i[s])}}return r=i=null,o},clean:function(e,t,n,r){var s,o,u,a,f,l,c,h,p,d,m,g,y=t===i&&Ct,b=[];if(!t||typeof t.createDocumentFragment=="undefined")t=i;for(s=0;(u=e[s])!=null;s++){typeof u=="number"&&(u+="");if(!u)continue;if(typeof u=="string")if(!gt.test(u))u=t.createTextNode(u);else{y=y||lt(t),c=t.createElement("div"),y.appendChild(c),u=u.replace(dt,"<$1>"),a=(vt.exec(u)||["",""])[1].toLowerCase(),f=Nt[a]||Nt._default,l=f[0],c.innerHTML=f[1]+u+f[2];while(l--)c=c.lastChild;if(!v.support.tbody){h=mt.test(u),p=a==="table"&&!h?c.firstChild&&c.firstChild.childNodes:f[1]===""&&!h?c.childNodes:[];for(o=p.length-1;o>=0;--o)v.nodeName(p[o],"tbody")&&!p[o].childNodes.length&&p[o].parentNode.removeChild(p[o])}!v.support.leadingWhitespace&&pt.test(u)&&c.insertBefore(t.createTextNode(pt.exec(u)[0]),c.firstChild),u=c.childNodes,c.parentNode.removeChild(c)}u.nodeType?b.push(u):v.merge(b,u)}c&&(u=c=y=null);if(!v.support.appendChecked)for(s=0;(u=b[s])!=null;s++)v.nodeName(u,"input")?_t(u):typeof u.getElementsByTagName!="undefined"&&v.grep(u.getElementsByTagName("input"),_t);if(n){m=function(e){if(!e.type||xt.test(e.type))return r?r.push(e.parentNode?e.parentNode.removeChild(e):e):n.appendChild(e)};for(s=0;(u=b[s])!=null;s++)if(!v.nodeName(u,"script")||!m(u))n.appendChild(u),typeof u.getElementsByTagName!="undefined"&&(g=v.grep(v.merge([],u.getElementsByTagName("script")),m),b.splice.apply(b,[s+1,0].concat(g)),s+=g.length)}return b},cleanData:function(e,t){var n,r,i,s,o=0,u=v.expando,a=v.cache,f=v.support.deleteExpando,l=v.event.special;for(;(i=e[o])!=null;o++)if(t||v.acceptData(i)){r=i[u],n=r&&a[r];if(n){if(n.events)for(s in n.events)l[s]?v.event.remove(i,s):v.removeEvent(i,s,n.handle);a[r]&&(delete a[r],f?delete i[u]:i.removeAttribute?i.removeAttribute(u):i[u]=null,v.deletedIds.push(r))}}}}),function(){var e,t;v.uaMatch=function(e){e=e.toLowerCase();var t=/(chrome)[ \/]([\w.]+)/.exec(e)||/(webkit)[ \/]([\w.]+)/.exec(e)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(e)||/(msie) ([\w.]+)/.exec(e)||e.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(e)||[];return{browser:t[1]||"",version:t[2]||"0"}},e=v.uaMatch(o.userAgent),t={},e.browser&&(t[e.browser]=!0,t.version=e.version),t.chrome?t.webkit=!0:t.webkit&&(t.safari=!0),v.browser=t,v.sub=function(){function e(t,n){return new e.fn.init(t,n)}v.extend(!0,e,this),e.superclass=this,e.fn=e.prototype=this(),e.fn.constructor=e,e.sub=this.sub,e.fn.init=function(r,i){return i&&i instanceof v&&!(i instanceof e)&&(i=e(i)),v.fn.init.call(this,r,i,t)},e.fn.init.prototype=e.fn;var t=e(i);return e}}();var Dt,Pt,Ht,Bt=/alpha\([^)]*\)/i,jt=/opacity=([^)]*)/,Ft=/^(top|right|bottom|left)$/,It=/^(none|table(?!-c[ea]).+)/,qt=/^margin/,Rt=new RegExp("^("+m+")(.*)$","i"),Ut=new RegExp("^("+m+")(?!px)[a-z%]+$","i"),zt=new RegExp("^([-+])=("+m+")","i"),Wt={BODY:"block"},Xt={position:"absolute",visibility:"hidden",display:"block"},Vt={letterSpacing:0,fontWeight:400},$t=["Top","Right","Bottom","Left"],Jt=["Webkit","O","Moz","ms"],Kt=v.fn.toggle;v.fn.extend({css:function(e,n){return v.access(this,function(e,n,r){return r!==t?v.style(e,n,r):v.css(e,n)},e,n,arguments.length>1)},show:function(){return Yt(this,!0)},hide:function(){return Yt(this)},toggle:function(e,t){var n=typeof e=="boolean";return v.isFunction(e)&&v.isFunction(t)?Kt.apply(this,arguments):this.each(function(){(n?e:Gt(this))?v(this).show():v(this).hide()})}}),v.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Dt(e,"opacity");return n===""?"1":n}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":v.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(!e||e.nodeType===3||e.nodeType===8||!e.style)return;var s,o,u,a=v.camelCase(n),f=e.style;n=v.cssProps[a]||(v.cssProps[a]=Qt(f,a)),u=v.cssHooks[n]||v.cssHooks[a];if(r===t)return u&&"get"in u&&(s=u.get(e,!1,i))!==t?s:f[n];o=typeof r,o==="string"&&(s=zt.exec(r))&&(r=(s[1]+1)*s[2]+parseFloat(v.css(e,n)),o="number");if(r==null||o==="number"&&isNaN(r))return;o==="number"&&!v.cssNumber[a]&&(r+="px");if(!u||!("set"in u)||(r=u.set(e,r,i))!==t)try{f[n]=r}catch(l){}},css:function(e,n,r,i){var s,o,u,a=v.camelCase(n);return n=v.cssProps[a]||(v.cssProps[a]=Qt(e.style,a)),u=v.cssHooks[n]||v.cssHooks[a],u&&"get"in u&&(s=u.get(e,!0,i)),s===t&&(s=Dt(e,n)),s==="normal"&&n in Vt&&(s=Vt[n]),r||i!==t?(o=parseFloat(s),r||v.isNumeric(o)?o||0:s):s},swap:function(e,t,n){var r,i,s={};for(i in t)s[i]=e.style[i],e.style[i]=t[i];r=n.call(e);for(i in t)e.style[i]=s[i];return r}}),e.getComputedStyle?Dt=function(t,n){var r,i,s,o,u=e.getComputedStyle(t,null),a=t.style;return u&&(r=u.getPropertyValue(n)||u[n],r===""&&!v.contains(t.ownerDocument,t)&&(r=v.style(t,n)),Ut.test(r)&&qt.test(n)&&(i=a.width,s=a.minWidth,o=a.maxWidth,a.minWidth=a.maxWidth=a.width=r,r=u.width,a.width=i,a.minWidth=s,a.maxWidth=o)),r}:i.documentElement.currentStyle&&(Dt=function(e,t){var n,r,i=e.currentStyle&&e.currentStyle[t],s=e.style;return i==null&&s&&s[t]&&(i=s[t]),Ut.test(i)&&!Ft.test(t)&&(n=s.left,r=e.runtimeStyle&&e.runtimeStyle.left,r&&(e.runtimeStyle.left=e.currentStyle.left),s.left=t==="fontSize"?"1em":i,i=s.pixelLeft+"px",s.left=n,r&&(e.runtimeStyle.left=r)),i===""?"auto":i}),v.each(["height","width"],function(e,t){v.cssHooks[t]={get:function(e,n,r){if(n)return e.offsetWidth===0&&It.test(Dt(e,"display"))?v.swap(e,Xt,function(){return tn(e,t,r)}):tn(e,t,r)},set:function(e,n,r){return Zt(e,n,r?en(e,t,r,v.support.boxSizing&&v.css(e,"boxSizing")==="border-box"):0)}}}),v.support.opacity||(v.cssHooks.opacity={get:function(e,t){return jt.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=v.isNumeric(t)?"alpha(opacity="+t*100+")":"",s=r&&r.filter||n.filter||"";n.zoom=1;if(t>=1&&v.trim(s.replace(Bt,""))===""&&n.removeAttribute){n.removeAttribute("filter");if(r&&!r.filter)return}n.filter=Bt.test(s)?s.replace(Bt,i):s+" "+i}}),v(function(){v.support.reliableMarginRight||(v.cssHooks.marginRight={get:function(e,t){return v.swap(e,{display:"inline-block"},function(){if(t)return Dt(e,"marginRight")})}}),!v.support.pixelPosition&&v.fn.position&&v.each(["top","left"],function(e,t){v.cssHooks[t]={get:function(e,n){if(n){var r=Dt(e,t);return Ut.test(r)?v(e).position()[t]+"px":r}}}})}),v.expr&&v.expr.filters&&(v.expr.filters.hidden=function(e){return e.offsetWidth===0&&e.offsetHeight===0||!v.support.reliableHiddenOffsets&&(e.style&&e.style.display||Dt(e,"display"))==="none"},v.expr.filters.visible=function(e){return!v.expr.filters.hidden(e)}),v.each({margin:"",padding:"",border:"Width"},function(e,t){v.cssHooks[e+t]={expand:function(n){var r,i=typeof n=="string"?n.split(" "):[n],s={};for(r=0;r<4;r++)s[e+$t[r]+t]=i[r]||i[r-2]||i[0];return s}},qt.test(e)||(v.cssHooks[e+t].set=Zt)});var rn=/%20/g,sn=/\[\]$/,on=/\r?\n/g,un=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,an=/^(?:select|textarea)/i;v.fn.extend({serialize:function(){return v.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?v.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||an.test(this.nodeName)||un.test(this.type))}).map(function(e,t){var n=v(this).val();return n==null?null:v.isArray(n)?v.map(n,function(e,n){return{name:t.name,value:e.replace(on,"\r\n")}}):{name:t.name,value:n.replace(on,"\r\n")}}).get()}}),v.param=function(e,n){var r,i=[],s=function(e,t){t=v.isFunction(t)?t():t==null?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};n===t&&(n=v.ajaxSettings&&v.ajaxSettings.traditional);if(v.isArray(e)||e.jquery&&!v.isPlainObject(e))v.each(e,function(){s(this.name,this.value)});else for(r in e)fn(r,e[r],n,s);return i.join("&").replace(rn,"+")};var ln,cn,hn=/#.*$/,pn=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,dn=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,vn=/^(?:GET|HEAD)$/,mn=/^\/\//,gn=/\?/,yn=/)<[^<]*)*<\/script>/gi,bn=/([?&])_=[^&]*/,wn=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,En=v.fn.load,Sn={},xn={},Tn=["*/"]+["*"];try{cn=s.href}catch(Nn){cn=i.createElement("a"),cn.href="",cn=cn.href}ln=wn.exec(cn.toLowerCase())||[],v.fn.load=function(e,n,r){if(typeof e!="string"&&En)return En.apply(this,arguments);if(!this.length)return this;var i,s,o,u=this,a=e.indexOf(" ");return a>=0&&(i=e.slice(a,e.length),e=e.slice(0,a)),v.isFunction(n)?(r=n,n=t):n&&typeof n=="object"&&(s="POST"),v.ajax({url:e,type:s,dataType:"html",data:n,complete:function(e,t){r&&u.each(r,o||[e.responseText,t,e])}}).done(function(e){o=arguments,u.html(i?v("
").append(e.replace(yn,"")).find(i):e)}),this},v.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(e,t){v.fn[t]=function(e){return this.on(t,e)}}),v.each(["get","post"],function(e,n){v[n]=function(e,r,i,s){return v.isFunction(r)&&(s=s||i,i=r,r=t),v.ajax({type:n,url:e,data:r,success:i,dataType:s})}}),v.extend({getScript:function(e,n){return v.get(e,t,n,"script")},getJSON:function(e,t,n){return v.get(e,t,n,"json")},ajaxSetup:function(e,t){return t?Ln(e,v.ajaxSettings):(t=e,e=v.ajaxSettings),Ln(e,t),e},ajaxSettings:{url:cn,isLocal:dn.test(ln[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":Tn},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":e.String,"text html":!0,"text json":v.parseJSON,"text xml":v.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:Cn(Sn),ajaxTransport:Cn(xn),ajax:function(e,n){function T(e,n,s,a){var l,y,b,w,S,T=n;if(E===2)return;E=2,u&&clearTimeout(u),o=t,i=a||"",x.readyState=e>0?4:0,s&&(w=An(c,x,s));if(e>=200&&e<300||e===304)c.ifModified&&(S=x.getResponseHeader("Last-Modified"),S&&(v.lastModified[r]=S),S=x.getResponseHeader("Etag"),S&&(v.etag[r]=S)),e===304?(T="notmodified",l=!0):(l=On(c,w),T=l.state,y=l.data,b=l.error,l=!b);else{b=T;if(!T||e)T="error",e<0&&(e=0)}x.status=e,x.statusText=(n||T)+"",l?d.resolveWith(h,[y,T,x]):d.rejectWith(h,[x,T,b]),x.statusCode(g),g=t,f&&p.trigger("ajax"+(l?"Success":"Error"),[x,c,l?y:b]),m.fireWith(h,[x,T]),f&&(p.trigger("ajaxComplete",[x,c]),--v.active||v.event.trigger("ajaxStop"))}typeof e=="object"&&(n=e,e=t),n=n||{};var r,i,s,o,u,a,f,l,c=v.ajaxSetup({},n),h=c.context||c,p=h!==c&&(h.nodeType||h instanceof v)?v(h):v.event,d=v.Deferred(),m=v.Callbacks("once memory"),g=c.statusCode||{},b={},w={},E=0,S="canceled",x={readyState:0,setRequestHeader:function(e,t){if(!E){var n=e.toLowerCase();e=w[n]=w[n]||e,b[e]=t}return this},getAllResponseHeaders:function(){return E===2?i:null},getResponseHeader:function(e){var n;if(E===2){if(!s){s={};while(n=pn.exec(i))s[n[1].toLowerCase()]=n[2]}n=s[e.toLowerCase()]}return n===t?null:n},overrideMimeType:function(e){return E||(c.mimeType=e),this},abort:function(e){return e=e||S,o&&o.abort(e),T(0,e),this}};d.promise(x),x.success=x.done,x.error=x.fail,x.complete=m.add,x.statusCode=function(e){if(e){var t;if(E<2)for(t in e)g[t]=[g[t],e[t]];else t=e[x.status],x.always(t)}return this},c.url=((e||c.url)+"").replace(hn,"").replace(mn,ln[1]+"//"),c.dataTypes=v.trim(c.dataType||"*").toLowerCase().split(y),c.crossDomain==null&&(a=wn.exec(c.url.toLowerCase()),c.crossDomain=!(!a||a[1]===ln[1]&&a[2]===ln[2]&&(a[3]||(a[1]==="http:"?80:443))==(ln[3]||(ln[1]==="http:"?80:443)))),c.data&&c.processData&&typeof c.data!="string"&&(c.data=v.param(c.data,c.traditional)),kn(Sn,c,n,x);if(E===2)return x;f=c.global,c.type=c.type.toUpperCase(),c.hasContent=!vn.test(c.type),f&&v.active++===0&&v.event.trigger("ajaxStart");if(!c.hasContent){c.data&&(c.url+=(gn.test(c.url)?"&":"?")+c.data,delete c.data),r=c.url;if(c.cache===!1){var N=v.now(),C=c.url.replace(bn,"$1_="+N);c.url=C+(C===c.url?(gn.test(c.url)?"&":"?")+"_="+N:"")}}(c.data&&c.hasContent&&c.contentType!==!1||n.contentType)&&x.setRequestHeader("Content-Type",c.contentType),c.ifModified&&(r=r||c.url,v.lastModified[r]&&x.setRequestHeader("If-Modified-Since",v.lastModified[r]),v.etag[r]&&x.setRequestHeader("If-None-Match",v.etag[r])),x.setRequestHeader("Accept",c.dataTypes[0]&&c.accepts[c.dataTypes[0]]?c.accepts[c.dataTypes[0]]+(c.dataTypes[0]!=="*"?", "+Tn+"; q=0.01":""):c.accepts["*"]);for(l in c.headers)x.setRequestHeader(l,c.headers[l]);if(!c.beforeSend||c.beforeSend.call(h,x,c)!==!1&&E!==2){S="abort";for(l in{success:1,error:1,complete:1})x[l](c[l]);o=kn(xn,c,n,x);if(!o)T(-1,"No Transport");else{x.readyState=1,f&&p.trigger("ajaxSend",[x,c]),c.async&&c.timeout>0&&(u=setTimeout(function(){x.abort("timeout")},c.timeout));try{E=1,o.send(b,T)}catch(k){if(!(E<2))throw k;T(-1,k)}}return x}return x.abort()},active:0,lastModified:{},etag:{}});var Mn=[],_n=/\?/,Dn=/(=)\?(?=&|$)|\?\?/,Pn=v.now();v.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Mn.pop()||v.expando+"_"+Pn++;return this[e]=!0,e}}),v.ajaxPrefilter("json jsonp",function(n,r,i){var s,o,u,a=n.data,f=n.url,l=n.jsonp!==!1,c=l&&Dn.test(f),h=l&&!c&&typeof a=="string"&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Dn.test(a);if(n.dataTypes[0]==="jsonp"||c||h)return s=n.jsonpCallback=v.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,o=e[s],c?n.url=f.replace(Dn,"$1"+s):h?n.data=a.replace(Dn,"$1"+s):l&&(n.url+=(_n.test(f)?"&":"?")+n.jsonp+"="+s),n.converters["script json"]=function(){return u||v.error(s+" was not called"),u[0]},n.dataTypes[0]="json",e[s]=function(){u=arguments},i.always(function(){e[s]=o,n[s]&&(n.jsonpCallback=r.jsonpCallback,Mn.push(s)),u&&v.isFunction(o)&&o(u[0]),u=o=t}),"script"}),v.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(e){return v.globalEval(e),e}}}),v.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),v.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=i.head||i.getElementsByTagName("head")[0]||i.documentElement;return{send:function(s,o){n=i.createElement("script"),n.async="async",e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,i){if(i||!n.readyState||/loaded|complete/.test(n.readyState))n.onload=n.onreadystatechange=null,r&&n.parentNode&&r.removeChild(n),n=t,i||o(200,"success")},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(0,1)}}}});var Hn,Bn=e.ActiveXObject?function(){for(var e in Hn)Hn[e](0,1)}:!1,jn=0;v.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&Fn()||In()}:Fn,function(e){v.extend(v.support,{ajax:!!e,cors:!!e&&"withCredentials"in e})}(v.ajaxSettings.xhr()),v.support.ajax&&v.ajaxTransport(function(n){if(!n.crossDomain||v.support.cors){var r;return{send:function(i,s){var o,u,a=n.xhr();n.username?a.open(n.type,n.url,n.async,n.username,n.password):a.open(n.type,n.url,n.async);if(n.xhrFields)for(u in n.xhrFields)a[u]=n.xhrFields[u];n.mimeType&&a.overrideMimeType&&a.overrideMimeType(n.mimeType),!n.crossDomain&&!i["X-Requested-With"]&&(i["X-Requested-With"]="XMLHttpRequest");try{for(u in i)a.setRequestHeader(u,i[u])}catch(f){}a.send(n.hasContent&&n.data||null),r=function(e,i){var u,f,l,c,h;try{if(r&&(i||a.readyState===4)){r=t,o&&(a.onreadystatechange=v.noop,Bn&&delete Hn[o]);if(i)a.readyState!==4&&a.abort();else{u=a.status,l=a.getAllResponseHeaders(),c={},h=a.responseXML,h&&h.documentElement&&(c.xml=h);try{c.text=a.responseText}catch(p){}try{f=a.statusText}catch(p){f=""}!u&&n.isLocal&&!n.crossDomain?u=c.text?200:404:u===1223&&(u=204)}}}catch(d){i||s(-1,d)}c&&s(u,f,c,l)},n.async?a.readyState===4?setTimeout(r,0):(o=++jn,Bn&&(Hn||(Hn={},v(e).unload(Bn)),Hn[o]=r),a.onreadystatechange=r):r()},abort:function(){r&&r(0,1)}}}});var qn,Rn,Un=/^(?:toggle|show|hide)$/,zn=new RegExp("^(?:([-+])=|)("+m+")([a-z%]*)$","i"),Wn=/queueHooks$/,Xn=[Gn],Vn={"*":[function(e,t){var n,r,i=this.createTween(e,t),s=zn.exec(t),o=i.cur(),u=+o||0,a=1,f=20;if(s){n=+s[2],r=s[3]||(v.cssNumber[e]?"":"px");if(r!=="px"&&u){u=v.css(i.elem,e,!0)||n||1;do a=a||".5",u/=a,v.style(i.elem,e,u+r);while(a!==(a=i.cur()/o)&&a!==1&&--f)}i.unit=r,i.start=u,i.end=s[1]?u+(s[1]+1)*n:n}return i}]};v.Animation=v.extend(Kn,{tweener:function(e,t){v.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;r-1,f={},l={},c,h;a?(l=i.position(),c=l.top,h=l.left):(c=parseFloat(o)||0,h=parseFloat(u)||0),v.isFunction(t)&&(t=t.call(e,n,s)),t.top!=null&&(f.top=t.top-s.top+c),t.left!=null&&(f.left=t.left-s.left+h),"using"in t?t.using.call(e,f):i.css(f)}},v.fn.extend({position:function(){if(!this[0])return;var e=this[0],t=this.offsetParent(),n=this.offset(),r=er.test(t[0].nodeName)?{top:0,left:0}:t.offset();return n.top-=parseFloat(v.css(e,"marginTop"))||0,n.left-=parseFloat(v.css(e,"marginLeft"))||0,r.top+=parseFloat(v.css(t[0],"borderTopWidth"))||0,r.left+=parseFloat(v.css(t[0],"borderLeftWidth"))||0,{top:n.top-r.top,left:n.left-r.left}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||i.body;while(e&&!er.test(e.nodeName)&&v.css(e,"position")==="static")e=e.offsetParent;return e||i.body})}}),v.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);v.fn[e]=function(i){return v.access(this,function(e,i,s){var o=tr(e);if(s===t)return o?n in o?o[n]:o.document.documentElement[i]:e[i];o?o.scrollTo(r?v(o).scrollLeft():s,r?s:v(o).scrollTop()):e[i]=s},e,i,arguments.length,null)}}),v.each({Height:"height",Width:"width"},function(e,n){v.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){v.fn[i]=function(i,s){var o=arguments.length&&(r||typeof i!="boolean"),u=r||(i===!0||s===!0?"margin":"border");return v.access(this,function(n,r,i){var s;return v.isWindow(n)?n.document.documentElement["client"+e]:n.nodeType===9?(s=n.documentElement,Math.max(n.body["scroll"+e],s["scroll"+e],n.body["offset"+e],s["offset"+e],s["client"+e])):i===t?v.css(n,r,i,u):v.style(n,r,i,u)},n,o?i:t,o,null)}})}),e.jQuery=e.$=v,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return v})})(window); \ No newline at end of file diff --git a/demos/js/popper.min.js b/demos/js/popper.min.js new file mode 100644 index 0000000..79ccbf5 --- /dev/null +++ b/demos/js/popper.min.js @@ -0,0 +1,5 @@ +/* + Copyright (C) Federico Zivolo 2018 + Distributed under the MIT License (license terms are at http://opensource.org/licenses/MIT). + */(function(e,t){'object'==typeof exports&&'undefined'!=typeof module?module.exports=t():'function'==typeof define&&define.amd?define(t):e.Popper=t()})(this,function(){'use strict';function e(e){return e&&'[object Function]'==={}.toString.call(e)}function t(e,t){if(1!==e.nodeType)return[];var o=getComputedStyle(e,null);return t?o[t]:o}function o(e){return'HTML'===e.nodeName?e:e.parentNode||e.host}function n(e){if(!e)return document.body;switch(e.nodeName){case'HTML':case'BODY':return e.ownerDocument.body;case'#document':return e.body;}var i=t(e),r=i.overflow,p=i.overflowX,s=i.overflowY;return /(auto|scroll|overlay)/.test(r+s+p)?e:n(o(e))}function r(e){return 11===e?re:10===e?pe:re||pe}function p(e){if(!e)return document.documentElement;for(var o=r(10)?document.body:null,n=e.offsetParent;n===o&&e.nextElementSibling;)n=(e=e.nextElementSibling).offsetParent;var i=n&&n.nodeName;return i&&'BODY'!==i&&'HTML'!==i?-1!==['TD','TABLE'].indexOf(n.nodeName)&&'static'===t(n,'position')?p(n):n:e?e.ownerDocument.documentElement:document.documentElement}function s(e){var t=e.nodeName;return'BODY'!==t&&('HTML'===t||p(e.firstElementChild)===e)}function d(e){return null===e.parentNode?e:d(e.parentNode)}function a(e,t){if(!e||!e.nodeType||!t||!t.nodeType)return document.documentElement;var o=e.compareDocumentPosition(t)&Node.DOCUMENT_POSITION_FOLLOWING,n=o?e:t,i=o?t:e,r=document.createRange();r.setStart(n,0),r.setEnd(i,0);var l=r.commonAncestorContainer;if(e!==l&&t!==l||n.contains(i))return s(l)?l:p(l);var f=d(e);return f.host?a(f.host,t):a(e,d(t).host)}function l(e){var t=1=o.clientWidth&&n>=o.clientHeight}),l=0a[e]&&!t.escapeWithReference&&(n=J(f[o],a[e]-('right'===e?f.width:f.height))),ae({},o,n)}};return l.forEach(function(e){var t=-1===['left','top'].indexOf(e)?'secondary':'primary';f=le({},f,m[t](e))}),e.offsets.popper=f,e},priority:['left','right','top','bottom'],padding:5,boundariesElement:'scrollParent'},keepTogether:{order:400,enabled:!0,fn:function(e){var t=e.offsets,o=t.popper,n=t.reference,i=e.placement.split('-')[0],r=Z,p=-1!==['top','bottom'].indexOf(i),s=p?'right':'bottom',d=p?'left':'top',a=p?'width':'height';return o[s]r(n[s])&&(e.offsets.popper[d]=r(n[s])),e}},arrow:{order:500,enabled:!0,fn:function(e,o){var n;if(!q(e.instance.modifiers,'arrow','keepTogether'))return e;var i=o.element;if('string'==typeof i){if(i=e.instance.popper.querySelector(i),!i)return e;}else if(!e.instance.popper.contains(i))return console.warn('WARNING: `arrow.element` must be child of its popper element!'),e;var r=e.placement.split('-')[0],p=e.offsets,s=p.popper,d=p.reference,a=-1!==['left','right'].indexOf(r),l=a?'height':'width',f=a?'Top':'Left',m=f.toLowerCase(),h=a?'left':'top',c=a?'bottom':'right',u=S(i)[l];d[c]-us[c]&&(e.offsets.popper[m]+=d[m]+u-s[c]),e.offsets.popper=g(e.offsets.popper);var b=d[m]+d[l]/2-u/2,y=t(e.instance.popper),w=parseFloat(y['margin'+f],10),E=parseFloat(y['border'+f+'Width'],10),v=b-e.offsets.popper[m]-w-E;return v=$(J(s[l]-u,v),0),e.arrowElement=i,e.offsets.arrow=(n={},ae(n,m,Q(v)),ae(n,h,''),n),e},element:'[x-arrow]'},flip:{order:600,enabled:!0,fn:function(e,t){if(W(e.instance.modifiers,'inner'))return e;if(e.flipped&&e.placement===e.originalPlacement)return e;var o=v(e.instance.popper,e.instance.reference,t.padding,t.boundariesElement,e.positionFixed),n=e.placement.split('-')[0],i=T(n),r=e.placement.split('-')[1]||'',p=[];switch(t.behavior){case he.FLIP:p=[n,i];break;case he.CLOCKWISE:p=z(n);break;case he.COUNTERCLOCKWISE:p=z(n,!0);break;default:p=t.behavior;}return p.forEach(function(s,d){if(n!==s||p.length===d+1)return e;n=e.placement.split('-')[0],i=T(n);var a=e.offsets.popper,l=e.offsets.reference,f=Z,m='left'===n&&f(a.right)>f(l.left)||'right'===n&&f(a.left)f(l.top)||'bottom'===n&&f(a.top)f(o.right),g=f(a.top)f(o.bottom),b='left'===n&&h||'right'===n&&c||'top'===n&&g||'bottom'===n&&u,y=-1!==['top','bottom'].indexOf(n),w=!!t.flipVariations&&(y&&'start'===r&&h||y&&'end'===r&&c||!y&&'start'===r&&g||!y&&'end'===r&&u);(m||b||w)&&(e.flipped=!0,(m||b)&&(n=p[d+1]),w&&(r=G(r)),e.placement=n+(r?'-'+r:''),e.offsets.popper=le({},e.offsets.popper,C(e.instance.popper,e.offsets.reference,e.placement)),e=P(e.instance.modifiers,e,'flip'))}),e},behavior:'flip',padding:5,boundariesElement:'viewport'},inner:{order:700,enabled:!1,fn:function(e){var t=e.placement,o=t.split('-')[0],n=e.offsets,i=n.popper,r=n.reference,p=-1!==['left','right'].indexOf(o),s=-1===['top','left'].indexOf(o);return i[p?'left':'top']=r[o]-(s?i[p?'width':'height']:0),e.placement=T(t),e.offsets.popper=g(i),e}},hide:{order:800,enabled:!0,fn:function(e){if(!q(e.instance.modifiers,'hide','preventOverflow'))return e;var t=e.offsets.reference,o=D(e.instance.modifiers,function(e){return'preventOverflow'===e.name}).boundaries;if(t.bottomo.right||t.top>o.bottom||t.right + + + + One-to-One Video Chat using RTCMultiConnection + + + + + + +
+ + MenuMenu + +
+ +

+ One-to-One Video Chat +

+ Maximum two users can join a room. +

+

+ +
+
+ + + + +
+ +
+ + +
+ + + + + + + + + + +
+ +
+ + + + diff --git a/demos/screen-sharing.html b/demos/screen-sharing.html new file mode 100644 index 0000000..449caa5 --- /dev/null +++ b/demos/screen-sharing.html @@ -0,0 +1,315 @@ + + + + + Screen Sharing using RTCMultiConnection + + + + + + +
+ + MenuMenu + +
+ +

+ Screen Sharing using RTCMultiConnection +

+ Multi-user (one-to-many) screen sharing using star topology. +

+

+ +
+ + + + + +
+ + +
+ + + + + + + + + + +
+ +
+ + + + diff --git a/demos/stylesheet.css b/demos/stylesheet.css new file mode 100644 index 0000000..3b2f07b --- /dev/null +++ b/demos/stylesheet.css @@ -0,0 +1,248 @@ +/* Fonts Copyright (C) 2011-2017 Hoefler & Co.*/ +@font-face { + font-family: "Whitney SSm A"; + src: url(data:application/x-font-woff2;base64,d09GMgABAAAAAD/gABIAAAAAnJgAAD99AAFNDgAAAAAAAAAAAAAAAAAAAAAAAAAAGh4bwXAcgQAGYACINAgsCYJhEQwKgb98galYEggBNgIkA4VoC4J4AAQgBZZ2B4RpDIFmG8GOF9g2jR5edwKpmdX3P+IoKlkvMTtQw8YRMGbZavb///cFKjLWDW7ac1BBBQZlznQWDYVyaEXnvA556nBJFlHeJNXo+Ohb3UaxbqVkVxpOB5dcj6ZdKEbIBaOVmhTLlc4N7L4aBLRELtbcwG6/YblvnkqlIWzMAH4B/61LdIhh3F+I4T3oAtuGt5KTaa8Pb1e+PyeuPHugHEFVUpFVevD//zare59oySuhoCBBOhAjnaLNDumMWY8JIybyO4cVz5r8KZ8rA7TNzigUo0iVSgFBLJRuFVAJxcKu1W+60GV91iJLVy7b/faLFExdmLb/JAVwlI9hm17Ep/E8/DF4z73vh1YkfYqi6kUEUAbQWgc4kWnTxB6U276khVaNxigipuyvNBG8BcB+ut4044X3JE+QvaGjLtgd7k/RjCTb84l9xCG73W1DxNUhTNNV0JK5TlU+u29qRbPifiIGZNBNj2ffjutWs5pNnFXEQsEXwkhqFMzt02AOMZgHJkO3tGwK1wAKFCB9v+mE60O2O6E6Dw06V+a6SMYUHmHOqV9Xb/Cruf+vJwM9k5tL/BjyYYlAGCAJAJKE3eqcyearVQhuJToC/UyWc3JoAwk0dGo/0U1blo4ei1JVcM8haJ+51NoyLFgerZx7z+T/1+lXOe9J0bc8GM/MEnzQItVxFgBKoHK3ku6T/GQ9KXGkOAbZwYHAJzvJp/w/42c5/grtOc4SoTPA3C1BjUWHFWC5RZUpur9Nt01L0FHRFNuUU265/peaZfpeY8hFz55BQz40NtMqiJyLFeXg7x4CbAAkrzGzBiDX4JznOcoTM7NVQ3OGRxkbKYgUKzrjMwWRtBtWkfTmbznLIM6zpZRSBgkiIQQJ4u5vsJzVgUDiFSyG6No9nvez33JwEYmRlCPuoYK3zy1jWr+Hd7t22tbJlgAJglablnmp/XWtshZHCCJOeXw3g+1VbgsEQBNzb5uC0MeM/cdwwQDqVovif+6CxgJEvvpUSx2ApAiA/5PrVeC4yDNvNjcAka8811QHxEM8DLAfExzqXoiFLI3b8gEQs/hfbopifFIGCDczEfG8x09lvubHoRGMw2LIn//m/wKB5FLyEgiQwaW9eUA4ogvIIVvszCZ7Q1OdsOZQVIhDWH7d+tiYEUeb3byRrFJ85aaFVBOZSYheSDgHaSItA068RqjPB0jQzEB0dLq1tpNwdw0uuQaVHDTiN0AiY5+mPW3EHQQuEhe52mRHLC9LlIR8StoTimaxyAGiviuMVGCtsXgPOjZSoYXaqwzud2BzAnnNhKav+ebnYGyyIpEG6SQTouLn/OQ3EqNx5iAkPScLkEeujKlS/eyR1GwgmVx9pZkPAYTlqEIsHH+6sV70OBcTiyjD1A5ElWEhVYM1yt7coVLD5FGp5ZDo+8UhPzjBUD6vYsPhQcfdvdHIsyAiHixKS/qBTy7/6dcH5TcsaeCg/pKBFI8x5x9iwsFTMBiWng5zcoKerjr0IJYDjwHqnyPeGTC6Gk6RKEysgHLKZNpFetmFRxPKjidXeoBDJYj8wVulqoQiaV4iuPfBFcJy6GcnkkUqAQoJqa9MN+5MZI9WczR6BxkyJpHmfa251GsQRLAuxORhaWZSRSAHQlhY4c0pamX4yZX1K7l/p/6UNhu8odEd2/LOwbp/an80V7CSGUsQkSfa1UhuG4dOAC6pKGJpPXIrnXs0yT0PmbtREmpWUheZpayc3em69cE4Dn4R3/2Z+sd0OG9GTEUlAna+NA+ljsjTec6vjegG0fcB2L+U9CmiiH9FsltOIVDRATQVE2ITE2z0p8dOSu5Q0SThblR7MSzqlVTJR750x7Cgi6oIcASF4CcMxfmxfWse2GNZuNdR91xYLNAYSiiOSWLOyCTU/b4XqdEQaQnO5FPtSPPdo6CrQNXrHliUs5yUNq8U4e7q1xKiB4IL1AyF3TafKAb35eZAp+iskWv+mymHVB+18+6hGeuAyLPYoRxc2ibwNRovLfAwP59vNC1+Cgco1uk62pCxRK11w3yF5Xtb9zwVEsvfl6WjZUdqib9HZwYUA8RqpJQqtAtO5M6+JwybgL8ZKsqQ6y4hdgSFXJshwNI8il5QzCNLlqOExMtzi4PgMnhAsU7T3QYfDV2pj4PTSQoroStyWinsJ2Vm84MDvov77c1LlCsx2LjMWVx+EWdInMOz3q87tcB4Prk2L/5Ao3r12jU+99hBUesZzmFJPqhnbzby2wjIXM1dh1xbtBUZvsXT+VB0TwVQv1JVhne6C6jbkQfVwe+q4cPy9WAFcq0kKlHlcfrkyj2Mg15HEayzGfNfis2bSEDXkVBfAgym2STEpyLQUrLSVr1cabulW+kHgMkTApRyeuuQQFTuRZfKvfBRL/hW5w1kuDgPk49u3BcKEYEyVQlx98+71Y2emqZ+YQqxKat8JW4UCJQ+EB+82GMR2EC8Q9p6oDpnSsd3VPWzOGtbvWDh/AacCmjkaOP63MoRk+7e68M5o6rZzHOcZTIZ1ccXPhF8J7mHZgY3QO+5z4C4p8prySrpMXNI6znExu3oRRyb0AkZxklp68jKtWV0yY27Lz1gaSc5+rVg0NdBNVSqutSvBs0gk7iFPYvvxL0cP5ZSoF99LI9ISKZqDybSdVhHOsOwabvVLRRonJm4tsXRjb76hWpE7WEpEcH3WTU+cN9WxX9qWntVZ0oxQrmxhVjhc1J7ykDdWYyg+wy1+1p/R0WvvdTux9zicDcbXpoDocHwHLwBrEh1xLq2TCBWNbx9gnmWbVJosOQ7FwFo+mgujDiRbe2gfxj5rlE0w/L4AiGHgYmFjYOLZyVXGfjEpAQMGDMHWLAEmDNnTUzOjSdvPkPRlS+0Z/rmZmyQkZFEwh5I8TPnAkzwFQEpQQRAT0HDcSH5QFMHoOR0s6jqdtSnz4492l9xAM2UGUJ6hg4AwKQL4BLisiBhhoODUw0RAAUAmK0DlNB5VV71SBinTVuEhUVEikFODwMjryNm4eOxZMuew2bEpu6JZHS9NJoRh4S4cpTUs/YARLQjiSRnoKegYR2DA352fQnlLLgOC9cZMwF/XRHgkqEBuiiOIgagQkOWxfgSSnLWNK3mRp8HT2a8haCJoMUVyyhTqjpZavTQm2pShmHzSqyyR6UfHNDIj4IABKIQQF2P118dInC0+Oe7J++8w2QBqn9t8ANisF2fNh1dDPDLDgudQFkU07Zy/ArdJ1JBWD/tEGAC35L8KU0Ld4hdqCkA0vdXWcgucT0AgN6KCUDNTA/HXi8BwDYA1LKOAUCjgLp2FCMAUDiU8aCY4oD/le7WQ9kyNH3WHDjzFkBOq1ipRi3adOr1nX2OOOmsi6544KyL3sJ7DMEAXeKSEEhgQQQbYqihhxFWMiKKJLIoYkl+CmNPSVzxpjo1qUtDmtKSznSnN5P+0CJ6pNc3DayYumL6iteoeBQclYzCoAiobNTvCWZyskDTY8iBMze+ZFT0nLxatOnQ7Vv7HHTcWRdcdsMT5132Hr4gKL22ydfjJqutJt4jtuGPCryHK/by7b9CxVFMecvwK9SvpCgrLSkhLioiLCTAz8fryqVzp44c2LdjxbIliyktcPpIKY9WPZEIcDsA4N9/eFwB/4b48EIVC/59wWYxGePPU4R/71TAvxCAv9//p/wtf8mfhPef+hvP8FT3u/Z8zncR/56oTJ+ZbU+pJzyyEJoCuojHwnM41xjJoUeNGSfgcL2BiNOtxaRcnzXNk5zXnU+aos/37ofNMGIiYDxdsAWsYuZzta9SktMOBpqDAvQTRdIeQbgpBcPByX9NCg5FKP7HPun1B8MRjSfTGZqdI2osLC7R8srq2vrG5tb2zu7efo44C7A7zknnAs5nsrJzeLl5fIFQJAaAAFKyi4DisgoAsp/0AEDJa02Nza0tbR1dnd09fb39A1P//P77/x8AgISrGuB7Ndf1v1h1gPslAAAiAQAQcxdo/8QOAAAQe+8HIP1xxfCIQqnVqdQA49+Bg7+aAZD0/XcgUxEAAAqfB8peqames0h2bslSyfmVy4WAzYdYtXQ0IVfhCuUyZU8K0K4PrhnUOxy52L+BpoY2FLboN8/W4eSMv7VodYCzRIA0IvdRoIsOQgNSWEBp1IDim52vjUIz7HIPzYbelzsY/qYFmzzCwQMCmP1HbW7xjAXLnuUPs5GA0RCZWqiSNH0ri1+tu40//W9Om588Stj4rceVmmFBLWMmhy/dFL7km7GZQDRPM4XfJ24okilB0baqbe65udAdALZwM9FfM67kB2dhwjbtfPlSOwQmcYJ+ULzrvQFDqjkgrWykrmqfsuzz67cKNG2+904zZhNAAEFEdOZkAwBXACDvA/ADAK2PgPk1gNoB5EWA1S+gBAAAFIIjcMzILEweNp1VjiRynyGtbdSks+BaAiFCMMVMIgLtnHv3EFVilevYhkHpXH7VKcRoE4zSVRtVVW1AlHzZDUQZGu/aHoHT19EBa6jVWu8EEZYa8t3UbTRyHcNt4KclhFNK8VY7m1RTaCrh6xcuUYgeHthQz6eVW3xqVgJxh5OqNO7LylH74793qxmgul2ArFXNHioAKsTaDdqUZFrKmiKH19vxqV/52BiZWro5da5AqN8Ayx7n1Npf8my8J09LwuAXg2zoHPW/vAbyYWtdpIzhHC8qnBOhDIVjm/2JFCHO8lrI6t+6fGKzkBe3+Q0BekpkVNQjG0ItmbzcHv2BwqLEy9sou6sUyq3tMbOzQq6E0E7TT1KHX1U6V8zfCAO0zih/0nNu/d3+p/ICdx49rZLj2p6ZS9t/xDFDWvwjinIMUDqdJXydy+N/WB7ucn3yDwZ4F3YubxYa+o3SnXueEz5/CW/7r4QQAGblfw5K+QWvEb9OZSkrsS6eADRoyBAQ8GalYByQIWDZziOAJjYTZAnyUcdSxOIgGILUEGa9hUdHYHAI6iQHhal3edic2qL0HONmv1HWPz5ackMpCm6Xxwqc8gPywBAUNOUl9hhc/kmJMUZdj5vg7B/+l1wqVe8IXO7iHVv3+QNjCDTEGYFh5dRBS/Z18RcMNM9km5K0xzX19Q1zHYjRYt3BJz/QaNJmUJwdKfF+UX8oUe76x3wGX6p9NG6xTnaCRsfofnyOZ/dP4nQvDtBUQX18KVUqnN9pQfu9fMzOOli1SM03qJ/98MR9mm91Aw0t79dnE2zN27Z1LDrXqg+rrD1Tb6FaPGz9iS76DsbBJlbiL2H87S7stPxIVryPa1hHM5ObXXbIluREDDw/3RBOa98AfYf9vR9Yajj2j/IUJ3LNAqVjExaj8dFlS6aIZSZMOuamA2xQ8tH3+t32RmyoiS02M6EQZSdPMMpuY9TXwHlTHW6s2RmWADv/B+87AAdWTEgz0lhXezmjzTYLnVZ7duO1cWfcbSC0lAjLLSuLfvLkUxRARYDEzKtSrIs2ebzPhDIPKjyhVuT8yapogjGBPyqXtWGuepPPP4KOPaIanDih7A8qATCOxpT4ACA0Bhs2jZFb56zBH44BrLfbc0MP+aEytG6LobhTnUo/ik21z9EWYA+UFhTbatrJW1iv1KlGeh9K6ik5e42zw5eGxisNKw2OkVnbmB1Vq4zoyq8T03QyKAM3mmqgWgAaXd0FreGdRH6uENim2a4bHpO3ssbdjC5MRhpq/ec2mXgs7GTdngCGNmM+qFWmGk6VC9Eyc1Lixn7AHOOQeAyirOSzoSPLkdr+RNlrpIWlqg2ZVof6klBXLIS6Rd3wnAcBC7kXrHbeIACPI5IPxqjTC8CABeYm3NTG9i4hc85osFfr/EDEMRuPURvqLjGY6nfPFZlzMZePfXKRA6DAtyc22rKtP7tT4C/tFqa9wrbDJRkJ/+DLqq4ZjHWdC02MDQrbuyQ2AU2gTqG5g0CAPhW1urAY3xmxIdjeQzBWt8IpPtuwU7Lq1103Gm6bWHFhu8sfQtsPiq1cz2/9tAV+d6Mkv7MekRRh65SykH2QB8ouc33DF1ULp8KxcILOjk4QMKLuAWA+n6WiCAbnrhvXl6fnt9uu618KY7e14B2vXLZCxOJw+sHrqBwQkmyMsiE6te40LV2pwpygnMLFdci3ZaOXfq38Z/Nk3cJrHuzPM/O6uJNvdEgfA5q525EfLrYozrmganuYlJ9ccblWi64A0Gqy9NhBDMSxNUlTVZyI0pDw5hEKReYm9rHslgJ+Q6cXfWWcyR3K/iW59Vk+fMXEI3qx4o/+W/o9NGCdwIuj59QDmxyf6Duk/NbfXODLgMfDgGtO1niWi/8ln/2Rx0+41+YdiyTjugfzv/9Rl3u1QxSuHvMwrutP/NX/8t5v+zDvtf/hPHSAU+vznb5P6qnQn4nPKMq2nzR+9ZtNvtOj13rS236/7a8SfmebmvCMV9WmT9s81y88Bk21EBZTwfaHFUdeNCKrQA+spo9VgK/CRuFpx5/l6mKR2hvuukjNbfWh50qoARsQvs1j8ajE233KGEpxwOGA/bnbjh50g0dZ7YGvDq88BmWr2z736lGrs9l13NtvAVmlZ7MIAiiLUH/V274TyyihwnMmFEtyz+k1ZowvN+Fsvzw+rV2g8iDk4S9RdjZcv0o2DWxWYgAKMUlPU0e8iCrzTJ+gI72lMmoF6jrz9JcJ9C0TDwB+JDjQTbqNh76NcrFF+36iVJ2G2/MUP7FAGfs8mF1Ql4wcRhGAPzNJuAcFfrqgq8kOlBkA75aN74qZJSrzshDejudvkfGYyQTt7kELSziBlhPmEqU3ZzRn9nbTBlIdkD1v7fDZMZZFHhBuerpdNGDr7mcMnoJ2djzlUaGFexnqRsx9t5PpJS0V6y1acs3uTdj7OeY96Ce6VImZkQIk8ZdsF5s0psIUvarJYQqRAhz5RJQhVi0ZXCjZw4onTK0FclurGZ7uDbkpbfPG5Yds+fuhygxd5QGLBCBNGVKQtX+6LkZlai2rxTSwQVvpfrtqREl9V/k7DsVAe+L3iRIN5SXsWTl7BarBEnESma2dfwdUsfhzkl0oVFscxr5Ll5MuKpL32S5aMx5eq7pd6E2luk7BKydgyoo/L/nizb99Ibqp+l1mtBhpwDuBp9bB1vDqae3iH+iTsGdsSUgwXJd2KeEUhR8paFUeC++iE7DcvvkvP9RVGhzckbdMCZ3MEUyQ6zuqGjvmcFToo9AAxrYZLav2/dv+8lm77Id+l93inB2b7G0n5GDhqdPLEw8WCFFhbXlT0OemrV6WvCt7mXgieX930ub2ze5LU+TjqKz+8Any6Y/PWBjIgCkPjONwJy6YJOOSL5yQxw9suYX+zPO4dO4zt+xqPByz9ue3c34pdkLK2NJyGIdt4d/fHRxWvvTQK3xcHP1cXXJo4YKg9qaPPbnqzALEeZScToKJ3ggornKCIg37B10BT2UXQMvA6l/MSGL2UWrcAOqOZHxMkexdK4mEzeO61izfSczyMlsunpQiteas5MYNG/8deavmdw2rre63lwnqsN3yxUvuDRdESJs1Dbun9PRcaPMSQrHkjP3vDhdedlO7e0bbyghwtbqX5/F5fDRl7zeZrcPIyLkw8NwRpFdnl4zyR6/wrlyuYbZp0SDvvSNeBVEj1GEFdYV18KQhERhTOigCQ5//+JPkpy6O93nh/a7cXWdJC8mF14JlUfiunjDh5QyK47tSq+Ds5rrxufZlDvLe21kiWeaNJ7KFexbulW8r2CR8Jnz6UPRMFGVxxP8Zs0dx/Unmtgep5N1YFfViWPeHiN+fj47lg+BcbY4gq5SyH6TYU0viM3TQuSnC+MLq/Oq+/Es64mlVlOuFwvFQf5ASN8vajT7LwWulHA8s94+xP1uby4zZuTqOKMZgqfHL1OUZPe+dRqMclaAsk9q8iKoCj8IwJfuvNpJE25tu8zAHLRbWoKO0n6sTVKb8HqHZ7SZk55VSpQZcg1SKb5AYPNTcPB/pLEim3VVt5s4oL1mQ5jg2dqpkPqe0hD1da1TQak3KJrxsmmaaoglnVFBrMzbM+/IKJPmiVY91yXLWZvM7SSrzNK7dwxg0W5iD9tIBrl5Wg94ZoVlbQRTxPVSJAdcgk+IaZfoKqijdkCgd2wSShIuLWX8xkBKaPIEaiz0PksLoWUdzsRo8ixXc292qHlOrHMrSalNf2+GqMfUwBiQlypiVATW5ATXMSgVvtNi/OaC5KGf09kS1mTVkK+3lajQ9XGWxmSOX1JmluAaJwUXj5biaAb8aNaqXn8Nzjn41ZsBCuASDLN0Fzy5mqse2tUyr0nhlhbL86hR3gUvOm6hW4DvERc7cVU/NYOmchc2UqX/P5+BbZDiKEs+UYWWTxOiiYdpnZ5MuOHhCWJqjHtvdNFDlpMBF/72UP82a9UVoUVjrIaUWt6Lq/W4GVnHXCmfleqFmkAZfis5GDwz0JyMepY2sz1eTbyoJZJR4WAdncE0JZ0Gq18fvHrFMwIDeR635N11F/a+4yjtvWD38WkYFSZkL4kSEaqWqiigSVZIUSnwl/7BmZxrMlK1BcSqqWiv2qvdlLw2U4s6ooz/3vG81dnFeBoiu1F2uE9w+pY7eXn7aqT3n3OLU/SoKuq+8LjYHdTw1qKJOko/gzBO2oIY/+ihUNQW0Xht113etLH9pbsZOx2qQMHA4DdvDhJzW1m50zpWgi0MY4WxMaQdbN4RI3BCU8n+rKYGtucm5YdkVaxa74+t/Rf8VIfM4U3Nw/26YgWUQJVbWjOTiUCz3NJdZAh0NE752w3K2fNelhBpCfPDXqxCUbhq9iDK9nQlRkHwyuRuTleWKPfNJGVFww8TMohtSzmA8aonbWipmaFk2xvIdVLIEFoQwlb1gFtmTs9LtOJEUXy4SE8olUgc2PbMw+W24sk6XwiQIEKMwHTsNpn0jRBJpRsS3YWJTIH9KJYnPtWOEUly5lI/x5snz8exMEylDDndlRPf5eWw+K9dFWXC+JM9kBukZgXKlw6283GiMIR6kdTWt6bmgvGDlWwdUJrEcDAyAJOUpZOIKGbEknpvuiBZhPBh9L28WCt8/lmHIoKBFfUooyThnkBwurw2/8AJBQYnmKqFk8JR/WHGhK7d9yJ/piHZl+SeIx14vK0dRyqhGihgcNhKfclAJlqnSlTIeTyrncqTy3BT/GPqJQ7VsGJdeyLjar4IoI4o3FLGyzEaLpse771DiBAQymZj4FQJ5YR+PVcVy5qfeL44ukGWkh4+4QCI2NOkzukjF2hESi4KxaPL2v7tu/6fxyd6K26fHpSTXsh9zqfmMKwOqAX/4LqRemaKKzYrQHCpmZfIVqc8uudlZZq1F0zPSFMgc0I6VpOEUWjXdldRQEd4rltlxnHQbTijDe0V2q0hmA2tpaKoWMqG6S8+JOkdD2bHNkesEXUkDjwOAUyWROzBpFDl4fFQZfjMrQvPawuYt9sN6NBcfS8cqwk6KIikEAfwt3Nh/6GTsDRMzm65PzhFg3WIFySeXuzBZWc7QhK3KactPUMDymZ/FTFQOVKGZOpay2vxtKwyl0bLwdivfukURcXDKvCEt2UyP/Hf+6o6MQPnRKBX4231rt2urNoSsvbf4mnF31L+flOAFF+acMGyc3BO+DSe579/7LCl+P0g4xRiBPRdefhZc3vrrvu8+HwdaW/P1KjkRrKKgqaDjCMwsGuI4CIEmg5VEhV6dX5VTwb5OxkaZ8Fjg1obFAYs33AawuCgzlryTU7ZC3Hv+PxHoP3Q4OyjfoJITI1VkNI3BvlTEVRwpGVopmMgHwPjhyOjv6V/D48ttVgQnJqZOE+OTxxX1eHi4YoGwEMMJiKmzx1T+LysGiRZmbszrj6KqoXM1Q4pMRyyvU+tn8877u4e9Krm4wm6HTeeECTkSOE8iTJTTBo8OPzB9nvbXVY41NF+Q28n5ZeIbWfSV2gvl+rcjPy7bUbw5a3O5tPyfR+lOYWOZs4wojo7FFvrM6YOe0sEMq3WIa9SLmUkVlgUhz8nAm/WsflthN0Ot7mEUFDL79Y+b9hXaeo7exuzbk39ACiHS5MlEpI7BFKbi+FKjEUb3Lh9bhBIobQqFqpCPfhgynd5R4VmBZfTTMr15DaExKdnopNrrjeOnce2VT0Az2eFT+Wn/3+BciYI8hsNlLSOzwtb7F+2P2h2SJw75OSVKKyiLUCKRuPHZOS68VIJ3ZhPVqFd3Tjbe8goXY71uRbHZwrx2zEwnLv7lZlsnup2CMjC7SGjZT4Vt4gOsPIIbl0Sc0TqDz+DHrcDiVj99j8c/eroah1v17DE+6z48W/UdNGxiPgw2fyIMmiYQsNl5grSbFezGX53xaFNQna0u6uQ42724JCGpLYlQ0rMMJzcXa4klvcuwuGW9JVQzGzmVTYPtbGDD0lLl7C4qhh4grMn7QSH087H8GPKtf82+KKXwB/JujBIRl9v7GPHH9dF7MZ4gG4XdZg1JwNBC56E4ZP0CAoMfTSatrI1fq4xyvVAWPdQl/FTzR1LimxP1EMaJN0D8oJXfh2QjEWIkUoxAsmeeHv1XmvvqU5gkKF4hXfAofO5D0xNy051GzykcguZ/DCfs+eEiT+ZpKrL+9SbxpkQ68mrWUDAEBZyI0Ef4PkcqBltKXeQBbZA+DQIf8TueTAy2lrko/db7PBcNCRwND+5d0rsryYoa5XSk6w9fklexez2+cRmynRLIrnVbq0eamqZXa0qlFfex2pSyy1Cx8DuLz26jFSRYwiXfGGFkjiiDjXD/7iXqomeqMyqzMjIF6dxcOa/I958iSYnXV1jgclrQHy8tWT0rZVbFjNDXlQyGcNGB/X7u4hoj10X5FiSaUkkS5JYxkh/VpksJr0YXY+kEiZk5HVUcik+fOxgemxOWpdClTlx3MHMyTKT0QehS0ZAD5XKHSGTKB2nSN/0WLsBH6UOq4HdXwcmrmWwn9V1oKFjU598tob6pThqz2hovwK15lmE08Ezbppalzb721ZVmRU/iHDkZuJI8mZXEysrHUCPUObVvsk2hYKIQx5DDykWh4BCJnczGn/oeIiPbCr2DoQpUeO4jKZgY+JynXYAsyp79iKZpoI++ey7QLUgqer/GWNRcpr/wlXms9pLm/hfWEQFJkHQZqvsltBd/NveUEfb/jMycG6Zp0xxYKAiv8E5wRawqlnRAGYgBSTvRVka4xM2p1gh/L1L7evUOVrikgtunjCh1czRudlv5SReyDd+5Z5rt2CTNefUhTBIQL5OODHMUTVijklqrAthrchzZ8+0iz6+YovKJd56sEqsDlIgThIfQ+CS/7/RK5LZQ1OQguexi03LoidqjAhSZPPFTgi41NUH78wSZIkjekqjbGApur6h2+BzMjvWyT78WJAZZam+z0NfJD4+yio1inEypaMmajyMR4tcr5dfqvG4vrO8c8zOLJeAxISHPR6DQkeshh5MqkpLak5Jbk5K8OTzQRxgQQ6BDWhlIDOUwHnHgbw11y+2Oqxho7q6bJyMjVf2wjnFMBJtrv3hjsiRczfIxGn61JRQsSr1eDjw5VDGkCJPD5GvkYSti7IXvlxF8oOWkCTvSMzRIemFHJ0xcMeGwvZ8lTO6q+qCyDn5FsoT4wlH1fnnJMN/yvib2Lcc2yzUxTWOaua119jpvXWFdaR/S+9Me7NTe508GgXDDd5Ftl+c5MOmZBQhbuLRGl5Kur3YlmKOXExmYSBgCmw2Ps9dWmrj56DNhoiEPlpdRhJOLmM4dnsFSBAwcEx3tnp3mnppI7aXRuqkQCid5qmCA18/jp0ztMJq4pl4W3TWjbruo3w8vpzRtLueMjXckRwTeRu+aSoXO7XIvezDsCPrj4+syH9/IEr67b+1aDzHOcCnLLDmLM7566NMjLGd4By7zH6LPft+naXr90yzzjcwNBg2zl0/0/PgQ/v9I5J1XerCvpO8ff8UwhOeN3Moyi9Wvr+DqxRSllLk71MFZuRM1CiGlUmpjGrPIXbjVZVwQwk7j+KaZnnZY/JNDtPWO+NrKiPk5TwqZM09PWL2oC3HR8J0j/YnMH7XBDzwEiuMNHBBdbSN9ce7jR9FAzndksEhXvDzeBh/7xFk0kIuDmPRE+fsh9OBatfLXcGQIkTKte3buLBfIeFqXvr3tvZMHjYSvh5Av+9ink6d6tyf+xw9uhowf/uSP6MTf/zIi+D3187sg/JduWiyjvpu6H9qPbr69+vo53/2QGMJCI4WMjcxYJA1P75rGsMjdH/ZDRHpk6bwj30t+PIfe4MT+H9SCOOx/HoO6Z5oA2l46rmflbGr4qiPXH017YUK2NQFFuODB1ZpzIcTidffuXXgf1nz/5uTMCf2+/ySk/cYWFsrGTX62lMQqHnS8NGxmWnSDFlH4xsr9KQI0zgvSqtYWxdGTJbSKNflxwiF6pT77JujE/A3xOKLgipxHhccf3iSLoBEEi2YXx1Ws5TgFpda5n9GwVMJerGj55bctNHO2NUrFYuH8edkIG75NwO/7iyxZvTG6VgwJX31qVSSYVBcWXSdOBK869Rs4Etobpq4rykXmomlKp8OZ6LQ7laflriIXseJ7+tHU1Mv0xKAT9RBI/Yk3m5BYJJKNvzyw7JfiRV3wpNnGR7f+SYhnLSLvO5Vmn+2IR5JAR3OSRZPR2ykJran/B8fs/m41/J/ryXkB6P0x/zI6lgAIQHcx8LpAN4lHfMW1NW/o9RIxbv22Qe/2e1cPEiHdU/KhsckSInBcnptLgoEJeFz/iJdaFdJHjJVv2PKu9bQ9K5b2nbWFgEHM22NpxrmAAEEckNkOUifclu5YNj+25jFy2IyxCFj1x+sB9r/5APeueICH1zzAnsvFB5ET0t39wNW2M7vWv6LdxEdp7jr45gsbAYYUBRhPjC0GVk1+6u6Jv7NbFXq1hdmISBTUsH0aJBywfYWJ/1svIHsrsne/aD6UBcGhXWlicN/+176+dt9zCTYeWwy8yejjiZb+u7KMeRsnxRhb2jBvf/eyw7t3Te4xNADvndX80FNj703aIK2561mCJrNTe+fJverLsVfaKq15zmbJmP934fhb+rm0Axmor2Lvnft8k4cjDrWA9upz5yLaWoA3cZloEp7cmwbTpMVsRX46xwE4BbMYMjkbnS/NPbnb+P8HANlyZL/GCaCW9HnZgoZ5oxFoE23QF5NmRqNohN+D/Jhsvs+HsVWF/3OHXOg2iAz0n5FazbqRWMu6JFQILcBAR52TBFwh+AhNClYPycJrqkBXOsGYkB0S7cQORSl4Bf0C/P9BzopSC9aNVBPWJRhJu2cGwDjTND3DBsIGwOehECyQFPIOArIRA/f8P5DvLLTDjZIV0yJLT7/pjdX1KtW9KqBHr40cBWrEQyKcmKF4Cn7wi3cE4HAFAWJglKKCKmqhVmRGYx9RH+asuNYY1o3zBmDaZuekahYWScZwPWRjvcGc+dtL6IQvIeQ4kJxvNiaFZCgX5Q2NYiahYeZQ6IpVbCRWcxM2uQPmwx5Mq2aN0klTRf86zqoZScjuZQGB0GOGZbY6MFMA2cynKwJHrmmemefN5mqAXflhYa6Yx5EMcHCcjDCZn80ad6uCm8kZm2MGsw/NFpgjAViO5dUKxuVKmlfzQwC4TPSbydEC5QSwtt9I73uKgw/q9gL4DSRUX2gyKoFQhb8gV16WQ/okWwKYBolLZVtKmdHCCJAj44hKXysvYeT7AIvkiTJSgA0opHo+HVIMCC4g4BLKIM5fcnxNLakqUH4uLAEAB13WoBXZSBiicWiVvkA6ajKSvDOAgHqqcEDlyEAoRVxNim1hbSLxalTNqql7skZnS58EiyLqnPSQ2GKE7W137FnkMU+HP1z7on2BoL4lQnOxCkAp2D/S4Inu/QF0BdCR+RRcbw7WQcGcc+wpjVtS0y2Gg1Gf+UkhJD6CBPQLdUULgsiygMEgEdI5kIOUjGAQSoUYwD86Z6ENalDuB2XkP0AX+RcORZ/yeR1bs/Ktz6zZk+qkKxlKHk54TNGIXqmrdZce0g/r0OHlt7Bar221M+x99oFsA5H4dud1rW6Gu89BPEkbLDLHA7Ci7YoC9VKGF45gQ1GMLOUMwFMBphCHIVyI0ErKQtOBNq4kL7XSDLqPQhnajvBXlVe1qhnqPrUPuMz7DSgWsStNtekyQ+ZhE7pcLIb7bGgLcSWizL1PBBWwbmzourJY2a5oCMf9uMGi3oMrc939JFlUfbkXOzlgAF5hVvzwa6pkBRVEd9CLvPX8yqbT3navzJQq9jmlKU36CfqZkhpoWlAyGMWKBlwwVF4YROj+DeTK9qZQF2I6i4LWWhsJ90JKqmg+UsQ2jCYM1LkEY8C9zVhMMcoPxYYKHAmoaogWXMUh19mVKZXMx4zUlZRxvEcwPhwiZJMiaJcNm7mZK8U/+if63eoB1Aca43z6gPitINBFXfdop3P791r1HgjVacfgL9sZaV/HxNZj3WUl7PYxHOIBOi09kIQQKhcDNrvex45a1tqfd7VgQfajUy67cuJUeDL5zbwjh7FO46CwZLQj2JitMQj4/YoYVhfImfyApl0/XvpJtb++XqmyaqtFfZBWJ6lL+VgGo6vB31jy0+/UDrps1MlqDRdWCNKQLhAYgWB/kXjS4w7BeJkI9rXAoAgTTBEWzitwgXNrmhVUYU7S8Foo0k0SXSI6ocHxgkJrqWIdKpXoVF8szDuas5r+z5VBh0RaBzCAOZialRQjW9PUwWo1Bdx4kt+l0E3N7Q9Vx+qWMD1Qi/s/GOvKDO7sqQYIDrqck3JCJJ+SSsGXQIzYVqU+rhUkumwSwqHpxLIj60tvR0x3qsOTw9FEgdZWVcOjbaUIdidq5dReoBBQ/tDSMKAOx0sfM0TQ0Jh9wMMSFCOcGPgNKIwMN0pqIHnrNTZPbo6VQ4o3252TCq/flYU2TPUI3pT5pRlvHsgKTDRtybSnsoDiSxZD8YhfqAHFWNR3IlG6AxBS4Rktrn35rZdoaYffhz2cFbHYSBKheMCJ8M4TArRW71TgiZR0SW5mhcAjbvxTDDTYgdKymiFGqNtM78fia5lrL0TPCAYEaiB9pjkjy6tvBhI4QDowEqAmWKuWeyljKwdepoM1I0RvT/S1RHeJP6VQl6qBfoDrh4S+W+n7tD7IxCfYZfu9vFty7RN9mxKl5+J0vR96V0p7uFDyk4YDCI9ImpBIHx+orKxx1/GW9qCFKrJSBW2DiuyEWGf7QM5nvuLk+kauNwh9gIivkou0jvI0aYAvEjYUVlxVXd8J5J2k8PYX84tylvPOIRZyQnDJNm6Wqthh1IDcG1lgT0swGxy5gFWk6DPivn4H7DOFwBJIccYzOEPi4CKJAC6hnQyBZGnAZiP5VKhcFuElNRXsSkA4PYEV5j83d2RkAf0orglyTIlgDwNGlWPJH4txJA26Na5h0NnFRk4++Okm6yq0MkGVtkmLtwwYDMeyXKODH3ch3mCwX0E/wAFssCVN7GYkZ8bZ7B1UxwdYhIi+20nX4S8iEyM8FUkRVZKoRpA0ar/Lmsc+TVPqh7SoFWVpA7UHMSlP90lT4qoSq7wnxTqRuYTWDal6rp90uf9ac7TKIgXNjQBakhG7wdBjWKVTf+F8t5uKi+qjHRDM4gbnqrZWtjVW1iussdbHPRE/4tARB/3SzTjCfudUaOedDxTbuybbfj+rwJ49XOfyl7hfEWLud2Y4VC4sh4erpohah7EODw6MFRivre5upve879YW53I9wJzmDyu0qmk+zoMejEppZRCg6F1QK8RDIAwDrxWJeH2wDqzMFtJb+tTDC9Wm90RlQuX9fdBCl/J0UKIptTK3OYaVSvXzzcKaXCVpNS7hm56RE86c/7nEl4ZZ2iNuqhSbVgOWRITnk6I25wo2BhOp2IkzWrYS4Qwm28n7oWawfvY6n+0rRmUkctZVXYwzG5BY0+hRglHHuxqMZL5QsbmxL7aDYVuEk0HFDVOioXXq3RhOH6OH38vldVR53BW1VjQyaUSn80ofyBb0ku4Ud0W4R6G4g7VsREF72XdwqEymeT2mlfm+z8Ya/DGJioxWNSQKByA6H64ZOJCeIvpVQn4yxMW3URY3ielmC/uYaEIpk4kMpBWG+RekSytlCImwjVhoCrgXhdZBztTyVviHqIxzuydm9G2FrjMU4clO2WehVM1hBVXj8Q4hNA8qjKQvEPoitXMT/fkeO32X+8Gd79c0FwUFZIVn5Mcciy0D3PNEeYrs5iwSZIdcnmSzGznSK/sZiW1p0bCwMmbpfOrQnVICDtCocGBUIM5dCSNGC2zZqmmCu70FJESNROnrqSuss4vDpJeMvxDG851mUwxbUQ/0I7Kh9Jw0hiSTQuArvkoN7qnS7cKyUdB5vXTDBoBoVUIMLo12yszjllmpaKiqZ+LTvCA0ex6MHXVf+GxEPPxY/T/te2lTmZwL8yc1HeXR9Ii0CyObwmQ4Azof4TQqyKGPQFgk+xNJgSw0LHEJbFeatXTYnhbtAlRRTRu1laJmY+LiiQIvssRSGx1mg+ACDH/SFn0dJ+jb8wc2GNHlVuEqIg047BPsBXI4rckl3EAPRkBGN7Tfp+Cd1wsl8UYaWs19VIUz+3HOJ3fNJrObcRif6TazzSPGCMMZZulzQaw4Dv228CTGEUsuPT557UeE8sZaTFDpM5Eoso9EAFmmIMC8PNnUrbnRNz38E2DTRM526J4jXkzoDtucUXSbNaEzffs1RQlrWsclA0x3j1Nqu37Ndjwbb2bYjhdZetLms80Oi6cKRtZGmrKxsKPxN4wLqSENACrsm0VgJW0Ub/x2TzAclCFrGDLgq4flkLK0nBWVgikkOw0YRgYz7aDTID4kZrxV3ZBy3Gx0GkPDWXM054xzQPM9cG5TtdJg4azyDfjpja6dU8kKu/aF0nWycUi5gXYJZ+ZujeNNK9aRoLhnYiyThgPTBebz5c1i/khnunvFTBSrt1bnnutkzVDWFOuvumI9H+GU+e23s01FrDLQAelTZE4xsnZ9cZ2IWNHS+UzIgjgnh4+JviWKwryqynF+Hz5pOlIqW+1kIye/A8RKRrwr8YLEonnXE0zcpXQI60ChRM06uokC5J0JFCTjurlCKfFjKQVj0Iy7FLmx9dHRTPkXe3KBDZtv3c78reKvsLTXW7Gbz+elfn+1r7eWMD+B6Xo+vtL32vjMOKdlJUtxdHXr22VVQQcogTN7Q6f4OdRFgTiTEYH4Ja2lwojRsHMSOy23ptkov9OZQTK0DMuGLcNAbocaX7BoLmTov7INgsGe6pLzNOuGgQqCI4S+5B0oIS4XC4sV6dqQtIrIBlbCrTElFnkxdqyCQ+ento0hEhaZqBEVL4OA6MZ4jDyEfFqJVpE1Qgg9Wngp5EialgoSUNNHSfhayvKJ5daP5Cldto6JiwA62CQ6KLP7RsodKyqhKj9eJp1rsLIxRadaNfu26h4GP748PapC63vObn+jJOmwmMQtFrzEN2KbfuDYrRmVJVuxjI1qzXDYOt9yM0JzEWUr6CR4b5kpsHluEG+9UOICyaRm6kYhk/+3C61hq2phabOXdETscXNm+LDWHc2FfEYmK70dAUWhw0UUMohysfsdqi1vuRJbypovq9cLhZP3TjrOnTgXww/jpCauBEW1bXonoGYyf0azrWRzTPrVesK0h5qrlfQapUsq9CepVxlxI2xbebkU7ZaV9O7AlqKoyRFH2OiWonmin9XJfTczOe8lrQd+0Q5DbJg8LwrXU0K3pe6oeFI/TP82lwmkJnxSsCZr9nASnBBRy7Vo1Z6nul6HdZjhdLGrsQg9PVMAWG1pdhyZhrnsV+mOOsLgH6LSMof9oCqg93Wo1+6rVnVEmNiVKTD/CLbnlw1grXyGdo/PN6eG58LEWPljNQFfZV8ZnxLHej5W2pjHaoa6EZXPakw81qrSfZgsJRuliPuZW7vRoHLRVGKCWS1Uqlr3VadGnXfqyRdMymiNp1F6jtLS8eqf0iui1Jl4E5C7jlSFZ6qEsUWzU9/LbZKABBUTmZbKiha7lxwEUtA0RpJaqitxP5Kp0rSyG5X3NvJt6o2wDZ6EsnJvCSuQ1p6C3KdUQMk25ibkp1DvRnrPCGihi1Ur3UqOuA6+LF4quxND4koa45ZaQIiF4yiFbHhh0VSfbxbS8i2kUK8HUEw1cX6ZCIjlw/zdAFCXdjvffyqHTs4aZrNFud5oM+m1bRXldqPjSa9qY1ur6vdh21Q9nCpXOZVmy1AjsF4ewqNMMyKWEI/2UXiAz3TCdJ8oqLdRukdhiDMS/1Nk4RoYzqzdgnGwW81Wjyh+pQa81WGRFyy8BWSNCsg9FGrbXyDYawSLitBvTFf3IghMh2TkjD0VvJBGJhlye7lQlv9CL5WhbgQyqK7Qw+GJQAfzawWMgKl2UJQVwjuCRBNNiWOr6dOdIbMdTcG6sbakGqhu0rhh8wxKk/B4s8xXwbXMBPXNHJugzOKlKH3S/pqw/GCt9Tz/exLQPV4W7oxWWe3WprnqWcTofoAOdCnrM/WKTI20eEEF195BWGmIbHdxeFLUIpackLsdMfHIb1TKH98YYbZiG/RONHCA44e0HTBc3TW8IYrbXloCOEoGB+31hbRST87P6z8HaERqBJ8Sh5xtj/PaLcuL2++wM9lwFNbBQX6FeedKCy1bKm9W/PdkgG3Mb/AJzL2/RJ8HSWmXEgIy+4A8DFbkCSRlHMEi4Ro0RmsvBjwxu2WWdBakbb27ZUz6EMTQ4V9shrFNHm/aXi8+TFCwwpSYlFSvkR7fipKKHGronTq79owd1UlyWW1jJImkXh7VkK4CPEe4wsdRSMVSjMMc1UY68yxBJteWGyPLOQfqV1m1Cbyw456wCkIrjSK7U/VSlE74rtebcfwbksZ6hckLmGTgIDsdJFsjDdM/6OGAXr99ykbSGuYsHET9BvYlq0R4xNCoWbS4Arqdr0zbKSLaheOuLwvW1yJ1Rc1MMQsY0XchFFdYejSKR6bp4GD15Dc655qu5/LDM4FM7WBZUdpM4QwadhTlX/UTMte4wKXPPck5nIz4/iEwdMMZgnvAQxlUf3OhTuK5Tc6qcQjxj5VnQD/Nmx1j6CA88wzv2zcgcfTb4VNgA6Eqr/U9cI1pitTQvgb9FblUhbLBRUy97YN7LU0jq0lMPxUi0XhekFDl1mNwuQn6jSpYhsvdq1F9DwUCC+ucbEGwki7l5gLmQnal2FeO7XxUSzspU9HKPsuDslpYDnRtWfVvagQX5BfwOCZI7qatczYLUGIo3xJlG7Wi1q+9Oa4ITKJXl8x/XIUwT/ukvwz1/3iYvxH/NgrhMZxaOa+Z9TI6SC4uuVQ2kv1uMgAkWQJD11uB0oDXRzStVe7BFlVIGkmR0AZ7L2qvL+Au3JekgAD3aAyNX/uzM4r3f2iK/hsRwI9+2bM2/Kj4//jXh4Gr9JdEoCABAgAEol8eRBM78WB88krgKlIAN/koUZBGefpcwNjfxPQkzjhO1Fc4voMhZ+XnrIzclts24gTDbP4RnmA4sK453mE21eImWkaiGa4PdKUUekqsJXHuJ6ktVtV9ZCPIJGOo+fV5W1lC3tWafxvjgYKR3lUNkhkGNQv9/JzCpC8VdULqgkqZ3c2im5l2Mc/c0VYXZO6QlESpNRsVymk9Zwk8KsaLB7lGKa3iDERiIPNr8ZAtHvsBlkpaidcmNKuXl5kMSmUicpbl4rYpnMPXdU4DmsS3drL+xL4IbaODOJtEtFhaV9FShKaME2DlsQAQn1vLFpsVp8b8OAi6Do19onjJJ+DmH4TMDzgAKLeq6mHkfANRHusMDnhQQZ7jKcUQnS/Xf2gjHgSBxQHgBgK8cpxNwI1YwjhEMh7iSWTIMVCEWoHrcSN+gzfwFZwnhMgLGDdKMGzFiys35hghFm3MzxmVgwYDaZaGZpKuoD/+YNPNdu6j9cBifBAvwFXYh2uxA9fjJnxmZH7e+wGnZcRxL/gBXGkYNAQJ3B8WoA4o8B384YQMshkBAAAfQK8QE3wUinSMokA4Oay4riiZV6MoYx5XVBzvWwWcgjqqsAbF4N9VSbHQ0aytF/ZBCWBLZ2FHH45QjM2AQ5Tpnis1KArO13uVBBpMKBoylobNumLhVoNSHHh2qcLwpblW8TCx28IBlJT+xp6s1GAl7Nw2C9dBacC1oSbcog+3UehUfFvLlt0z7cVB/DkIPf5p3jL5iQR2Ie0YvG7AaThIW+GK9qyGqVCFCr0GvBR4gFOjcpVJp1cn52dnqCrrT835yWnTsTzYh/T0V3+7/w2i90WTYb0yrWsdxOyc+CcmzdSGmpxEcuJbgEDiq0E0Rf5YCQh3RdmBFVUzGOAsPMwrTzV/8gTensoTzbDn94Ti4o24RYD1nqilTwuV4ZrVq4cFrCWsnZPVBlKWmzRuSy/mBu9GNsqRjbDccE1B7wh4HCnAw6ghs9rRV4QKI0iRRpgXWtY3iQxhQMkbQ6C7WHbv2XzX6maGj9nNIFnd7tQOKiZRMyjIN9qgFBj0W0emJmhyNX7+VHcR6mts5z5MI+hENbkmOgEHB9zViefzZOMFlyYpRIX9Fwdwent71cHZyekpvGXyEwnsQgLfALVUy93xKK5/uBtthYNgic1Ynrn9t7vb3n54gATn5TuFOqGcXp2cn539Fjh+SZz1+OZcx0r4KsCV+4jd+JRXf7VOfSNE45zzQlxumjyze/gHr9OV6p+YwhFlavDDEsfyj1kOaBpJC0wwgPyioy14fPnZGwsS2JplzEYgAVOyRwYPLCT3leaYY8OZ2aWi4mVsqLAfc4kcNeblXQx38WcUzxaZ6orXSKgqX+McK5Y6hXGhTVcO/g3hqiiZp1gdmxusW89YrOPPHKcVdPh9Vc06JizYxdaZsc0gLVg8TwBzIB1Dn2EeBPi1nIJzLEvTc84pjGG5QhHIlBbz0nbGU59Fy6l2oPLfAl+Z+eVfSHonrPtwtR/IUqkn7KfIvnlxg/1YYvcZwEicE7KWzZmr02MRMTj/zXaWnAN2Pcd9aOJ1hQtxThffeX91uZDNwcw8H+sYgnNk+vbY3h3qATjHxFWggST79VbIMmqpkynh2S3csaLKQU52fwlu1/0XEPbwqWcBzfNdZadjtzP0t3aLdc+mzT7t7ctPk5fZ/T0/xf/GNB1X4vi8PjjRv9p4HiEJaT9Zl6WcHgOGjBgzZcaSFWs27Nhz4MiJMxeu3LiPsNff6z5ExCSkZBSUVNQ0tHT0DIxMzCwK2DgUKeHkMt2gJVPGbTpkzEvTTLrjhjUO2+2YR474U55SIwo8dsFZ5/yl2HxPjRpT6annBpWp4lOrRp11qjVq0KRZqxZt2j3RoUunbr16rPfNC9s9c8ddfzvlsx2+uuy2cddcd8sVN/3rjPMuuGujc+6Z6YjrbnwcCcxBigw5CpSoUKNBix76GGCIDmMwFuOY1NIqvBktL1MN22irkrFYnseaA0qdJ6y6kHpih9WcDU4zt9vcQXaa+bSk2kTr2uBS3CbjQi+0eWxb0+RODtyZ0W56zccuUaMUSMcv6VgbxSFmawt5B847nhUCW7HSfLSrX/CnCbuxGNJHGFNP9GD8CG/NyyHQJShJuuptLw7H/oHf9cT0jQ757jHdP3F12jrLmkMv8oXJ7dgb7j7gOPpq79Qbzj5ulf/hGxcdeBAdUwfs1EP2PS3S1dtd9LATd4/yV8lJVvz4XSqcPCSPuujsvbcjNJjsCvStc/bwhMNzLpEj97lRsCZwsODt0rzxQwfX3igLptCE6/5EyDw4jyNYhNXoysiCdRM=); + font-weight: 400; + font-style: normal; +} + +html, body, section, ul, li, nav, a, h1, h2 { + padding: 0; + margin: 0; + outline: none; + text-shadow: none; + box-shadow: none; + border-radius: 0; + text-decoration: none; +} + +body { + font-family: "Whitney SSm A", "Whitney SSm B", "Lato", "Lucida Grande", "Lucida Sans Unicode", Tahoma, Sans-Serif; + font-size: 17px; + line-height: 1.5em; +} + +::-webkit-input-placeholder { /* Chrome/Opera/Safari */ + color: inherit; +} +::-moz-placeholder { /* Firefox 19+ */ + color: inherit; +} +:-ms-input-placeholder { /* IE 10+ */ + color: inherit; +} +:-moz-placeholder { /* Firefox 18- */ + color: inherit; +} + +h1 { + font-size: 25px; + text-align: center; + color: #38a8e0; + padding: 20px; +} + +h1 p { + font-size: 17px; + font-weight: normal; +} + +h2 { + font-size: 22px; +} + +.logo { + float: left; + margin-right: 20px; + display: block; +} + +.logo img { + height: 55px; +} + +nav { + margin-top: 17px; + text-align: right; +} + +header { + height: 50px; +} + +section, header { + border-bottom: 1px solid #95d4e7; +} + +section, header, footer { + padding: 5px 20px; +} + +ul li, nav li { + list-style: none; + display: inline-block; +} + +a { + margin: 0 10px; +} + +a, h2 { + color: #EC008C; +} + +a:hover { + color: #671345; +} + +.highlighted { + color: #EC008C; +} + +.make-center { + text-align: center; +} + +button { + -moz-box-shadow:inset 0px 39px 0px -24px #e67a73; + -webkit-box-shadow:inset 0px 39px 0px -24px #e67a73; + box-shadow:inset 0px 39px 0px -24px #e67a73; + background-color:#e4685d; + -moz-border-radius:4px; + -webkit-border-radius:4px; + border-radius:4px; + border:1px solid #ffffff; + display:inline-block; + cursor:pointer; + color:#ffffff; + padding:6px 15px; + text-decoration:none; + text-shadow:0px 1px 0px #b23e35; +} +button:hover { + background-color:#eb675e; +} +button:active { + position:relative; + top:1px; +} + +button[disabled], input[disabled] { + background: transparent!important; + box-shadow: none!important; + text-shadow: none!important; + color: #dcd7d7!important; + border: 1px solid #dcd7d7!important; + cursor: not-allowed!important; +} + +.menu-explorer { + color: transparent!important; + display: block; + display: none; + text-align: center; + position: absolute; + margin-right: 12px; + margin-top: 12px; + right: 0; +} + +.menu-explorer img { + vertical-align: middle; + width: 25px; +} + +@media all and (max-width: 900px) { + tr, td, .logo { + display: block; + } + + .logo { + text-align: center; + } + + nav li { + border: 0; + display: block; + text-align: right; + } + + nav li img { + float: right; + margin-right: 0; + margin-left: 12px; + } + + nav { + height: auto; + margin: 0; + display: none; + + position: fixed; + left: auto; + right: 0; + top: 0; + z-index: 9; + background: white; + width: auto; + height: 100%; + box-shadow: rgb(84, 145, 208) 0px 0 0px 2px; + } + + nav li { + border-bottom: 1px solid rgb(84, 145, 208); + text-align: center; + line-height: 2; + } + + nav li a { + padding-right: 3px; + } + + .menu-explorer { + display: block; + } + + .header { + position: static; + border: 0; + box-shadow: rgb(84, 145, 208) 0px 2px 0px 0px; + } + + .no-mobile { + display: none!important; + opacity: 0!important; + visibility: hidden!important; + z-index: -1!important; + width: 0!important; + height: 0!important; + overflow: hidden!important; + border: 0!important; + box-shadow: none!important; + } + + nav a, .menu-explorer { + font-size: 15px; + } +} + +@media all and (max-width: 620px) { + button, input { + display: block; + margin: 5px 10px; + } +} + +@media all and (max-width: 500px) { + h1 { + font-size: 18px; + } +} + +@media screen and (orientation:portrait) and (min-width: 350px) { + .header { + position: fixed!important; + border-bottom: 1px solid white!important; + box-shadow: rgb(84, 145, 208) 0px 1px 0px 0px!important; + } +} diff --git a/demos/text-chat-file-sharing.html b/demos/text-chat-file-sharing.html new file mode 100644 index 0000000..a2ad8f7 --- /dev/null +++ b/demos/text-chat-file-sharing.html @@ -0,0 +1,306 @@ + + + + + + + + + TextChat+FileSharing using RTCMultiConnection + + + + + + + + +
+ +
+

TextChat+FileSharing using RTCMultiConnection

+

+ HOME + © + Muaz Khan . + @WebRTCWeb . + Github . + Latest issues . + What's New? +

+
+ + +
+ +
+
+ + + + + +

+ + + + +
+ +
+
+
+
+
+ + + + + + + + + +
+

Latest Updates

+
+
+ +
+

Latest Issues

+
+
+ +
+

Feedback

+
+ +
+ Enter your email too; if you want "direct" reply! +
+ + + + + + +
+ + + + + + diff --git a/demos/translate-text-chat.html b/demos/translate-text-chat.html new file mode 100644 index 0000000..8f14738 --- /dev/null +++ b/demos/translate-text-chat.html @@ -0,0 +1,370 @@ + + + + + + + + + TextChat Translation using RTCMultiConnection + + + + + + + + +
+ +
+

TextChat Translation using RTCMultiConnection

+

+ HOME + © + Muaz Khan . + @WebRTCWeb . + Github . + Latest issues . + What's New? +

+
+ + +
+ +
+
+ + + + + +

+ + + + + +
+ +
+
+
+
+ + + + + + + + + +
+

Latest Updates

+
+
+ +
+

Latest Issues

+
+
+ +
+

Feedback

+
+ +
+ Enter your email too; if you want "direct" reply! +
+ + + + + + +
+ + + + + + diff --git a/demos/video-and-screen-sharing.html b/demos/video-and-screen-sharing.html new file mode 100644 index 0000000..2f12d9a --- /dev/null +++ b/demos/video-and-screen-sharing.html @@ -0,0 +1,414 @@ + + + + + Video + Screen Sharing using RTCMultiConnection + + + + + + +
+ + MenuMenu + +
+ +

+ Video + Screen Sharing using RTCMultiConnection +

+ Multi-user (many-to-many) video chat using mesh networking model. +

+

+ Add and remove screen anytime and multiple times! +

+

+ +
+

+ + + + +

+ +
+
+ + + + + + + + + + + + +
+ +
+ + + + diff --git a/demos/video-broadcasting.html b/demos/video-broadcasting.html new file mode 100644 index 0000000..b18573d --- /dev/null +++ b/demos/video-broadcasting.html @@ -0,0 +1,316 @@ + + + + + Video OneWay Broadcasting using RTCMultiConnection + + + + + + +
+ + MenuMenu + +
+ +

+ Video OneWay Broadcasting using RTCMultiConnection +

+ Multi-user (one-to-many) video broadcasting using star topology. +

+

+ +
+ + + + + +
+ + +
+ + + + + + + + + + +
+ +
+ + + + diff --git a/demos/video-conference/index.html b/demos/video-conference/index.html new file mode 100644 index 0000000..0df44b8 --- /dev/null +++ b/demos/video-conference/index.html @@ -0,0 +1,765 @@ + + + + + + + + Video Conference | RTCMultiConnection + + + + + + + + + + + + + + +
+ Video Conference + +
+ + + Active rooms: 0 +
+
+ + + + + + + + + + +
+
+ + + + + + + + + + + + +
#Room IDOwner IDSessionExtraParticipantsJoin
No active room found for this demo.
+ + +
Video Conference using RTCMultiConnection
+ + + + diff --git a/demos/video-conference/video-conference.html b/demos/video-conference/video-conference.html new file mode 100644 index 0000000..4f3f238 --- /dev/null +++ b/demos/video-conference/video-conference.html @@ -0,0 +1,266 @@ + + + + + + + Video Conference using RTCMultiConnection + + + + + + +
+ + MenuMenu + +
+ +

+ Video Conference using RTCMultiConnection +

+ Multi-user (many-to-many) video chat using mesh networking model. +

+

+ +
+
+ +
+ + + + + + + + + + +
+

+ You can write cordova/ionic/phonegap based iOS or Android apps for this demo as well. +

+ +

+ You can run same demo on Safari-11 as well. (both on MacOSX & iOS) +

+ +

+ You can install following Android app and join meetings from this demo: + + https://play.google.com/store/apps/details?id=rmc3.videoconference +

+ +

+ Microsoft Edge is also supported. +

+
+ +
+ +
+ + + + diff --git a/demos/video-conferencing-chat-filesharing.html b/demos/video-conferencing-chat-filesharing.html new file mode 100644 index 0000000..058c599 --- /dev/null +++ b/demos/video-conferencing-chat-filesharing.html @@ -0,0 +1,357 @@ + + + + + Audio+Video+TextChat+FileSharing using RTCMultiConnection + + + + + + +
+ + MenuMenu + +
+ +

+ Audio+Video+TextChat+FileSharing using RTCMultiConnection +

+ Multi-user (many-to-many) video streaming + text chat + file sharing using mesh networking model. +

+

+ +
+ + + + + +

+ + +

+ + + + +
+
+
+
+
+
+ + + + + + + + + + + + +
+ +
+ + + + diff --git a/demos/video-conferencing.html b/demos/video-conferencing.html new file mode 100644 index 0000000..afb0883 --- /dev/null +++ b/demos/video-conferencing.html @@ -0,0 +1,460 @@ + + + + + Video Conferencing using RTCMultiConnection + + + + + + +
+ + MenuMenu + +
+ +

+ Video Conferencing using RTCMultiConnection +

+ Multi-user (many-to-many) video chat using mesh networking model. +

+

+ +
+
+ + + +

+ + + + + +
+ +
+ + +
+ + + + + + + + + + + + +
+ +
+ + + + diff --git a/demos/vuejs-video-conferencing.html b/demos/vuejs-video-conferencing.html new file mode 100644 index 0000000..3ee3b39 --- /dev/null +++ b/demos/vuejs-video-conferencing.html @@ -0,0 +1,260 @@ + + + + + Vuejs Video Conferencing using RTCMultiConnection + + + + + + +
+ + MenuMenu + +
+ +

+ Vuejs Video Conferencing using RTCMultiConnection +

+ Multi-user (many-to-many) video chat using mesh networking model. +

+

+ +
+ + + + + +
+ + +
+ + +
+ + + + + + + +
+ +
+ + + + diff --git a/dweb-2.html b/dweb-2.html deleted file mode 100644 index 6cb25f7..0000000 --- a/dweb-2.html +++ /dev/null @@ -1,61 +0,0 @@ - - - - - -
    - - - - - - \ No newline at end of file diff --git a/dweb.html b/dweb.html deleted file mode 100644 index 7257b95..0000000 --- a/dweb.html +++ /dev/null @@ -1,28 +0,0 @@ - - - - - -
      - - - - - - \ No newline at end of file diff --git a/gun-server/node_modules/.bin/mime b/gun-server/node_modules/.bin/mime new file mode 120000 index 0000000..fbb7ee0 --- /dev/null +++ b/gun-server/node_modules/.bin/mime @@ -0,0 +1 @@ +../mime/cli.js \ No newline at end of file diff --git a/gun-server/node_modules/.package-lock.json b/gun-server/node_modules/.package-lock.json new file mode 100644 index 0000000..a9277c7 --- /dev/null +++ b/gun-server/node_modules/.package-lock.json @@ -0,0 +1,879 @@ +{ + "name": "gun-server", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "node_modules/@peculiar/asn1-schema": { + "version": "2.3.13", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-schema/-/asn1-schema-2.3.13.tgz", + "integrity": "sha512-3Xq3a01WkHRZL8X04Zsfg//mGaA21xlL4tlVn4v2xGT0JStiztATRkMwa5b+f/HXmY2smsiLXYK46Gwgzvfg3g==", + "license": "MIT", + "dependencies": { + "asn1js": "^3.0.5", + "pvtsutils": "^1.3.5", + "tslib": "^2.6.2" + } + }, + "node_modules/@peculiar/json-schema": { + "version": "1.1.12", + "resolved": "https://registry.npmjs.org/@peculiar/json-schema/-/json-schema-1.1.12.tgz", + "integrity": "sha512-coUfuoMeIB7B8/NMekxaDzLhaYmp0HZNPEjYRm9goRou8UZIC3z21s0sL9AWoCw4EG876QyO3kYrc61WNF9B/w==", + "license": "MIT", + "dependencies": { + "tslib": "^2.0.0" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/@peculiar/webcrypto": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@peculiar/webcrypto/-/webcrypto-1.5.0.tgz", + "integrity": "sha512-BRs5XUAwiyCDQMsVA9IDvDa7UBR9gAvPHgugOeGng3YN6vJ9JYonyDc0lNczErgtCWtucjR5N7VtaonboD/ezg==", + "license": "MIT", + "dependencies": { + "@peculiar/asn1-schema": "^2.3.8", + "@peculiar/json-schema": "^1.1.12", + "pvtsutils": "^1.3.5", + "tslib": "^2.6.2", + "webcrypto-core": "^1.8.0" + }, + "engines": { + "node": ">=10.12.0" + } + }, + "node_modules/accepts": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", + "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", + "license": "MIT", + "dependencies": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/array-flatten": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", + "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==", + "license": "MIT" + }, + "node_modules/asn1js": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/asn1js/-/asn1js-3.0.5.tgz", + "integrity": "sha512-FVnvrKJwpt9LP2lAMl8qZswRNm3T4q9CON+bxldk2iwk3FFpuwhx2FfinyitizWHsVYyaY+y5JzDR0rCMV5yTQ==", + "license": "BSD-3-Clause", + "dependencies": { + "pvtsutils": "^1.3.2", + "pvutils": "^1.1.3", + "tslib": "^2.4.0" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/body-parser": { + "version": "1.20.2", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.2.tgz", + "integrity": "sha512-ml9pReCu3M61kGlqoTm2umSXTlRTuGTx0bfYj+uIUKKYycG5NtSbeetV3faSU6R7ajOPw0g/J1PvK4qNy7s5bA==", + "license": "MIT", + "dependencies": { + "bytes": "3.1.2", + "content-type": "~1.0.5", + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "on-finished": "2.4.1", + "qs": "6.11.0", + "raw-body": "2.5.2", + "type-is": "~1.6.18", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.7.tgz", + "integrity": "sha512-GHTSNSYICQ7scH7sZ+M2rFopRoLh8t2bLSW6BbgrtLsahOIB5iyAVJf9GjWK3cYTDaMj4XdBpM1cA6pIS0Kv2w==", + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "set-function-length": "^1.2.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/content-disposition": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", + "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", + "license": "MIT", + "dependencies": { + "safe-buffer": "5.2.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.6.0.tgz", + "integrity": "sha512-U71cyTamuh1CRNCfpGY6to28lxvNwPG4Guz/EVjgf3Jmzv0vlDp1atT9eS5dDjMYHucpHbWns6Lwf3BKz6svdw==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", + "integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==", + "license": "MIT" + }, + "node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/define-data-property": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz", + "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==", + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/destroy": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", + "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", + "license": "MIT", + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/encodeurl": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", + "integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/es-define-property": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.0.tgz", + "integrity": "sha512-jxayLKShrEqqzJ0eumQbVhTYQM27CfT1T35+gCgDFoL82JLsXqTJ76zv6A0YLOgEnLUMvLzsDsGIrl8NFpT2gQ==", + "license": "MIT", + "dependencies": { + "get-intrinsic": "^1.2.4" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express": { + "version": "4.19.2", + "resolved": "https://registry.npmjs.org/express/-/express-4.19.2.tgz", + "integrity": "sha512-5T6nhjsT+EOMzuck8JjBHARTHfMht0POzlA60WV2pMD3gyXw2LZnZ+ueGdNxG+0calOJcWKbpFcuzLZ91YWq9Q==", + "license": "MIT", + "dependencies": { + "accepts": "~1.3.8", + "array-flatten": "1.1.1", + "body-parser": "1.20.2", + "content-disposition": "0.5.4", + "content-type": "~1.0.4", + "cookie": "0.6.0", + "cookie-signature": "1.0.6", + "debug": "2.6.9", + "depd": "2.0.0", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "1.2.0", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "merge-descriptors": "1.0.1", + "methods": "~1.1.2", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "path-to-regexp": "0.1.7", + "proxy-addr": "~2.0.7", + "qs": "6.11.0", + "range-parser": "~1.2.1", + "safe-buffer": "5.2.1", + "send": "0.18.0", + "serve-static": "1.15.0", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "type-is": "~1.6.18", + "utils-merge": "1.0.1", + "vary": "~1.1.2" + }, + "engines": { + "node": ">= 0.10.0" + } + }, + "node_modules/finalhandler": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.2.0.tgz", + "integrity": "sha512-5uXcUVftlQMFnWC9qu/svkWv3GTd2PfUhK/3PLkYNAe7FbqJMt3515HaxE6eRL74GdsriiwujiawdaB1BpEISg==", + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "statuses": "2.0.1", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.4.tgz", + "integrity": "sha512-5uYhsJH8VJBTv7oslg4BznJYhDoRI6waYCxMmCdnTrcCrHA/fCFKoTFz2JKKE0HdDFUF7/oQuhzumXJK7paBRQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "has-proto": "^1.0.1", + "has-symbols": "^1.0.3", + "hasown": "^2.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/gopd": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.0.1.tgz", + "integrity": "sha512-d65bNlIadxvpb/A2abVdlqKqV563juRnZ1Wtk6s1sIR8uNsXR70xqIzVqxVf1eTqDunwT2MkczEeaezCKTZhwA==", + "license": "MIT", + "dependencies": { + "get-intrinsic": "^1.1.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/gun": { + "version": "0.2020.1240", + "resolved": "https://registry.npmjs.org/gun/-/gun-0.2020.1240.tgz", + "integrity": "sha512-uhnyadZTywn0HHgBjS2DePqpcdwLeVm6nFeSZZBPJRltm9O8MjFPyltaxk2PBKS+O8wSZac9qlbCIriJDgQQog==", + "license": "(Zlib OR MIT OR Apache-2.0)", + "dependencies": { + "ws": "^7.2.1" + }, + "engines": { + "node": ">=0.8.4" + }, + "optionalDependencies": { + "@peculiar/webcrypto": "^1.1.1" + } + }, + "node_modules/has-property-descriptors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", + "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==", + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-proto": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has-proto/-/has-proto-1.0.3.tgz", + "integrity": "sha512-SJ1amZAJUiZS+PhsVLf5tGydlaVB8EdFpaSO4gmiUKUOxk8qzn5AIy4ZeJUmh22znIdk/uMAUT2pl3FxzVUH+Q==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.3.tgz", + "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/http-errors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", + "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", + "license": "MIT", + "dependencies": { + "depd": "2.0.0", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/merge-descriptors": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz", + "integrity": "sha512-cCi6g3/Zr1iqQi6ySbseM1Xvooa98N0w31jzUYrXPX2xqObmFGHJ0tQ5u74H3mVh7wLouTseZyYIq39g8cNp1w==", + "license": "MIT" + }, + "node_modules/methods": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "license": "MIT", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "license": "MIT" + }, + "node_modules/negotiator": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", + "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/object-inspect": { + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.2.tgz", + "integrity": "sha512-IRZSRuzJiynemAXPYtPe5BoI/RESNYR7TYm50MC5Mqbd3Jmw5y790sErYw3V6SryFJD64b74qQQs9wn5Bg/k3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-to-regexp": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz", + "integrity": "sha512-5DFkuoqlv1uYQKxy8omFBeJPQcdoE07Kv2sferDCrAq1ohOU+MSDswDIbnx3YAM60qIOnYa53wBhXW0EbMonrQ==", + "license": "MIT" + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/pvtsutils": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/pvtsutils/-/pvtsutils-1.3.5.tgz", + "integrity": "sha512-ARvb14YB9Nm2Xi6nBq1ZX6dAM0FsJnuk+31aUp4TrcZEdKUlSqOqsxJHUPJDNE3qiIp+iUPEIeR6Je/tgV7zsA==", + "license": "MIT", + "dependencies": { + "tslib": "^2.6.1" + } + }, + "node_modules/pvutils": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/pvutils/-/pvutils-1.1.3.tgz", + "integrity": "sha512-pMpnA0qRdFp32b1sJl1wOJNxZLQ2cbQx+k6tjNtZ8CpvVhNqEPRgivZ2WOUev2YMajecdH7ctUPDvEe87nariQ==", + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/qs": { + "version": "6.11.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.11.0.tgz", + "integrity": "sha512-MvjoMCJwEarSbUYk5O+nmoSzSutSsTwF85zcHPQ9OrlFoZOYIjaqBAJIqIXjptyD5vThxGq52Xu/MaJzRkIk4Q==", + "license": "BSD-3-Clause", + "dependencies": { + "side-channel": "^1.0.4" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.2.tgz", + "integrity": "sha512-8zGqypfENjCIqGhgXToC8aB2r7YrBX+AQAfIPs/Mlk+BtPTztOvTS01NRW/3Eh60J+a48lt8qsCzirQ6loCVfA==", + "license": "MIT", + "dependencies": { + "bytes": "3.1.2", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/send": { + "version": "0.18.0", + "resolved": "https://registry.npmjs.org/send/-/send-0.18.0.tgz", + "integrity": "sha512-qqWzuOjSFOuqPjFe4NOsMLafToQQwBSOEpS+FwEt3A2V3vKubTquT3vmLTQpFgMXp8AlFWFuP1qKaJZOtPpVXg==", + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "mime": "1.6.0", + "ms": "2.1.3", + "on-finished": "2.4.1", + "range-parser": "~1.2.1", + "statuses": "2.0.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/send/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/serve-static": { + "version": "1.15.0", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.15.0.tgz", + "integrity": "sha512-XGuRDNjXUijsUL0vl6nSD7cwURuzEgglbOaFuZM9g3kwDXOWVTck0jLzjPzGD+TazWbboZYu52/9/XPdUgne9g==", + "license": "MIT", + "dependencies": { + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "0.18.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/set-function-length": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz", + "integrity": "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==", + "license": "MIT", + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "gopd": "^1.0.1", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/side-channel": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.6.tgz", + "integrity": "sha512-fDW/EZ6Q9RiO8eFG8Hj+7u/oW+XrPTIChwCOM2+th2A6OblDtYYIpve9m+KvI9Z4C9qSEXlaGR6bTEYHReuglA==", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.4", + "object-inspect": "^1.13.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/statuses": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/tslib": { + "version": "2.6.3", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.6.3.tgz", + "integrity": "sha512-xNvxJEOUiWPGhUuUdQgAJPKOOJfGnIyKySOc09XkKsgdUV/3E2zvwZYdejjmRgPCgcym1juLH3226yA7sEFJKQ==", + "license": "0BSD" + }, + "node_modules/type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "license": "MIT", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/utils-merge": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", + "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==", + "license": "MIT", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/webcrypto-core": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/webcrypto-core/-/webcrypto-core-1.8.0.tgz", + "integrity": "sha512-kR1UQNH8MD42CYuLzvibfakG5Ew5seG85dMMoAM/1LqvckxaF6pUiidLuraIu4V+YCIFabYecUZAW0TuxAoaqw==", + "license": "MIT", + "dependencies": { + "@peculiar/asn1-schema": "^2.3.8", + "@peculiar/json-schema": "^1.1.12", + "asn1js": "^3.0.1", + "pvtsutils": "^1.3.5", + "tslib": "^2.6.2" + } + }, + "node_modules/ws": { + "version": "7.5.10", + "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.10.tgz", + "integrity": "sha512-+dbF1tHwZpXcbOJdVOkzLDxZP1ailvSxM6ZweXTegylPny803bFhA+vqBYw4s31NSAk4S2Qz+AKXK9a4wkdjcQ==", + "license": "MIT", + "engines": { + "node": ">=8.3.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": "^5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + } + } +} diff --git a/gun-server/node_modules/@peculiar/asn1-schema/LICENSE b/gun-server/node_modules/@peculiar/asn1-schema/LICENSE new file mode 100644 index 0000000..6f9ec13 --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/gun-server/node_modules/@peculiar/asn1-schema/README.md b/gun-server/node_modules/@peculiar/asn1-schema/README.md new file mode 100644 index 0000000..e056dc2 --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/README.md @@ -0,0 +1,106 @@ +# `@peculiar/asn1-schema` + +[![License](https://img.shields.io/badge/license-MIT-green.svg?style=flat)](https://raw.githubusercontent.com/PeculiarVentures/asn1-schema/master/packages/schema/LICENSE.md) +[![npm version](https://badge.fury.io/js/%40peculiar%2Fasn1-schema.svg)](https://badge.fury.io/js/%40peculiar%2Fasn1-schema) + +[![NPM](https://nodei.co/npm/@peculiar/asn1-schema.png)](https://nodei.co/npm/@peculiar/asn1-schema/) + +This package uses ES2015 [decorators](https://medium.com/google-developers/exploring-es7-decorators-76ecb65fb841) to simplify working with ASN.1 creation and parsing. + + +## Introduction + +Abstract Syntax Notation One (ASN.1) is a standard interface description language for defining data structures that can be serialized and deserialized in a cross-platform way. Working with ASN.1 can be complicated as there are many ways to represent the same data and many solutions handcraft, incorrectly, the ASN.1 representation of the data. + +`asn1-schema` addresses this by using decorators to make both serialization and parsing of ASN.1 possible via a simple class that handles these problems for you. + +This is important because validating input data before its use is important to do because all input data is evil. + + +## Installation + +Installation is handled via `npm`: + +``` +$ npm install @peculiar/asn1-schema +``` + +## TypeScript examples +Node.js: + +ASN.1 schema +``` +Extension ::= SEQUENCE { + extnID OBJECT IDENTIFIER, + critical BOOLEAN DEFAULT FALSE, + extnValue OCTET STRING + -- contains the DER encoding of an ASN.1 value + -- corresponding to the extension type identified + -- by extnID +} + +id-ce-basicConstraints OBJECT IDENTIFIER ::= { id-ce 19 } + +BasicConstraints ::= SEQUENCE { + cA BOOLEAN DEFAULT FALSE, + pathLenConstraint INTEGER (0..MAX) OPTIONAL +} +``` + +ASN.1 schema declaration in TypeScript project +```ts +import { Asn1Prop, Asn1PropTypes, Asn1Serializer } from "@peculiar/asn1-schema"; + +class Extension { + + public static CRITICAL = false; + + @AsnProp({ type: Asn1PropTypes.ObjectIdentifier }) + public extnID: string = ""; + + @AsnProp({ + type: Asn1PropTypes.Boolean, + defaultValue: Extension.CRITICAL, + }) + public critical = Extension.CRITICAL; + + @AsnProp({ type: Asn1PropTypes.OctetString }) + public extnValue: ArrayBuffer = new ArrayBuffer(0); + +} + +class BasicConstraints { + @AsnProp({ type: Asn1PropTypes.Boolean, defaultValue: false }) + public ca = false; + + @AsnProp({ type: Asn1PropTypes.Integer, optional: true }) + public pathLenConstraint?: number; +} +``` + +Encoding ASN.1 data +```ts +const basicConstraints = new BasicConstraints(); +basicConstraints.ca = true; +basicConstraints.pathLenConstraint = 1; + +const extension = new Extension(); +extension.critical = true; +extension.extnID = "2.5.29.19"; +extension.extnValue = AsnSerializer.serialize(basicConstraints); + +console.log(Buffer.from(AsnSerializer.serialize(extension)).toString("hex")); // 30120603551d130101ff040830060101ff020101 +``` + +[ASN.1 encoded data](http://lapo.it/asn1js/#MBIGA1UdEwEB_wQIMAYBAf8CAQE) + +Decoding ASN.1 data +```ts +const extension = AsnParser.parse(Buffer.from("30120603551d130101ff040830060101ff020101", "hex"), Extension); +console.log("Extension ID:", extension.extnID); // Extension ID: 2.5.29.19 +console.log("Critical:", extension.critical); // Critical: true + +const basicConstraints = AsnParser.parse(extension.extnValue, BasicConstraints); +console.log("CA:", basicConstraints.ca); // CA: true +console.log("Path length:", basicConstraints.pathLenConstraint); // Path length: 1 +``` diff --git a/gun-server/node_modules/@peculiar/asn1-schema/build/cjs/convert.js b/gun-server/node_modules/@peculiar/asn1-schema/build/cjs/convert.js new file mode 100644 index 0000000..985a01d --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/build/cjs/convert.js @@ -0,0 +1,26 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AsnConvert = void 0; +const asn1js = require("asn1js"); +const pvtsutils_1 = require("pvtsutils"); +const parser_1 = require("./parser"); +const serializer_1 = require("./serializer"); +class AsnConvert { + static serialize(obj) { + return serializer_1.AsnSerializer.serialize(obj); + } + static parse(data, target) { + return parser_1.AsnParser.parse(data, target); + } + static toString(data) { + const buf = pvtsutils_1.BufferSourceConverter.isBufferSource(data) + ? pvtsutils_1.BufferSourceConverter.toArrayBuffer(data) + : AsnConvert.serialize(data); + const asn = asn1js.fromBER(buf); + if (asn.offset === -1) { + throw new Error(`Cannot decode ASN.1 data. ${asn.result.error}`); + } + return asn.result.toString(); + } +} +exports.AsnConvert = AsnConvert; diff --git a/gun-server/node_modules/@peculiar/asn1-schema/build/cjs/converters.js b/gun-server/node_modules/@peculiar/asn1-schema/build/cjs/converters.js new file mode 100644 index 0000000..38beba4 --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/build/cjs/converters.js @@ -0,0 +1,140 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.defaultConverter = exports.AsnNullConverter = exports.AsnGeneralizedTimeConverter = exports.AsnUTCTimeConverter = exports.AsnCharacterStringConverter = exports.AsnGeneralStringConverter = exports.AsnVisibleStringConverter = exports.AsnGraphicStringConverter = exports.AsnIA5StringConverter = exports.AsnVideotexStringConverter = exports.AsnTeletexStringConverter = exports.AsnPrintableStringConverter = exports.AsnNumericStringConverter = exports.AsnUniversalStringConverter = exports.AsnBmpStringConverter = exports.AsnUtf8StringConverter = exports.AsnConstructedOctetStringConverter = exports.AsnOctetStringConverter = exports.AsnBooleanConverter = exports.AsnObjectIdentifierConverter = exports.AsnBitStringConverter = exports.AsnIntegerBigIntConverter = exports.AsnIntegerArrayBufferConverter = exports.AsnEnumeratedConverter = exports.AsnIntegerConverter = exports.AsnAnyConverter = void 0; +const asn1js = require("asn1js"); +const enums_1 = require("./enums"); +const index_1 = require("./types/index"); +exports.AsnAnyConverter = { + fromASN: (value) => value instanceof asn1js.Null ? null : value.valueBeforeDecodeView, + toASN: (value) => { + if (value === null) { + return new asn1js.Null(); + } + const schema = asn1js.fromBER(value); + if (schema.result.error) { + throw new Error(schema.result.error); + } + return schema.result; + }, +}; +exports.AsnIntegerConverter = { + fromASN: (value) => value.valueBlock.valueHexView.byteLength >= 4 + ? value.valueBlock.toString() + : value.valueBlock.valueDec, + toASN: (value) => new asn1js.Integer({ value: +value }), +}; +exports.AsnEnumeratedConverter = { + fromASN: (value) => value.valueBlock.valueDec, + toASN: (value) => new asn1js.Enumerated({ value }), +}; +exports.AsnIntegerArrayBufferConverter = { + fromASN: (value) => value.valueBlock.valueHexView, + toASN: (value) => new asn1js.Integer({ valueHex: value }), +}; +exports.AsnIntegerBigIntConverter = { + fromASN: (value) => value.toBigInt(), + toASN: (value) => asn1js.Integer.fromBigInt(value), +}; +exports.AsnBitStringConverter = { + fromASN: (value) => value.valueBlock.valueHexView, + toASN: (value) => new asn1js.BitString({ valueHex: value }), +}; +exports.AsnObjectIdentifierConverter = { + fromASN: (value) => value.valueBlock.toString(), + toASN: (value) => new asn1js.ObjectIdentifier({ value }), +}; +exports.AsnBooleanConverter = { + fromASN: (value) => value.valueBlock.value, + toASN: (value) => new asn1js.Boolean({ value }), +}; +exports.AsnOctetStringConverter = { + fromASN: (value) => value.valueBlock.valueHexView, + toASN: (value) => new asn1js.OctetString({ valueHex: value }), +}; +exports.AsnConstructedOctetStringConverter = { + fromASN: (value) => new index_1.OctetString(value.getValue()), + toASN: (value) => value.toASN(), +}; +function createStringConverter(Asn1Type) { + return { + fromASN: (value) => value.valueBlock.value, + toASN: (value) => new Asn1Type({ value }), + }; +} +exports.AsnUtf8StringConverter = createStringConverter(asn1js.Utf8String); +exports.AsnBmpStringConverter = createStringConverter(asn1js.BmpString); +exports.AsnUniversalStringConverter = createStringConverter(asn1js.UniversalString); +exports.AsnNumericStringConverter = createStringConverter(asn1js.NumericString); +exports.AsnPrintableStringConverter = createStringConverter(asn1js.PrintableString); +exports.AsnTeletexStringConverter = createStringConverter(asn1js.TeletexString); +exports.AsnVideotexStringConverter = createStringConverter(asn1js.VideotexString); +exports.AsnIA5StringConverter = createStringConverter(asn1js.IA5String); +exports.AsnGraphicStringConverter = createStringConverter(asn1js.GraphicString); +exports.AsnVisibleStringConverter = createStringConverter(asn1js.VisibleString); +exports.AsnGeneralStringConverter = createStringConverter(asn1js.GeneralString); +exports.AsnCharacterStringConverter = createStringConverter(asn1js.CharacterString); +exports.AsnUTCTimeConverter = { + fromASN: (value) => value.toDate(), + toASN: (value) => new asn1js.UTCTime({ valueDate: value }), +}; +exports.AsnGeneralizedTimeConverter = { + fromASN: (value) => value.toDate(), + toASN: (value) => new asn1js.GeneralizedTime({ valueDate: value }), +}; +exports.AsnNullConverter = { + fromASN: () => null, + toASN: () => { + return new asn1js.Null(); + }, +}; +function defaultConverter(type) { + switch (type) { + case enums_1.AsnPropTypes.Any: + return exports.AsnAnyConverter; + case enums_1.AsnPropTypes.BitString: + return exports.AsnBitStringConverter; + case enums_1.AsnPropTypes.BmpString: + return exports.AsnBmpStringConverter; + case enums_1.AsnPropTypes.Boolean: + return exports.AsnBooleanConverter; + case enums_1.AsnPropTypes.CharacterString: + return exports.AsnCharacterStringConverter; + case enums_1.AsnPropTypes.Enumerated: + return exports.AsnEnumeratedConverter; + case enums_1.AsnPropTypes.GeneralString: + return exports.AsnGeneralStringConverter; + case enums_1.AsnPropTypes.GeneralizedTime: + return exports.AsnGeneralizedTimeConverter; + case enums_1.AsnPropTypes.GraphicString: + return exports.AsnGraphicStringConverter; + case enums_1.AsnPropTypes.IA5String: + return exports.AsnIA5StringConverter; + case enums_1.AsnPropTypes.Integer: + return exports.AsnIntegerConverter; + case enums_1.AsnPropTypes.Null: + return exports.AsnNullConverter; + case enums_1.AsnPropTypes.NumericString: + return exports.AsnNumericStringConverter; + case enums_1.AsnPropTypes.ObjectIdentifier: + return exports.AsnObjectIdentifierConverter; + case enums_1.AsnPropTypes.OctetString: + return exports.AsnOctetStringConverter; + case enums_1.AsnPropTypes.PrintableString: + return exports.AsnPrintableStringConverter; + case enums_1.AsnPropTypes.TeletexString: + return exports.AsnTeletexStringConverter; + case enums_1.AsnPropTypes.UTCTime: + return exports.AsnUTCTimeConverter; + case enums_1.AsnPropTypes.UniversalString: + return exports.AsnUniversalStringConverter; + case enums_1.AsnPropTypes.Utf8String: + return exports.AsnUtf8StringConverter; + case enums_1.AsnPropTypes.VideotexString: + return exports.AsnVideotexStringConverter; + case enums_1.AsnPropTypes.VisibleString: + return exports.AsnVisibleStringConverter; + default: + return null; + } +} +exports.defaultConverter = defaultConverter; diff --git a/gun-server/node_modules/@peculiar/asn1-schema/build/cjs/decorators.js b/gun-server/node_modules/@peculiar/asn1-schema/build/cjs/decorators.js new file mode 100644 index 0000000..0655e73 --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/build/cjs/decorators.js @@ -0,0 +1,44 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AsnProp = exports.AsnSequenceType = exports.AsnSetType = exports.AsnChoiceType = exports.AsnType = void 0; +const converters = require("./converters"); +const enums_1 = require("./enums"); +const storage_1 = require("./storage"); +const AsnType = (options) => (target) => { + let schema; + if (!storage_1.schemaStorage.has(target)) { + schema = storage_1.schemaStorage.createDefault(target); + storage_1.schemaStorage.set(target, schema); + } + else { + schema = storage_1.schemaStorage.get(target); + } + Object.assign(schema, options); +}; +exports.AsnType = AsnType; +const AsnChoiceType = () => (0, exports.AsnType)({ type: enums_1.AsnTypeTypes.Choice }); +exports.AsnChoiceType = AsnChoiceType; +const AsnSetType = (options) => (0, exports.AsnType)({ type: enums_1.AsnTypeTypes.Set, ...options }); +exports.AsnSetType = AsnSetType; +const AsnSequenceType = (options) => (0, exports.AsnType)({ type: enums_1.AsnTypeTypes.Sequence, ...options }); +exports.AsnSequenceType = AsnSequenceType; +const AsnProp = (options) => (target, propertyKey) => { + let schema; + if (!storage_1.schemaStorage.has(target.constructor)) { + schema = storage_1.schemaStorage.createDefault(target.constructor); + storage_1.schemaStorage.set(target.constructor, schema); + } + else { + schema = storage_1.schemaStorage.get(target.constructor); + } + const copyOptions = Object.assign({}, options); + if (typeof copyOptions.type === "number" && !copyOptions.converter) { + const defaultConverter = converters.defaultConverter(options.type); + if (!defaultConverter) { + throw new Error(`Cannot get default converter for property '${propertyKey}' of ${target.constructor.name}`); + } + copyOptions.converter = defaultConverter; + } + schema.items[propertyKey] = copyOptions; +}; +exports.AsnProp = AsnProp; diff --git a/gun-server/node_modules/@peculiar/asn1-schema/build/cjs/enums.js b/gun-server/node_modules/@peculiar/asn1-schema/build/cjs/enums.js new file mode 100644 index 0000000..f9ba8eb --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/build/cjs/enums.js @@ -0,0 +1,39 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AsnPropTypes = exports.AsnTypeTypes = void 0; +var AsnTypeTypes; +(function (AsnTypeTypes) { + AsnTypeTypes[AsnTypeTypes["Sequence"] = 0] = "Sequence"; + AsnTypeTypes[AsnTypeTypes["Set"] = 1] = "Set"; + AsnTypeTypes[AsnTypeTypes["Choice"] = 2] = "Choice"; +})(AsnTypeTypes || (exports.AsnTypeTypes = AsnTypeTypes = {})); +var AsnPropTypes; +(function (AsnPropTypes) { + AsnPropTypes[AsnPropTypes["Any"] = 1] = "Any"; + AsnPropTypes[AsnPropTypes["Boolean"] = 2] = "Boolean"; + AsnPropTypes[AsnPropTypes["OctetString"] = 3] = "OctetString"; + AsnPropTypes[AsnPropTypes["BitString"] = 4] = "BitString"; + AsnPropTypes[AsnPropTypes["Integer"] = 5] = "Integer"; + AsnPropTypes[AsnPropTypes["Enumerated"] = 6] = "Enumerated"; + AsnPropTypes[AsnPropTypes["ObjectIdentifier"] = 7] = "ObjectIdentifier"; + AsnPropTypes[AsnPropTypes["Utf8String"] = 8] = "Utf8String"; + AsnPropTypes[AsnPropTypes["BmpString"] = 9] = "BmpString"; + AsnPropTypes[AsnPropTypes["UniversalString"] = 10] = "UniversalString"; + AsnPropTypes[AsnPropTypes["NumericString"] = 11] = "NumericString"; + AsnPropTypes[AsnPropTypes["PrintableString"] = 12] = "PrintableString"; + AsnPropTypes[AsnPropTypes["TeletexString"] = 13] = "TeletexString"; + AsnPropTypes[AsnPropTypes["VideotexString"] = 14] = "VideotexString"; + AsnPropTypes[AsnPropTypes["IA5String"] = 15] = "IA5String"; + AsnPropTypes[AsnPropTypes["GraphicString"] = 16] = "GraphicString"; + AsnPropTypes[AsnPropTypes["VisibleString"] = 17] = "VisibleString"; + AsnPropTypes[AsnPropTypes["GeneralString"] = 18] = "GeneralString"; + AsnPropTypes[AsnPropTypes["CharacterString"] = 19] = "CharacterString"; + AsnPropTypes[AsnPropTypes["UTCTime"] = 20] = "UTCTime"; + AsnPropTypes[AsnPropTypes["GeneralizedTime"] = 21] = "GeneralizedTime"; + AsnPropTypes[AsnPropTypes["DATE"] = 22] = "DATE"; + AsnPropTypes[AsnPropTypes["TimeOfDay"] = 23] = "TimeOfDay"; + AsnPropTypes[AsnPropTypes["DateTime"] = 24] = "DateTime"; + AsnPropTypes[AsnPropTypes["Duration"] = 25] = "Duration"; + AsnPropTypes[AsnPropTypes["TIME"] = 26] = "TIME"; + AsnPropTypes[AsnPropTypes["Null"] = 27] = "Null"; +})(AsnPropTypes || (exports.AsnPropTypes = AsnPropTypes = {})); diff --git a/gun-server/node_modules/@peculiar/asn1-schema/build/cjs/errors/index.js b/gun-server/node_modules/@peculiar/asn1-schema/build/cjs/errors/index.js new file mode 100644 index 0000000..63a58bb --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/build/cjs/errors/index.js @@ -0,0 +1,4 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const tslib_1 = require("tslib"); +tslib_1.__exportStar(require("./schema_validation"), exports); diff --git a/gun-server/node_modules/@peculiar/asn1-schema/build/cjs/errors/schema_validation.js b/gun-server/node_modules/@peculiar/asn1-schema/build/cjs/errors/schema_validation.js new file mode 100644 index 0000000..9c97cf1 --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/build/cjs/errors/schema_validation.js @@ -0,0 +1,10 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AsnSchemaValidationError = void 0; +class AsnSchemaValidationError extends Error { + constructor() { + super(...arguments); + this.schemas = []; + } +} +exports.AsnSchemaValidationError = AsnSchemaValidationError; diff --git a/gun-server/node_modules/@peculiar/asn1-schema/build/cjs/helper.js b/gun-server/node_modules/@peculiar/asn1-schema/build/cjs/helper.js new file mode 100644 index 0000000..f9c3b3c --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/build/cjs/helper.js @@ -0,0 +1,46 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isArrayEqual = exports.isTypeOfArray = exports.isConvertible = void 0; +function isConvertible(target) { + if (typeof target === "function" && target.prototype) { + if (target.prototype.toASN && target.prototype.fromASN) { + return true; + } + else { + return isConvertible(target.prototype); + } + } + else { + return !!(target && typeof target === "object" && "toASN" in target && "fromASN" in target); + } +} +exports.isConvertible = isConvertible; +function isTypeOfArray(target) { + var _a; + if (target) { + const proto = Object.getPrototypeOf(target); + if (((_a = proto === null || proto === void 0 ? void 0 : proto.prototype) === null || _a === void 0 ? void 0 : _a.constructor) === Array) { + return true; + } + return isTypeOfArray(proto); + } + return false; +} +exports.isTypeOfArray = isTypeOfArray; +function isArrayEqual(bytes1, bytes2) { + if (!(bytes1 && bytes2)) { + return false; + } + if (bytes1.byteLength !== bytes2.byteLength) { + return false; + } + const b1 = new Uint8Array(bytes1); + const b2 = new Uint8Array(bytes2); + for (let i = 0; i < bytes1.byteLength; i++) { + if (b1[i] !== b2[i]) { + return false; + } + } + return true; +} +exports.isArrayEqual = isArrayEqual; diff --git a/gun-server/node_modules/@peculiar/asn1-schema/build/cjs/index.js b/gun-server/node_modules/@peculiar/asn1-schema/build/cjs/index.js new file mode 100644 index 0000000..9a04496 --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/build/cjs/index.js @@ -0,0 +1,22 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AsnSerializer = exports.AsnParser = exports.AsnPropTypes = exports.AsnTypeTypes = exports.AsnSetType = exports.AsnSequenceType = exports.AsnChoiceType = exports.AsnType = exports.AsnProp = void 0; +const tslib_1 = require("tslib"); +tslib_1.__exportStar(require("./converters"), exports); +tslib_1.__exportStar(require("./types/index"), exports); +var decorators_1 = require("./decorators"); +Object.defineProperty(exports, "AsnProp", { enumerable: true, get: function () { return decorators_1.AsnProp; } }); +Object.defineProperty(exports, "AsnType", { enumerable: true, get: function () { return decorators_1.AsnType; } }); +Object.defineProperty(exports, "AsnChoiceType", { enumerable: true, get: function () { return decorators_1.AsnChoiceType; } }); +Object.defineProperty(exports, "AsnSequenceType", { enumerable: true, get: function () { return decorators_1.AsnSequenceType; } }); +Object.defineProperty(exports, "AsnSetType", { enumerable: true, get: function () { return decorators_1.AsnSetType; } }); +var enums_1 = require("./enums"); +Object.defineProperty(exports, "AsnTypeTypes", { enumerable: true, get: function () { return enums_1.AsnTypeTypes; } }); +Object.defineProperty(exports, "AsnPropTypes", { enumerable: true, get: function () { return enums_1.AsnPropTypes; } }); +var parser_1 = require("./parser"); +Object.defineProperty(exports, "AsnParser", { enumerable: true, get: function () { return parser_1.AsnParser; } }); +var serializer_1 = require("./serializer"); +Object.defineProperty(exports, "AsnSerializer", { enumerable: true, get: function () { return serializer_1.AsnSerializer; } }); +tslib_1.__exportStar(require("./errors"), exports); +tslib_1.__exportStar(require("./objects"), exports); +tslib_1.__exportStar(require("./convert"), exports); diff --git a/gun-server/node_modules/@peculiar/asn1-schema/build/cjs/objects.js b/gun-server/node_modules/@peculiar/asn1-schema/build/cjs/objects.js new file mode 100644 index 0000000..a787c28 --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/build/cjs/objects.js @@ -0,0 +1,17 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AsnArray = void 0; +class AsnArray extends Array { + constructor(items = []) { + if (typeof items === "number") { + super(items); + } + else { + super(); + for (const item of items) { + this.push(item); + } + } + } +} +exports.AsnArray = AsnArray; diff --git a/gun-server/node_modules/@peculiar/asn1-schema/build/cjs/parser.js b/gun-server/node_modules/@peculiar/asn1-schema/build/cjs/parser.js new file mode 100644 index 0000000..787cfd3 --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/build/cjs/parser.js @@ -0,0 +1,140 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AsnParser = void 0; +const asn1js = require("asn1js"); +const enums_1 = require("./enums"); +const converters = require("./converters"); +const errors_1 = require("./errors"); +const helper_1 = require("./helper"); +const storage_1 = require("./storage"); +class AsnParser { + static parse(data, target) { + const asn1Parsed = asn1js.fromBER(data); + if (asn1Parsed.result.error) { + throw new Error(asn1Parsed.result.error); + } + const res = this.fromASN(asn1Parsed.result, target); + return res; + } + static fromASN(asn1Schema, target) { + var _a; + try { + if ((0, helper_1.isConvertible)(target)) { + const value = new target(); + return value.fromASN(asn1Schema); + } + const schema = storage_1.schemaStorage.get(target); + storage_1.schemaStorage.cache(target); + let targetSchema = schema.schema; + if (asn1Schema.constructor === asn1js.Constructed && schema.type !== enums_1.AsnTypeTypes.Choice) { + targetSchema = new asn1js.Constructed({ + idBlock: { + tagClass: 3, + tagNumber: asn1Schema.idBlock.tagNumber, + }, + value: schema.schema.valueBlock.value, + }); + for (const key in schema.items) { + delete asn1Schema[key]; + } + } + const asn1ComparedSchema = asn1js.compareSchema({}, asn1Schema, targetSchema); + if (!asn1ComparedSchema.verified) { + throw new errors_1.AsnSchemaValidationError(`Data does not match to ${target.name} ASN1 schema. ${asn1ComparedSchema.result.error}`); + } + const res = new target(); + if ((0, helper_1.isTypeOfArray)(target)) { + if (!("value" in asn1Schema.valueBlock && Array.isArray(asn1Schema.valueBlock.value))) { + throw new Error(`Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.`); + } + const itemType = schema.itemType; + if (typeof itemType === "number") { + const converter = converters.defaultConverter(itemType); + if (!converter) { + throw new Error(`Cannot get default converter for array item of ${target.name} ASN1 schema`); + } + return target.from(asn1Schema.valueBlock.value, (element) => converter.fromASN(element)); + } + else { + return target.from(asn1Schema.valueBlock.value, (element) => this.fromASN(element, itemType)); + } + } + for (const key in schema.items) { + const asn1SchemaValue = asn1ComparedSchema.result[key]; + if (!asn1SchemaValue) { + continue; + } + const schemaItem = schema.items[key]; + const schemaItemType = schemaItem.type; + if (typeof schemaItemType === "number" || (0, helper_1.isConvertible)(schemaItemType)) { + const converter = (_a = schemaItem.converter) !== null && _a !== void 0 ? _a : ((0, helper_1.isConvertible)(schemaItemType) + ? new schemaItemType() + : null); + if (!converter) { + throw new Error("Converter is empty"); + } + if (schemaItem.repeated) { + if (schemaItem.implicit) { + const Container = schemaItem.repeated === "sequence" + ? asn1js.Sequence + : asn1js.Set; + const newItem = new Container(); + newItem.valueBlock = asn1SchemaValue.valueBlock; + const newItemAsn = asn1js.fromBER(newItem.toBER(false)); + if (newItemAsn.offset === -1) { + throw new Error(`Cannot parse the child item. ${newItemAsn.result.error}`); + } + if (!("value" in newItemAsn.result.valueBlock && Array.isArray(newItemAsn.result.valueBlock.value))) { + throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed."); + } + const value = newItemAsn.result.valueBlock.value; + res[key] = Array.from(value, (element) => converter.fromASN(element)); + } + else { + res[key] = Array.from(asn1SchemaValue, (element) => converter.fromASN(element)); + } + } + else { + let value = asn1SchemaValue; + if (schemaItem.implicit) { + let newItem; + if ((0, helper_1.isConvertible)(schemaItemType)) { + newItem = new schemaItemType().toSchema(""); + } + else { + const Asn1TypeName = enums_1.AsnPropTypes[schemaItemType]; + const Asn1Type = asn1js[Asn1TypeName]; + if (!Asn1Type) { + throw new Error(`Cannot get '${Asn1TypeName}' class from asn1js module`); + } + newItem = new Asn1Type(); + } + newItem.valueBlock = value.valueBlock; + value = asn1js.fromBER(newItem.toBER(false)).result; + } + res[key] = converter.fromASN(value); + } + } + else { + if (schemaItem.repeated) { + if (!Array.isArray(asn1SchemaValue)) { + throw new Error("Cannot get list of items from the ASN.1 parsed value. ASN.1 value should be iterable."); + } + res[key] = Array.from(asn1SchemaValue, (element) => this.fromASN(element, schemaItemType)); + } + else { + res[key] = this.fromASN(asn1SchemaValue, schemaItemType); + } + } + } + return res; + } + catch (error) { + if (error instanceof errors_1.AsnSchemaValidationError) { + error.schemas.push(target.name); + } + throw error; + } + } +} +exports.AsnParser = AsnParser; diff --git a/gun-server/node_modules/@peculiar/asn1-schema/build/cjs/schema.js b/gun-server/node_modules/@peculiar/asn1-schema/build/cjs/schema.js new file mode 100644 index 0000000..e44e2e5 --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/build/cjs/schema.js @@ -0,0 +1,163 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AsnSchemaStorage = void 0; +const asn1js = require("asn1js"); +const enums_1 = require("./enums"); +const helper_1 = require("./helper"); +class AsnSchemaStorage { + constructor() { + this.items = new WeakMap(); + } + has(target) { + return this.items.has(target); + } + get(target, checkSchema = false) { + const schema = this.items.get(target); + if (!schema) { + throw new Error(`Cannot get schema for '${target.prototype.constructor.name}' target`); + } + if (checkSchema && !schema.schema) { + throw new Error(`Schema '${target.prototype.constructor.name}' doesn't contain ASN.1 schema. Call 'AsnSchemaStorage.cache'.`); + } + return schema; + } + cache(target) { + const schema = this.get(target); + if (!schema.schema) { + schema.schema = this.create(target, true); + } + } + createDefault(target) { + const schema = { + type: enums_1.AsnTypeTypes.Sequence, + items: {}, + }; + const parentSchema = this.findParentSchema(target); + if (parentSchema) { + Object.assign(schema, parentSchema); + schema.items = Object.assign({}, schema.items, parentSchema.items); + } + return schema; + } + create(target, useNames) { + const schema = this.items.get(target) || this.createDefault(target); + const asn1Value = []; + for (const key in schema.items) { + const item = schema.items[key]; + const name = useNames ? key : ""; + let asn1Item; + if (typeof (item.type) === "number") { + const Asn1TypeName = enums_1.AsnPropTypes[item.type]; + const Asn1Type = asn1js[Asn1TypeName]; + if (!Asn1Type) { + throw new Error(`Cannot get ASN1 class by name '${Asn1TypeName}'`); + } + asn1Item = new Asn1Type({ name }); + } + else if ((0, helper_1.isConvertible)(item.type)) { + const instance = new item.type(); + asn1Item = instance.toSchema(name); + } + else if (item.optional) { + const itemSchema = this.get(item.type); + if (itemSchema.type === enums_1.AsnTypeTypes.Choice) { + asn1Item = new asn1js.Any({ name }); + } + else { + asn1Item = this.create(item.type, false); + asn1Item.name = name; + } + } + else { + asn1Item = new asn1js.Any({ name }); + } + const optional = !!item.optional || item.defaultValue !== undefined; + if (item.repeated) { + asn1Item.name = ""; + const Container = item.repeated === "set" + ? asn1js.Set + : asn1js.Sequence; + asn1Item = new Container({ + name: "", + value: [ + new asn1js.Repeated({ + name, + value: asn1Item, + }), + ], + }); + } + if (item.context !== null && item.context !== undefined) { + if (item.implicit) { + if (typeof item.type === "number" || (0, helper_1.isConvertible)(item.type)) { + const Container = item.repeated + ? asn1js.Constructed + : asn1js.Primitive; + asn1Value.push(new Container({ + name, + optional, + idBlock: { + tagClass: 3, + tagNumber: item.context, + }, + })); + } + else { + this.cache(item.type); + const isRepeated = !!item.repeated; + let value = !isRepeated + ? this.get(item.type, true).schema + : asn1Item; + value = "valueBlock" in value ? value.valueBlock.value : value.value; + asn1Value.push(new asn1js.Constructed({ + name: !isRepeated ? name : "", + optional, + idBlock: { + tagClass: 3, + tagNumber: item.context, + }, + value: value, + })); + } + } + else { + asn1Value.push(new asn1js.Constructed({ + optional, + idBlock: { + tagClass: 3, + tagNumber: item.context, + }, + value: [asn1Item], + })); + } + } + else { + asn1Item.optional = optional; + asn1Value.push(asn1Item); + } + } + switch (schema.type) { + case enums_1.AsnTypeTypes.Sequence: + return new asn1js.Sequence({ value: asn1Value, name: "" }); + case enums_1.AsnTypeTypes.Set: + return new asn1js.Set({ value: asn1Value, name: "" }); + case enums_1.AsnTypeTypes.Choice: + return new asn1js.Choice({ value: asn1Value, name: "" }); + default: + throw new Error(`Unsupported ASN1 type in use`); + } + } + set(target, schema) { + this.items.set(target, schema); + return this; + } + findParentSchema(target) { + const parent = Object.getPrototypeOf(target); + if (parent) { + const schema = this.items.get(parent); + return schema || this.findParentSchema(parent); + } + return null; + } +} +exports.AsnSchemaStorage = AsnSchemaStorage; diff --git a/gun-server/node_modules/@peculiar/asn1-schema/build/cjs/serializer.js b/gun-server/node_modules/@peculiar/asn1-schema/build/cjs/serializer.js new file mode 100644 index 0000000..93a2839 --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/build/cjs/serializer.js @@ -0,0 +1,158 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AsnSerializer = void 0; +const asn1js = require("asn1js"); +const converters = require("./converters"); +const enums_1 = require("./enums"); +const helper_1 = require("./helper"); +const storage_1 = require("./storage"); +class AsnSerializer { + static serialize(obj) { + if (obj instanceof asn1js.BaseBlock) { + return obj.toBER(false); + } + return this.toASN(obj).toBER(false); + } + static toASN(obj) { + if (obj && typeof obj === "object" && (0, helper_1.isConvertible)(obj)) { + return obj.toASN(); + } + if (!(obj && typeof obj === "object")) { + throw new TypeError("Parameter 1 should be type of Object."); + } + const target = obj.constructor; + const schema = storage_1.schemaStorage.get(target); + storage_1.schemaStorage.cache(target); + let asn1Value = []; + if (schema.itemType) { + if (!Array.isArray(obj)) { + throw new TypeError("Parameter 1 should be type of Array."); + } + if (typeof schema.itemType === "number") { + const converter = converters.defaultConverter(schema.itemType); + if (!converter) { + throw new Error(`Cannot get default converter for array item of ${target.name} ASN1 schema`); + } + asn1Value = obj.map((o) => converter.toASN(o)); + } + else { + asn1Value = obj.map((o) => this.toAsnItem({ type: schema.itemType }, "[]", target, o)); + } + } + else { + for (const key in schema.items) { + const schemaItem = schema.items[key]; + const objProp = obj[key]; + if (objProp === undefined + || schemaItem.defaultValue === objProp + || (typeof schemaItem.defaultValue === "object" && typeof objProp === "object" + && (0, helper_1.isArrayEqual)(this.serialize(schemaItem.defaultValue), this.serialize(objProp)))) { + continue; + } + const asn1Item = AsnSerializer.toAsnItem(schemaItem, key, target, objProp); + if (typeof schemaItem.context === "number") { + if (schemaItem.implicit) { + if (!schemaItem.repeated + && (typeof schemaItem.type === "number" || (0, helper_1.isConvertible)(schemaItem.type))) { + const value = {}; + value.valueHex = asn1Item instanceof asn1js.Null ? asn1Item.valueBeforeDecodeView : asn1Item.valueBlock.toBER(); + asn1Value.push(new asn1js.Primitive({ + optional: schemaItem.optional, + idBlock: { + tagClass: 3, + tagNumber: schemaItem.context, + }, + ...value, + })); + } + else { + asn1Value.push(new asn1js.Constructed({ + optional: schemaItem.optional, + idBlock: { + tagClass: 3, + tagNumber: schemaItem.context, + }, + value: asn1Item.valueBlock.value, + })); + } + } + else { + asn1Value.push(new asn1js.Constructed({ + optional: schemaItem.optional, + idBlock: { + tagClass: 3, + tagNumber: schemaItem.context, + }, + value: [asn1Item], + })); + } + } + else if (schemaItem.repeated) { + asn1Value = asn1Value.concat(asn1Item); + } + else { + asn1Value.push(asn1Item); + } + } + } + let asnSchema; + switch (schema.type) { + case enums_1.AsnTypeTypes.Sequence: + asnSchema = new asn1js.Sequence({ value: asn1Value }); + break; + case enums_1.AsnTypeTypes.Set: + asnSchema = new asn1js.Set({ value: asn1Value }); + break; + case enums_1.AsnTypeTypes.Choice: + if (!asn1Value[0]) { + throw new Error(`Schema '${target.name}' has wrong data. Choice cannot be empty.`); + } + asnSchema = asn1Value[0]; + break; + } + return asnSchema; + } + static toAsnItem(schemaItem, key, target, objProp) { + let asn1Item; + if (typeof (schemaItem.type) === "number") { + const converter = schemaItem.converter; + if (!converter) { + throw new Error(`Property '${key}' doesn't have converter for type ${enums_1.AsnPropTypes[schemaItem.type]} in schema '${target.name}'`); + } + if (schemaItem.repeated) { + if (!Array.isArray(objProp)) { + throw new TypeError("Parameter 'objProp' should be type of Array."); + } + const items = Array.from(objProp, (element) => converter.toASN(element)); + const Container = schemaItem.repeated === "sequence" + ? asn1js.Sequence + : asn1js.Set; + asn1Item = new Container({ + value: items, + }); + } + else { + asn1Item = converter.toASN(objProp); + } + } + else { + if (schemaItem.repeated) { + if (!Array.isArray(objProp)) { + throw new TypeError("Parameter 'objProp' should be type of Array."); + } + const items = Array.from(objProp, (element) => this.toASN(element)); + const Container = schemaItem.repeated === "sequence" + ? asn1js.Sequence + : asn1js.Set; + asn1Item = new Container({ + value: items, + }); + } + else { + asn1Item = this.toASN(objProp); + } + } + return asn1Item; + } +} +exports.AsnSerializer = AsnSerializer; diff --git a/gun-server/node_modules/@peculiar/asn1-schema/build/cjs/storage.js b/gun-server/node_modules/@peculiar/asn1-schema/build/cjs/storage.js new file mode 100644 index 0000000..368009e --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/build/cjs/storage.js @@ -0,0 +1,5 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.schemaStorage = void 0; +const schema_1 = require("./schema"); +exports.schemaStorage = new schema_1.AsnSchemaStorage(); diff --git a/gun-server/node_modules/@peculiar/asn1-schema/build/cjs/types.js b/gun-server/node_modules/@peculiar/asn1-schema/build/cjs/types.js new file mode 100644 index 0000000..c8ad2e5 --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/build/cjs/types.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/gun-server/node_modules/@peculiar/asn1-schema/build/cjs/types/bit_string.js b/gun-server/node_modules/@peculiar/asn1-schema/build/cjs/types/bit_string.js new file mode 100644 index 0000000..4c2d84a --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/build/cjs/types/bit_string.js @@ -0,0 +1,63 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BitString = void 0; +const asn1js = require("asn1js"); +const pvtsutils_1 = require("pvtsutils"); +class BitString { + constructor(params, unusedBits = 0) { + this.unusedBits = 0; + this.value = new ArrayBuffer(0); + if (params) { + if (typeof params === "number") { + this.fromNumber(params); + } + else if (pvtsutils_1.BufferSourceConverter.isBufferSource(params)) { + this.unusedBits = unusedBits; + this.value = pvtsutils_1.BufferSourceConverter.toArrayBuffer(params); + } + else { + throw TypeError("Unsupported type of 'params' argument for BitString"); + } + } + } + fromASN(asn) { + if (!(asn instanceof asn1js.BitString)) { + throw new TypeError("Argument 'asn' is not instance of ASN.1 BitString"); + } + this.unusedBits = asn.valueBlock.unusedBits; + this.value = asn.valueBlock.valueHex; + return this; + } + toASN() { + return new asn1js.BitString({ unusedBits: this.unusedBits, valueHex: this.value }); + } + toSchema(name) { + return new asn1js.BitString({ name }); + } + toNumber() { + let res = ""; + const uintArray = new Uint8Array(this.value); + for (const octet of uintArray) { + res += octet.toString(2).padStart(8, "0"); + } + res = res.split("").reverse().join(""); + if (this.unusedBits) { + res = res.slice(this.unusedBits).padStart(this.unusedBits, "0"); + } + return parseInt(res, 2); + } + fromNumber(value) { + let bits = value.toString(2); + const octetSize = (bits.length + 7) >> 3; + this.unusedBits = (octetSize << 3) - bits.length; + const octets = new Uint8Array(octetSize); + bits = bits.padStart(octetSize << 3, "0").split("").reverse().join(""); + let index = 0; + while (index < octetSize) { + octets[index] = parseInt(bits.slice(index << 3, (index << 3) + 8), 2); + index++; + } + this.value = octets.buffer; + } +} +exports.BitString = BitString; diff --git a/gun-server/node_modules/@peculiar/asn1-schema/build/cjs/types/index.js b/gun-server/node_modules/@peculiar/asn1-schema/build/cjs/types/index.js new file mode 100644 index 0000000..cd5fccf --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/build/cjs/types/index.js @@ -0,0 +1,5 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const tslib_1 = require("tslib"); +tslib_1.__exportStar(require("./bit_string"), exports); +tslib_1.__exportStar(require("./octet_string"), exports); diff --git a/gun-server/node_modules/@peculiar/asn1-schema/build/cjs/types/octet_string.js b/gun-server/node_modules/@peculiar/asn1-schema/build/cjs/types/octet_string.js new file mode 100644 index 0000000..b3e82e0 --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/build/cjs/types/octet_string.js @@ -0,0 +1,43 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OctetString = void 0; +const asn1js = require("asn1js"); +const pvtsutils_1 = require("pvtsutils"); +class OctetString { + get byteLength() { + return this.buffer.byteLength; + } + get byteOffset() { + return 0; + } + constructor(param) { + if (typeof param === "number") { + this.buffer = new ArrayBuffer(param); + } + else { + if (pvtsutils_1.BufferSourceConverter.isBufferSource(param)) { + this.buffer = pvtsutils_1.BufferSourceConverter.toArrayBuffer(param); + } + else if (Array.isArray(param)) { + this.buffer = new Uint8Array(param); + } + else { + this.buffer = new ArrayBuffer(0); + } + } + } + fromASN(asn) { + if (!(asn instanceof asn1js.OctetString)) { + throw new TypeError("Argument 'asn' is not instance of ASN.1 OctetString"); + } + this.buffer = asn.valueBlock.valueHex; + return this; + } + toASN() { + return new asn1js.OctetString({ valueHex: this.buffer }); + } + toSchema(name) { + return new asn1js.OctetString({ name }); + } +} +exports.OctetString = OctetString; diff --git a/gun-server/node_modules/@peculiar/asn1-schema/build/es2015/convert.js b/gun-server/node_modules/@peculiar/asn1-schema/build/es2015/convert.js new file mode 100644 index 0000000..27f77a9 --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/build/es2015/convert.js @@ -0,0 +1,22 @@ +import * as asn1js from "asn1js"; +import { BufferSourceConverter } from "pvtsutils"; +import { AsnParser } from "./parser"; +import { AsnSerializer } from "./serializer"; +export class AsnConvert { + static serialize(obj) { + return AsnSerializer.serialize(obj); + } + static parse(data, target) { + return AsnParser.parse(data, target); + } + static toString(data) { + const buf = BufferSourceConverter.isBufferSource(data) + ? BufferSourceConverter.toArrayBuffer(data) + : AsnConvert.serialize(data); + const asn = asn1js.fromBER(buf); + if (asn.offset === -1) { + throw new Error(`Cannot decode ASN.1 data. ${asn.result.error}`); + } + return asn.result.toString(); + } +} diff --git a/gun-server/node_modules/@peculiar/asn1-schema/build/es2015/converters.js b/gun-server/node_modules/@peculiar/asn1-schema/build/es2015/converters.js new file mode 100644 index 0000000..e641506 --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/build/es2015/converters.js @@ -0,0 +1,136 @@ +import * as asn1js from "asn1js"; +import { AsnPropTypes } from "./enums"; +import { OctetString } from "./types/index"; +export const AsnAnyConverter = { + fromASN: (value) => value instanceof asn1js.Null ? null : value.valueBeforeDecodeView, + toASN: (value) => { + if (value === null) { + return new asn1js.Null(); + } + const schema = asn1js.fromBER(value); + if (schema.result.error) { + throw new Error(schema.result.error); + } + return schema.result; + }, +}; +export const AsnIntegerConverter = { + fromASN: (value) => value.valueBlock.valueHexView.byteLength >= 4 + ? value.valueBlock.toString() + : value.valueBlock.valueDec, + toASN: (value) => new asn1js.Integer({ value: +value }), +}; +export const AsnEnumeratedConverter = { + fromASN: (value) => value.valueBlock.valueDec, + toASN: (value) => new asn1js.Enumerated({ value }), +}; +export const AsnIntegerArrayBufferConverter = { + fromASN: (value) => value.valueBlock.valueHexView, + toASN: (value) => new asn1js.Integer({ valueHex: value }), +}; +export const AsnIntegerBigIntConverter = { + fromASN: (value) => value.toBigInt(), + toASN: (value) => asn1js.Integer.fromBigInt(value), +}; +export const AsnBitStringConverter = { + fromASN: (value) => value.valueBlock.valueHexView, + toASN: (value) => new asn1js.BitString({ valueHex: value }), +}; +export const AsnObjectIdentifierConverter = { + fromASN: (value) => value.valueBlock.toString(), + toASN: (value) => new asn1js.ObjectIdentifier({ value }), +}; +export const AsnBooleanConverter = { + fromASN: (value) => value.valueBlock.value, + toASN: (value) => new asn1js.Boolean({ value }), +}; +export const AsnOctetStringConverter = { + fromASN: (value) => value.valueBlock.valueHexView, + toASN: (value) => new asn1js.OctetString({ valueHex: value }), +}; +export const AsnConstructedOctetStringConverter = { + fromASN: (value) => new OctetString(value.getValue()), + toASN: (value) => value.toASN(), +}; +function createStringConverter(Asn1Type) { + return { + fromASN: (value) => value.valueBlock.value, + toASN: (value) => new Asn1Type({ value }), + }; +} +export const AsnUtf8StringConverter = createStringConverter(asn1js.Utf8String); +export const AsnBmpStringConverter = createStringConverter(asn1js.BmpString); +export const AsnUniversalStringConverter = createStringConverter(asn1js.UniversalString); +export const AsnNumericStringConverter = createStringConverter(asn1js.NumericString); +export const AsnPrintableStringConverter = createStringConverter(asn1js.PrintableString); +export const AsnTeletexStringConverter = createStringConverter(asn1js.TeletexString); +export const AsnVideotexStringConverter = createStringConverter(asn1js.VideotexString); +export const AsnIA5StringConverter = createStringConverter(asn1js.IA5String); +export const AsnGraphicStringConverter = createStringConverter(asn1js.GraphicString); +export const AsnVisibleStringConverter = createStringConverter(asn1js.VisibleString); +export const AsnGeneralStringConverter = createStringConverter(asn1js.GeneralString); +export const AsnCharacterStringConverter = createStringConverter(asn1js.CharacterString); +export const AsnUTCTimeConverter = { + fromASN: (value) => value.toDate(), + toASN: (value) => new asn1js.UTCTime({ valueDate: value }), +}; +export const AsnGeneralizedTimeConverter = { + fromASN: (value) => value.toDate(), + toASN: (value) => new asn1js.GeneralizedTime({ valueDate: value }), +}; +export const AsnNullConverter = { + fromASN: () => null, + toASN: () => { + return new asn1js.Null(); + }, +}; +export function defaultConverter(type) { + switch (type) { + case AsnPropTypes.Any: + return AsnAnyConverter; + case AsnPropTypes.BitString: + return AsnBitStringConverter; + case AsnPropTypes.BmpString: + return AsnBmpStringConverter; + case AsnPropTypes.Boolean: + return AsnBooleanConverter; + case AsnPropTypes.CharacterString: + return AsnCharacterStringConverter; + case AsnPropTypes.Enumerated: + return AsnEnumeratedConverter; + case AsnPropTypes.GeneralString: + return AsnGeneralStringConverter; + case AsnPropTypes.GeneralizedTime: + return AsnGeneralizedTimeConverter; + case AsnPropTypes.GraphicString: + return AsnGraphicStringConverter; + case AsnPropTypes.IA5String: + return AsnIA5StringConverter; + case AsnPropTypes.Integer: + return AsnIntegerConverter; + case AsnPropTypes.Null: + return AsnNullConverter; + case AsnPropTypes.NumericString: + return AsnNumericStringConverter; + case AsnPropTypes.ObjectIdentifier: + return AsnObjectIdentifierConverter; + case AsnPropTypes.OctetString: + return AsnOctetStringConverter; + case AsnPropTypes.PrintableString: + return AsnPrintableStringConverter; + case AsnPropTypes.TeletexString: + return AsnTeletexStringConverter; + case AsnPropTypes.UTCTime: + return AsnUTCTimeConverter; + case AsnPropTypes.UniversalString: + return AsnUniversalStringConverter; + case AsnPropTypes.Utf8String: + return AsnUtf8StringConverter; + case AsnPropTypes.VideotexString: + return AsnVideotexStringConverter; + case AsnPropTypes.VisibleString: + return AsnVisibleStringConverter; + default: + return null; + } +} diff --git a/gun-server/node_modules/@peculiar/asn1-schema/build/es2015/decorators.js b/gun-server/node_modules/@peculiar/asn1-schema/build/es2015/decorators.js new file mode 100644 index 0000000..43b1e3d --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/build/es2015/decorators.js @@ -0,0 +1,36 @@ +import * as converters from "./converters"; +import { AsnTypeTypes } from "./enums"; +import { schemaStorage } from "./storage"; +export const AsnType = (options) => (target) => { + let schema; + if (!schemaStorage.has(target)) { + schema = schemaStorage.createDefault(target); + schemaStorage.set(target, schema); + } + else { + schema = schemaStorage.get(target); + } + Object.assign(schema, options); +}; +export const AsnChoiceType = () => AsnType({ type: AsnTypeTypes.Choice }); +export const AsnSetType = (options) => AsnType({ type: AsnTypeTypes.Set, ...options }); +export const AsnSequenceType = (options) => AsnType({ type: AsnTypeTypes.Sequence, ...options }); +export const AsnProp = (options) => (target, propertyKey) => { + let schema; + if (!schemaStorage.has(target.constructor)) { + schema = schemaStorage.createDefault(target.constructor); + schemaStorage.set(target.constructor, schema); + } + else { + schema = schemaStorage.get(target.constructor); + } + const copyOptions = Object.assign({}, options); + if (typeof copyOptions.type === "number" && !copyOptions.converter) { + const defaultConverter = converters.defaultConverter(options.type); + if (!defaultConverter) { + throw new Error(`Cannot get default converter for property '${propertyKey}' of ${target.constructor.name}`); + } + copyOptions.converter = defaultConverter; + } + schema.items[propertyKey] = copyOptions; +}; diff --git a/gun-server/node_modules/@peculiar/asn1-schema/build/es2015/enums.js b/gun-server/node_modules/@peculiar/asn1-schema/build/es2015/enums.js new file mode 100644 index 0000000..e681c3c --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/build/es2015/enums.js @@ -0,0 +1,36 @@ +export var AsnTypeTypes; +(function (AsnTypeTypes) { + AsnTypeTypes[AsnTypeTypes["Sequence"] = 0] = "Sequence"; + AsnTypeTypes[AsnTypeTypes["Set"] = 1] = "Set"; + AsnTypeTypes[AsnTypeTypes["Choice"] = 2] = "Choice"; +})(AsnTypeTypes || (AsnTypeTypes = {})); +export var AsnPropTypes; +(function (AsnPropTypes) { + AsnPropTypes[AsnPropTypes["Any"] = 1] = "Any"; + AsnPropTypes[AsnPropTypes["Boolean"] = 2] = "Boolean"; + AsnPropTypes[AsnPropTypes["OctetString"] = 3] = "OctetString"; + AsnPropTypes[AsnPropTypes["BitString"] = 4] = "BitString"; + AsnPropTypes[AsnPropTypes["Integer"] = 5] = "Integer"; + AsnPropTypes[AsnPropTypes["Enumerated"] = 6] = "Enumerated"; + AsnPropTypes[AsnPropTypes["ObjectIdentifier"] = 7] = "ObjectIdentifier"; + AsnPropTypes[AsnPropTypes["Utf8String"] = 8] = "Utf8String"; + AsnPropTypes[AsnPropTypes["BmpString"] = 9] = "BmpString"; + AsnPropTypes[AsnPropTypes["UniversalString"] = 10] = "UniversalString"; + AsnPropTypes[AsnPropTypes["NumericString"] = 11] = "NumericString"; + AsnPropTypes[AsnPropTypes["PrintableString"] = 12] = "PrintableString"; + AsnPropTypes[AsnPropTypes["TeletexString"] = 13] = "TeletexString"; + AsnPropTypes[AsnPropTypes["VideotexString"] = 14] = "VideotexString"; + AsnPropTypes[AsnPropTypes["IA5String"] = 15] = "IA5String"; + AsnPropTypes[AsnPropTypes["GraphicString"] = 16] = "GraphicString"; + AsnPropTypes[AsnPropTypes["VisibleString"] = 17] = "VisibleString"; + AsnPropTypes[AsnPropTypes["GeneralString"] = 18] = "GeneralString"; + AsnPropTypes[AsnPropTypes["CharacterString"] = 19] = "CharacterString"; + AsnPropTypes[AsnPropTypes["UTCTime"] = 20] = "UTCTime"; + AsnPropTypes[AsnPropTypes["GeneralizedTime"] = 21] = "GeneralizedTime"; + AsnPropTypes[AsnPropTypes["DATE"] = 22] = "DATE"; + AsnPropTypes[AsnPropTypes["TimeOfDay"] = 23] = "TimeOfDay"; + AsnPropTypes[AsnPropTypes["DateTime"] = 24] = "DateTime"; + AsnPropTypes[AsnPropTypes["Duration"] = 25] = "Duration"; + AsnPropTypes[AsnPropTypes["TIME"] = 26] = "TIME"; + AsnPropTypes[AsnPropTypes["Null"] = 27] = "Null"; +})(AsnPropTypes || (AsnPropTypes = {})); diff --git a/gun-server/node_modules/@peculiar/asn1-schema/build/es2015/errors/index.js b/gun-server/node_modules/@peculiar/asn1-schema/build/es2015/errors/index.js new file mode 100644 index 0000000..6edc538 --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/build/es2015/errors/index.js @@ -0,0 +1 @@ +export * from "./schema_validation"; diff --git a/gun-server/node_modules/@peculiar/asn1-schema/build/es2015/errors/schema_validation.js b/gun-server/node_modules/@peculiar/asn1-schema/build/es2015/errors/schema_validation.js new file mode 100644 index 0000000..4fcc936 --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/build/es2015/errors/schema_validation.js @@ -0,0 +1,6 @@ +export class AsnSchemaValidationError extends Error { + constructor() { + super(...arguments); + this.schemas = []; + } +} diff --git a/gun-server/node_modules/@peculiar/asn1-schema/build/es2015/helper.js b/gun-server/node_modules/@peculiar/asn1-schema/build/es2015/helper.js new file mode 100644 index 0000000..6e298db --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/build/es2015/helper.js @@ -0,0 +1,40 @@ +export function isConvertible(target) { + if (typeof target === "function" && target.prototype) { + if (target.prototype.toASN && target.prototype.fromASN) { + return true; + } + else { + return isConvertible(target.prototype); + } + } + else { + return !!(target && typeof target === "object" && "toASN" in target && "fromASN" in target); + } +} +export function isTypeOfArray(target) { + var _a; + if (target) { + const proto = Object.getPrototypeOf(target); + if (((_a = proto === null || proto === void 0 ? void 0 : proto.prototype) === null || _a === void 0 ? void 0 : _a.constructor) === Array) { + return true; + } + return isTypeOfArray(proto); + } + return false; +} +export function isArrayEqual(bytes1, bytes2) { + if (!(bytes1 && bytes2)) { + return false; + } + if (bytes1.byteLength !== bytes2.byteLength) { + return false; + } + const b1 = new Uint8Array(bytes1); + const b2 = new Uint8Array(bytes2); + for (let i = 0; i < bytes1.byteLength; i++) { + if (b1[i] !== b2[i]) { + return false; + } + } + return true; +} diff --git a/gun-server/node_modules/@peculiar/asn1-schema/build/es2015/index.js b/gun-server/node_modules/@peculiar/asn1-schema/build/es2015/index.js new file mode 100644 index 0000000..1c0049e --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/build/es2015/index.js @@ -0,0 +1,9 @@ +export * from "./converters"; +export * from "./types/index"; +export { AsnProp, AsnType, AsnChoiceType, AsnSequenceType, AsnSetType } from "./decorators"; +export { AsnTypeTypes, AsnPropTypes } from "./enums"; +export { AsnParser } from "./parser"; +export { AsnSerializer } from "./serializer"; +export * from "./errors"; +export * from "./objects"; +export * from "./convert"; diff --git a/gun-server/node_modules/@peculiar/asn1-schema/build/es2015/objects.js b/gun-server/node_modules/@peculiar/asn1-schema/build/es2015/objects.js new file mode 100644 index 0000000..b858c74 --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/build/es2015/objects.js @@ -0,0 +1,13 @@ +export class AsnArray extends Array { + constructor(items = []) { + if (typeof items === "number") { + super(items); + } + else { + super(); + for (const item of items) { + this.push(item); + } + } + } +} diff --git a/gun-server/node_modules/@peculiar/asn1-schema/build/es2015/parser.js b/gun-server/node_modules/@peculiar/asn1-schema/build/es2015/parser.js new file mode 100644 index 0000000..a1f191a --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/build/es2015/parser.js @@ -0,0 +1,136 @@ +import * as asn1js from "asn1js"; +import { AsnPropTypes, AsnTypeTypes } from "./enums"; +import * as converters from "./converters"; +import { AsnSchemaValidationError } from "./errors"; +import { isConvertible, isTypeOfArray } from "./helper"; +import { schemaStorage } from "./storage"; +export class AsnParser { + static parse(data, target) { + const asn1Parsed = asn1js.fromBER(data); + if (asn1Parsed.result.error) { + throw new Error(asn1Parsed.result.error); + } + const res = this.fromASN(asn1Parsed.result, target); + return res; + } + static fromASN(asn1Schema, target) { + var _a; + try { + if (isConvertible(target)) { + const value = new target(); + return value.fromASN(asn1Schema); + } + const schema = schemaStorage.get(target); + schemaStorage.cache(target); + let targetSchema = schema.schema; + if (asn1Schema.constructor === asn1js.Constructed && schema.type !== AsnTypeTypes.Choice) { + targetSchema = new asn1js.Constructed({ + idBlock: { + tagClass: 3, + tagNumber: asn1Schema.idBlock.tagNumber, + }, + value: schema.schema.valueBlock.value, + }); + for (const key in schema.items) { + delete asn1Schema[key]; + } + } + const asn1ComparedSchema = asn1js.compareSchema({}, asn1Schema, targetSchema); + if (!asn1ComparedSchema.verified) { + throw new AsnSchemaValidationError(`Data does not match to ${target.name} ASN1 schema. ${asn1ComparedSchema.result.error}`); + } + const res = new target(); + if (isTypeOfArray(target)) { + if (!("value" in asn1Schema.valueBlock && Array.isArray(asn1Schema.valueBlock.value))) { + throw new Error(`Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.`); + } + const itemType = schema.itemType; + if (typeof itemType === "number") { + const converter = converters.defaultConverter(itemType); + if (!converter) { + throw new Error(`Cannot get default converter for array item of ${target.name} ASN1 schema`); + } + return target.from(asn1Schema.valueBlock.value, (element) => converter.fromASN(element)); + } + else { + return target.from(asn1Schema.valueBlock.value, (element) => this.fromASN(element, itemType)); + } + } + for (const key in schema.items) { + const asn1SchemaValue = asn1ComparedSchema.result[key]; + if (!asn1SchemaValue) { + continue; + } + const schemaItem = schema.items[key]; + const schemaItemType = schemaItem.type; + if (typeof schemaItemType === "number" || isConvertible(schemaItemType)) { + const converter = (_a = schemaItem.converter) !== null && _a !== void 0 ? _a : (isConvertible(schemaItemType) + ? new schemaItemType() + : null); + if (!converter) { + throw new Error("Converter is empty"); + } + if (schemaItem.repeated) { + if (schemaItem.implicit) { + const Container = schemaItem.repeated === "sequence" + ? asn1js.Sequence + : asn1js.Set; + const newItem = new Container(); + newItem.valueBlock = asn1SchemaValue.valueBlock; + const newItemAsn = asn1js.fromBER(newItem.toBER(false)); + if (newItemAsn.offset === -1) { + throw new Error(`Cannot parse the child item. ${newItemAsn.result.error}`); + } + if (!("value" in newItemAsn.result.valueBlock && Array.isArray(newItemAsn.result.valueBlock.value))) { + throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed."); + } + const value = newItemAsn.result.valueBlock.value; + res[key] = Array.from(value, (element) => converter.fromASN(element)); + } + else { + res[key] = Array.from(asn1SchemaValue, (element) => converter.fromASN(element)); + } + } + else { + let value = asn1SchemaValue; + if (schemaItem.implicit) { + let newItem; + if (isConvertible(schemaItemType)) { + newItem = new schemaItemType().toSchema(""); + } + else { + const Asn1TypeName = AsnPropTypes[schemaItemType]; + const Asn1Type = asn1js[Asn1TypeName]; + if (!Asn1Type) { + throw new Error(`Cannot get '${Asn1TypeName}' class from asn1js module`); + } + newItem = new Asn1Type(); + } + newItem.valueBlock = value.valueBlock; + value = asn1js.fromBER(newItem.toBER(false)).result; + } + res[key] = converter.fromASN(value); + } + } + else { + if (schemaItem.repeated) { + if (!Array.isArray(asn1SchemaValue)) { + throw new Error("Cannot get list of items from the ASN.1 parsed value. ASN.1 value should be iterable."); + } + res[key] = Array.from(asn1SchemaValue, (element) => this.fromASN(element, schemaItemType)); + } + else { + res[key] = this.fromASN(asn1SchemaValue, schemaItemType); + } + } + } + return res; + } + catch (error) { + if (error instanceof AsnSchemaValidationError) { + error.schemas.push(target.name); + } + throw error; + } + } +} diff --git a/gun-server/node_modules/@peculiar/asn1-schema/build/es2015/schema.js b/gun-server/node_modules/@peculiar/asn1-schema/build/es2015/schema.js new file mode 100644 index 0000000..abac0b5 --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/build/es2015/schema.js @@ -0,0 +1,159 @@ +import * as asn1js from "asn1js"; +import { AsnPropTypes, AsnTypeTypes } from "./enums"; +import { isConvertible } from "./helper"; +export class AsnSchemaStorage { + constructor() { + this.items = new WeakMap(); + } + has(target) { + return this.items.has(target); + } + get(target, checkSchema = false) { + const schema = this.items.get(target); + if (!schema) { + throw new Error(`Cannot get schema for '${target.prototype.constructor.name}' target`); + } + if (checkSchema && !schema.schema) { + throw new Error(`Schema '${target.prototype.constructor.name}' doesn't contain ASN.1 schema. Call 'AsnSchemaStorage.cache'.`); + } + return schema; + } + cache(target) { + const schema = this.get(target); + if (!schema.schema) { + schema.schema = this.create(target, true); + } + } + createDefault(target) { + const schema = { + type: AsnTypeTypes.Sequence, + items: {}, + }; + const parentSchema = this.findParentSchema(target); + if (parentSchema) { + Object.assign(schema, parentSchema); + schema.items = Object.assign({}, schema.items, parentSchema.items); + } + return schema; + } + create(target, useNames) { + const schema = this.items.get(target) || this.createDefault(target); + const asn1Value = []; + for (const key in schema.items) { + const item = schema.items[key]; + const name = useNames ? key : ""; + let asn1Item; + if (typeof (item.type) === "number") { + const Asn1TypeName = AsnPropTypes[item.type]; + const Asn1Type = asn1js[Asn1TypeName]; + if (!Asn1Type) { + throw new Error(`Cannot get ASN1 class by name '${Asn1TypeName}'`); + } + asn1Item = new Asn1Type({ name }); + } + else if (isConvertible(item.type)) { + const instance = new item.type(); + asn1Item = instance.toSchema(name); + } + else if (item.optional) { + const itemSchema = this.get(item.type); + if (itemSchema.type === AsnTypeTypes.Choice) { + asn1Item = new asn1js.Any({ name }); + } + else { + asn1Item = this.create(item.type, false); + asn1Item.name = name; + } + } + else { + asn1Item = new asn1js.Any({ name }); + } + const optional = !!item.optional || item.defaultValue !== undefined; + if (item.repeated) { + asn1Item.name = ""; + const Container = item.repeated === "set" + ? asn1js.Set + : asn1js.Sequence; + asn1Item = new Container({ + name: "", + value: [ + new asn1js.Repeated({ + name, + value: asn1Item, + }), + ], + }); + } + if (item.context !== null && item.context !== undefined) { + if (item.implicit) { + if (typeof item.type === "number" || isConvertible(item.type)) { + const Container = item.repeated + ? asn1js.Constructed + : asn1js.Primitive; + asn1Value.push(new Container({ + name, + optional, + idBlock: { + tagClass: 3, + tagNumber: item.context, + }, + })); + } + else { + this.cache(item.type); + const isRepeated = !!item.repeated; + let value = !isRepeated + ? this.get(item.type, true).schema + : asn1Item; + value = "valueBlock" in value ? value.valueBlock.value : value.value; + asn1Value.push(new asn1js.Constructed({ + name: !isRepeated ? name : "", + optional, + idBlock: { + tagClass: 3, + tagNumber: item.context, + }, + value: value, + })); + } + } + else { + asn1Value.push(new asn1js.Constructed({ + optional, + idBlock: { + tagClass: 3, + tagNumber: item.context, + }, + value: [asn1Item], + })); + } + } + else { + asn1Item.optional = optional; + asn1Value.push(asn1Item); + } + } + switch (schema.type) { + case AsnTypeTypes.Sequence: + return new asn1js.Sequence({ value: asn1Value, name: "" }); + case AsnTypeTypes.Set: + return new asn1js.Set({ value: asn1Value, name: "" }); + case AsnTypeTypes.Choice: + return new asn1js.Choice({ value: asn1Value, name: "" }); + default: + throw new Error(`Unsupported ASN1 type in use`); + } + } + set(target, schema) { + this.items.set(target, schema); + return this; + } + findParentSchema(target) { + const parent = Object.getPrototypeOf(target); + if (parent) { + const schema = this.items.get(parent); + return schema || this.findParentSchema(parent); + } + return null; + } +} diff --git a/gun-server/node_modules/@peculiar/asn1-schema/build/es2015/serializer.js b/gun-server/node_modules/@peculiar/asn1-schema/build/es2015/serializer.js new file mode 100644 index 0000000..848dcb6 --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/build/es2015/serializer.js @@ -0,0 +1,154 @@ +import * as asn1js from "asn1js"; +import * as converters from "./converters"; +import { AsnPropTypes, AsnTypeTypes } from "./enums"; +import { isConvertible, isArrayEqual } from "./helper"; +import { schemaStorage } from "./storage"; +export class AsnSerializer { + static serialize(obj) { + if (obj instanceof asn1js.BaseBlock) { + return obj.toBER(false); + } + return this.toASN(obj).toBER(false); + } + static toASN(obj) { + if (obj && typeof obj === "object" && isConvertible(obj)) { + return obj.toASN(); + } + if (!(obj && typeof obj === "object")) { + throw new TypeError("Parameter 1 should be type of Object."); + } + const target = obj.constructor; + const schema = schemaStorage.get(target); + schemaStorage.cache(target); + let asn1Value = []; + if (schema.itemType) { + if (!Array.isArray(obj)) { + throw new TypeError("Parameter 1 should be type of Array."); + } + if (typeof schema.itemType === "number") { + const converter = converters.defaultConverter(schema.itemType); + if (!converter) { + throw new Error(`Cannot get default converter for array item of ${target.name} ASN1 schema`); + } + asn1Value = obj.map((o) => converter.toASN(o)); + } + else { + asn1Value = obj.map((o) => this.toAsnItem({ type: schema.itemType }, "[]", target, o)); + } + } + else { + for (const key in schema.items) { + const schemaItem = schema.items[key]; + const objProp = obj[key]; + if (objProp === undefined + || schemaItem.defaultValue === objProp + || (typeof schemaItem.defaultValue === "object" && typeof objProp === "object" + && isArrayEqual(this.serialize(schemaItem.defaultValue), this.serialize(objProp)))) { + continue; + } + const asn1Item = AsnSerializer.toAsnItem(schemaItem, key, target, objProp); + if (typeof schemaItem.context === "number") { + if (schemaItem.implicit) { + if (!schemaItem.repeated + && (typeof schemaItem.type === "number" || isConvertible(schemaItem.type))) { + const value = {}; + value.valueHex = asn1Item instanceof asn1js.Null ? asn1Item.valueBeforeDecodeView : asn1Item.valueBlock.toBER(); + asn1Value.push(new asn1js.Primitive({ + optional: schemaItem.optional, + idBlock: { + tagClass: 3, + tagNumber: schemaItem.context, + }, + ...value, + })); + } + else { + asn1Value.push(new asn1js.Constructed({ + optional: schemaItem.optional, + idBlock: { + tagClass: 3, + tagNumber: schemaItem.context, + }, + value: asn1Item.valueBlock.value, + })); + } + } + else { + asn1Value.push(new asn1js.Constructed({ + optional: schemaItem.optional, + idBlock: { + tagClass: 3, + tagNumber: schemaItem.context, + }, + value: [asn1Item], + })); + } + } + else if (schemaItem.repeated) { + asn1Value = asn1Value.concat(asn1Item); + } + else { + asn1Value.push(asn1Item); + } + } + } + let asnSchema; + switch (schema.type) { + case AsnTypeTypes.Sequence: + asnSchema = new asn1js.Sequence({ value: asn1Value }); + break; + case AsnTypeTypes.Set: + asnSchema = new asn1js.Set({ value: asn1Value }); + break; + case AsnTypeTypes.Choice: + if (!asn1Value[0]) { + throw new Error(`Schema '${target.name}' has wrong data. Choice cannot be empty.`); + } + asnSchema = asn1Value[0]; + break; + } + return asnSchema; + } + static toAsnItem(schemaItem, key, target, objProp) { + let asn1Item; + if (typeof (schemaItem.type) === "number") { + const converter = schemaItem.converter; + if (!converter) { + throw new Error(`Property '${key}' doesn't have converter for type ${AsnPropTypes[schemaItem.type]} in schema '${target.name}'`); + } + if (schemaItem.repeated) { + if (!Array.isArray(objProp)) { + throw new TypeError("Parameter 'objProp' should be type of Array."); + } + const items = Array.from(objProp, (element) => converter.toASN(element)); + const Container = schemaItem.repeated === "sequence" + ? asn1js.Sequence + : asn1js.Set; + asn1Item = new Container({ + value: items, + }); + } + else { + asn1Item = converter.toASN(objProp); + } + } + else { + if (schemaItem.repeated) { + if (!Array.isArray(objProp)) { + throw new TypeError("Parameter 'objProp' should be type of Array."); + } + const items = Array.from(objProp, (element) => this.toASN(element)); + const Container = schemaItem.repeated === "sequence" + ? asn1js.Sequence + : asn1js.Set; + asn1Item = new Container({ + value: items, + }); + } + else { + asn1Item = this.toASN(objProp); + } + } + return asn1Item; + } +} diff --git a/gun-server/node_modules/@peculiar/asn1-schema/build/es2015/storage.js b/gun-server/node_modules/@peculiar/asn1-schema/build/es2015/storage.js new file mode 100644 index 0000000..5379efd --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/build/es2015/storage.js @@ -0,0 +1,2 @@ +import { AsnSchemaStorage } from "./schema"; +export const schemaStorage = new AsnSchemaStorage(); diff --git a/gun-server/node_modules/@peculiar/asn1-schema/build/es2015/types.js b/gun-server/node_modules/@peculiar/asn1-schema/build/es2015/types.js new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/build/es2015/types.js @@ -0,0 +1 @@ +export {}; diff --git a/gun-server/node_modules/@peculiar/asn1-schema/build/es2015/types/bit_string.js b/gun-server/node_modules/@peculiar/asn1-schema/build/es2015/types/bit_string.js new file mode 100644 index 0000000..1d8367c --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/build/es2015/types/bit_string.js @@ -0,0 +1,59 @@ +import * as asn1js from "asn1js"; +import { BufferSourceConverter } from "pvtsutils"; +export class BitString { + constructor(params, unusedBits = 0) { + this.unusedBits = 0; + this.value = new ArrayBuffer(0); + if (params) { + if (typeof params === "number") { + this.fromNumber(params); + } + else if (BufferSourceConverter.isBufferSource(params)) { + this.unusedBits = unusedBits; + this.value = BufferSourceConverter.toArrayBuffer(params); + } + else { + throw TypeError("Unsupported type of 'params' argument for BitString"); + } + } + } + fromASN(asn) { + if (!(asn instanceof asn1js.BitString)) { + throw new TypeError("Argument 'asn' is not instance of ASN.1 BitString"); + } + this.unusedBits = asn.valueBlock.unusedBits; + this.value = asn.valueBlock.valueHex; + return this; + } + toASN() { + return new asn1js.BitString({ unusedBits: this.unusedBits, valueHex: this.value }); + } + toSchema(name) { + return new asn1js.BitString({ name }); + } + toNumber() { + let res = ""; + const uintArray = new Uint8Array(this.value); + for (const octet of uintArray) { + res += octet.toString(2).padStart(8, "0"); + } + res = res.split("").reverse().join(""); + if (this.unusedBits) { + res = res.slice(this.unusedBits).padStart(this.unusedBits, "0"); + } + return parseInt(res, 2); + } + fromNumber(value) { + let bits = value.toString(2); + const octetSize = (bits.length + 7) >> 3; + this.unusedBits = (octetSize << 3) - bits.length; + const octets = new Uint8Array(octetSize); + bits = bits.padStart(octetSize << 3, "0").split("").reverse().join(""); + let index = 0; + while (index < octetSize) { + octets[index] = parseInt(bits.slice(index << 3, (index << 3) + 8), 2); + index++; + } + this.value = octets.buffer; + } +} diff --git a/gun-server/node_modules/@peculiar/asn1-schema/build/es2015/types/index.js b/gun-server/node_modules/@peculiar/asn1-schema/build/es2015/types/index.js new file mode 100644 index 0000000..28ceb71 --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/build/es2015/types/index.js @@ -0,0 +1,2 @@ +export * from "./bit_string"; +export * from "./octet_string"; diff --git a/gun-server/node_modules/@peculiar/asn1-schema/build/es2015/types/octet_string.js b/gun-server/node_modules/@peculiar/asn1-schema/build/es2015/types/octet_string.js new file mode 100644 index 0000000..f552953 --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/build/es2015/types/octet_string.js @@ -0,0 +1,39 @@ +import * as asn1js from "asn1js"; +import { BufferSourceConverter } from "pvtsutils"; +export class OctetString { + get byteLength() { + return this.buffer.byteLength; + } + get byteOffset() { + return 0; + } + constructor(param) { + if (typeof param === "number") { + this.buffer = new ArrayBuffer(param); + } + else { + if (BufferSourceConverter.isBufferSource(param)) { + this.buffer = BufferSourceConverter.toArrayBuffer(param); + } + else if (Array.isArray(param)) { + this.buffer = new Uint8Array(param); + } + else { + this.buffer = new ArrayBuffer(0); + } + } + } + fromASN(asn) { + if (!(asn instanceof asn1js.OctetString)) { + throw new TypeError("Argument 'asn' is not instance of ASN.1 OctetString"); + } + this.buffer = asn.valueBlock.valueHex; + return this; + } + toASN() { + return new asn1js.OctetString({ valueHex: this.buffer }); + } + toSchema(name) { + return new asn1js.OctetString({ name }); + } +} diff --git a/gun-server/node_modules/@peculiar/asn1-schema/build/types/convert.d.ts b/gun-server/node_modules/@peculiar/asn1-schema/build/types/convert.d.ts new file mode 100644 index 0000000..9bd5d7f --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/build/types/convert.d.ts @@ -0,0 +1,18 @@ +import { BufferSource } from "pvtsutils"; +import { IEmptyConstructor } from "./types"; +export declare class AsnConvert { + static serialize(obj: unknown): ArrayBuffer; + static parse(data: BufferSource, target: IEmptyConstructor): T; + /** + * Returns a string representation of an ASN.1 encoded data + * @param data ASN.1 encoded buffer source + * @returns String representation of ASN.1 structure + */ + static toString(data: BufferSource): string; + /** + * Returns a string representation of an ASN.1 schema + * @param obj Object which can be serialized to ASN.1 schema + * @returns String representation of ASN.1 structure + */ + static toString(obj: unknown): string; +} diff --git a/gun-server/node_modules/@peculiar/asn1-schema/build/types/converters.d.ts b/gun-server/node_modules/@peculiar/asn1-schema/build/types/converters.d.ts new file mode 100644 index 0000000..5f24d73 --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/build/types/converters.d.ts @@ -0,0 +1,113 @@ +import * as asn1js from "asn1js"; +import { AnyConverterType, IAsnConverter, IntegerConverterType } from "./types"; +import { AsnPropTypes } from "./enums"; +import { OctetString } from "./types/index"; +/** + * NOTE: Converter MUST have name AsnConverter. + * Asn1Prop decorator link custom converters by name of the Asn1PropType + */ +/** + * ASN.1 ANY converter + */ +export declare const AsnAnyConverter: IAsnConverter; +/** + * ASN.1 INTEGER to Number/String converter + */ +export declare const AsnIntegerConverter: IAsnConverter; +/** + * ASN.1 ENUMERATED converter + */ +export declare const AsnEnumeratedConverter: IAsnConverter; +/** + * ASN.1 INTEGER to ArrayBuffer converter + */ +export declare const AsnIntegerArrayBufferConverter: IAsnConverter; +/** + * ASN.1 INTEGER to BigInt converter + */ +export declare const AsnIntegerBigIntConverter: IAsnConverter; +/** + * ASN.1 BIT STRING converter + */ +export declare const AsnBitStringConverter: IAsnConverter; +/** + * ASN.1 OBJECT IDENTIFIER converter + */ +export declare const AsnObjectIdentifierConverter: IAsnConverter; +/** + * ASN.1 BOOLEAN converter + */ +export declare const AsnBooleanConverter: IAsnConverter; +/** + * ASN.1 OCTET_STRING converter + */ +export declare const AsnOctetStringConverter: IAsnConverter; +/** + * ASN.1 OCTET_STRING converter to OctetString class + */ +export declare const AsnConstructedOctetStringConverter: IAsnConverter; +/** + * ASN.1 UTF8_STRING converter + */ +export declare const AsnUtf8StringConverter: IAsnConverter; +/** + * ASN.1 BPM STRING converter + */ +export declare const AsnBmpStringConverter: IAsnConverter; +/** + * ASN.1 UNIVERSAL STRING converter + */ +export declare const AsnUniversalStringConverter: IAsnConverter; +/** + * ASN.1 NUMERIC STRING converter + */ +export declare const AsnNumericStringConverter: IAsnConverter; +/** + * ASN.1 PRINTABLE STRING converter + */ +export declare const AsnPrintableStringConverter: IAsnConverter; +/** + * ASN.1 TELETEX STRING converter + */ +export declare const AsnTeletexStringConverter: IAsnConverter; +/** + * ASN.1 VIDEOTEX STRING converter + */ +export declare const AsnVideotexStringConverter: IAsnConverter; +/** + * ASN.1 IA5 STRING converter + */ +export declare const AsnIA5StringConverter: IAsnConverter; +/** + * ASN.1 GRAPHIC STRING converter + */ +export declare const AsnGraphicStringConverter: IAsnConverter; +/** + * ASN.1 VISIBLE STRING converter + */ +export declare const AsnVisibleStringConverter: IAsnConverter; +/** + * ASN.1 GENERAL STRING converter + */ +export declare const AsnGeneralStringConverter: IAsnConverter; +/** + * ASN.1 CHARACTER STRING converter + */ +export declare const AsnCharacterStringConverter: IAsnConverter; +/** + * ASN.1 UTCTime converter + */ +export declare const AsnUTCTimeConverter: IAsnConverter; +/** + * ASN.1 GeneralizedTime converter + */ +export declare const AsnGeneralizedTimeConverter: IAsnConverter; +/** + * ASN.1 ANY converter + */ +export declare const AsnNullConverter: IAsnConverter; +/** + * Returns default converter for specified type + * @param type + */ +export declare function defaultConverter(type: AsnPropTypes): IAsnConverter | null; diff --git a/gun-server/node_modules/@peculiar/asn1-schema/build/types/decorators.d.ts b/gun-server/node_modules/@peculiar/asn1-schema/build/types/decorators.d.ts new file mode 100644 index 0000000..54bc349 --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/build/types/decorators.d.ts @@ -0,0 +1,31 @@ +import { AsnPropTypes, AsnTypeTypes } from "./enums"; +import { IAsnConverter, IEmptyConstructor } from "./types"; +export type AsnItemType = AsnPropTypes | IEmptyConstructor; +export interface IAsn1TypeOptions { + type: AsnTypeTypes; + itemType?: AsnItemType; +} +export type AsnRepeatTypeString = "sequence" | "set"; +export type AsnRepeatType = AsnRepeatTypeString; +export interface IAsn1PropOptions { + type: AsnItemType; + optional?: boolean; + defaultValue?: unknown; + context?: number; + implicit?: boolean; + converter?: IAsnConverter; + repeated?: AsnRepeatType; +} +export type AsnTypeDecorator = (target: IEmptyConstructor) => void; +export declare const AsnType: (options: IAsn1TypeOptions) => AsnTypeDecorator; +export declare const AsnChoiceType: () => AsnTypeDecorator; +export interface IAsn1SetOptions { + itemType: AsnItemType; +} +export declare const AsnSetType: (options: IAsn1SetOptions) => AsnTypeDecorator; +export interface IAsn1SequenceOptions { + itemType?: AsnItemType; +} +export declare const AsnSequenceType: (options: IAsn1SequenceOptions) => AsnTypeDecorator; +export type AsnPropDecorator = (target: object, propertyKey: string) => void; +export declare const AsnProp: (options: IAsn1PropOptions) => AsnPropDecorator; diff --git a/gun-server/node_modules/@peculiar/asn1-schema/build/types/enums.d.ts b/gun-server/node_modules/@peculiar/asn1-schema/build/types/enums.d.ts new file mode 100644 index 0000000..1312d25 --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/build/types/enums.d.ts @@ -0,0 +1,40 @@ +/** + * ASN.1 types for classes + */ +export declare enum AsnTypeTypes { + Sequence = 0, + Set = 1, + Choice = 2 +} +/** + * ASN.1 types for properties + */ +export declare enum AsnPropTypes { + Any = 1, + Boolean = 2, + OctetString = 3, + BitString = 4, + Integer = 5, + Enumerated = 6, + ObjectIdentifier = 7, + Utf8String = 8, + BmpString = 9, + UniversalString = 10, + NumericString = 11, + PrintableString = 12, + TeletexString = 13, + VideotexString = 14, + IA5String = 15, + GraphicString = 16, + VisibleString = 17, + GeneralString = 18, + CharacterString = 19, + UTCTime = 20, + GeneralizedTime = 21, + DATE = 22, + TimeOfDay = 23, + DateTime = 24, + Duration = 25, + TIME = 26, + Null = 27 +} diff --git a/gun-server/node_modules/@peculiar/asn1-schema/build/types/errors/index.d.ts b/gun-server/node_modules/@peculiar/asn1-schema/build/types/errors/index.d.ts new file mode 100644 index 0000000..6edc538 --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/build/types/errors/index.d.ts @@ -0,0 +1 @@ +export * from "./schema_validation"; diff --git a/gun-server/node_modules/@peculiar/asn1-schema/build/types/errors/schema_validation.d.ts b/gun-server/node_modules/@peculiar/asn1-schema/build/types/errors/schema_validation.d.ts new file mode 100644 index 0000000..81de5ad --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/build/types/errors/schema_validation.d.ts @@ -0,0 +1,3 @@ +export declare class AsnSchemaValidationError extends Error { + schemas: string[]; +} diff --git a/gun-server/node_modules/@peculiar/asn1-schema/build/types/helper.d.ts b/gun-server/node_modules/@peculiar/asn1-schema/build/types/helper.d.ts new file mode 100644 index 0000000..e7e2fd1 --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/build/types/helper.d.ts @@ -0,0 +1,5 @@ +import { IAsnConvertible, IEmptyConstructor } from "./types"; +export declare function isConvertible(target: IEmptyConstructor): target is (new () => IAsnConvertible); +export declare function isConvertible(target: unknown): target is IAsnConvertible; +export declare function isTypeOfArray(target: unknown): target is typeof Array; +export declare function isArrayEqual(bytes1: ArrayBuffer, bytes2: ArrayBuffer): boolean; diff --git a/gun-server/node_modules/@peculiar/asn1-schema/build/types/index.d.ts b/gun-server/node_modules/@peculiar/asn1-schema/build/types/index.d.ts new file mode 100644 index 0000000..f3d8397 --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/build/types/index.d.ts @@ -0,0 +1,10 @@ +export * from "./converters"; +export * from "./types/index"; +export { AsnProp, AsnType, AsnChoiceType, AsnSequenceType, AsnSetType } from "./decorators"; +export { AsnTypeTypes, AsnPropTypes } from "./enums"; +export { AsnParser } from "./parser"; +export { AsnSerializer } from "./serializer"; +export { IAsnConverter, IAsnConvertible } from "./types"; +export * from "./errors"; +export * from "./objects"; +export * from "./convert"; diff --git a/gun-server/node_modules/@peculiar/asn1-schema/build/types/objects.d.ts b/gun-server/node_modules/@peculiar/asn1-schema/build/types/objects.d.ts new file mode 100644 index 0000000..f57d9f3 --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/build/types/objects.d.ts @@ -0,0 +1,3 @@ +export declare abstract class AsnArray extends Array { + constructor(items?: T[]); +} diff --git a/gun-server/node_modules/@peculiar/asn1-schema/build/types/parser.d.ts b/gun-server/node_modules/@peculiar/asn1-schema/build/types/parser.d.ts new file mode 100644 index 0000000..50dd005 --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/build/types/parser.d.ts @@ -0,0 +1,20 @@ +import * as asn1js from "asn1js"; +import type { BufferSource } from "pvtsutils"; +import { IEmptyConstructor } from "./types"; +/** + * Deserializes objects from ASN.1 encoded data + */ +export declare class AsnParser { + /** + * Deserializes an object from the ASN.1 encoded buffer + * @param data ASN.1 encoded buffer + * @param target Target schema for object deserialization + */ + static parse(data: BufferSource, target: IEmptyConstructor): T; + /** + * Deserializes an object from the asn1js object + * @param asn1Schema asn1js object + * @param target Target schema for object deserialization + */ + static fromASN(asn1Schema: asn1js.AsnType, target: IEmptyConstructor): T; +} diff --git a/gun-server/node_modules/@peculiar/asn1-schema/build/types/schema.d.ts b/gun-server/node_modules/@peculiar/asn1-schema/build/types/schema.d.ts new file mode 100644 index 0000000..af504dc --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/build/types/schema.d.ts @@ -0,0 +1,33 @@ +import * as asn1js from "asn1js"; +import { AsnRepeatType } from "./decorators"; +import { AsnPropTypes, AsnTypeTypes } from "./enums"; +import { IAsnConverter, IEmptyConstructor } from "./types"; +export interface IAsnSchemaItem { + type: AsnPropTypes | IEmptyConstructor; + optional?: boolean; + defaultValue?: unknown; + context?: number; + implicit?: boolean; + converter?: IAsnConverter; + repeated?: AsnRepeatType; +} +export interface IAsnSchema { + type: AsnTypeTypes; + itemType: AsnPropTypes | IEmptyConstructor; + items: { + [key: string]: IAsnSchemaItem; + }; + schema?: AsnSchemaType; +} +export type AsnSchemaType = asn1js.Sequence | asn1js.Set | asn1js.Choice; +export declare class AsnSchemaStorage { + protected items: WeakMap; + has(target: object): boolean; + get(target: IEmptyConstructor, checkSchema: true): IAsnSchema & Required>; + get(target: IEmptyConstructor, checkSchema?: false): IAsnSchema; + cache(target: IEmptyConstructor): void; + createDefault(target: object): IAsnSchema; + create(target: object, useNames: boolean): AsnSchemaType; + set(target: object, schema: IAsnSchema): this; + protected findParentSchema(target: object): IAsnSchema | null; +} diff --git a/gun-server/node_modules/@peculiar/asn1-schema/build/types/serializer.d.ts b/gun-server/node_modules/@peculiar/asn1-schema/build/types/serializer.d.ts new file mode 100644 index 0000000..9405252 --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/build/types/serializer.d.ts @@ -0,0 +1,17 @@ +import * as asn1js from "asn1js"; +/** + * Serializes objects into ASN.1 encoded data + */ +export declare class AsnSerializer { + /** + * Serializes an object to the ASN.1 encoded buffer + * @param obj The object to serialize + */ + static serialize(obj: unknown): ArrayBuffer; + /** + * Serialize an object to the asn1js object + * @param obj The object to serialize + */ + static toASN(obj: unknown): asn1js.AsnType; + private static toAsnItem; +} diff --git a/gun-server/node_modules/@peculiar/asn1-schema/build/types/storage.d.ts b/gun-server/node_modules/@peculiar/asn1-schema/build/types/storage.d.ts new file mode 100644 index 0000000..4be1aa4 --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/build/types/storage.d.ts @@ -0,0 +1,2 @@ +import { AsnSchemaStorage } from "./schema"; +export declare const schemaStorage: AsnSchemaStorage; diff --git a/gun-server/node_modules/@peculiar/asn1-schema/build/types/types.d.ts b/gun-server/node_modules/@peculiar/asn1-schema/build/types/types.d.ts new file mode 100644 index 0000000..3196fae --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/build/types/types.d.ts @@ -0,0 +1,35 @@ +/** + * ASN1 type + */ +import * as asn1js from "asn1js"; +export interface IEmptyConstructor { + new (): T; +} +/** + * Allows to convert ASN.1 object to JS value and back + */ +export interface IAsnConverter { + /** + * Returns JS value from ASN.1 object + * @param value ASN.1 object from asn1js module + */ + fromASN(value: AsnType): T; + /** + * Returns ASN.1 object from JS value + * @param value JS value + */ + toASN(value: T): AsnType; +} +export type IntegerConverterType = string | number; +export type AnyConverterType = ArrayBuffer | null; +/** + * Allows an object to control its own ASN.1 serialization and deserialization + */ +export interface IAsnConvertible { + fromASN(asn: T): this; + toASN(): T; + toSchema(name: string): asn1js.BaseBlock; +} +export interface IAsnConvertibleConstructor { + new (): IAsnConvertible; +} diff --git a/gun-server/node_modules/@peculiar/asn1-schema/build/types/types/bit_string.d.ts b/gun-server/node_modules/@peculiar/asn1-schema/build/types/types/bit_string.d.ts new file mode 100644 index 0000000..a005fe6 --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/build/types/types/bit_string.d.ts @@ -0,0 +1,15 @@ +import * as asn1js from "asn1js"; +import { BufferSource } from "pvtsutils"; +import { IAsnConvertible } from "../types"; +export declare class BitString implements IAsnConvertible { + unusedBits: number; + value: ArrayBuffer; + constructor(); + constructor(value: T); + constructor(value: BufferSource, unusedBits?: number); + fromASN(asn: asn1js.BitString): this; + toASN(): asn1js.BitString; + toSchema(name: string): asn1js.BitString; + toNumber(): T; + fromNumber(value: T): void; +} diff --git a/gun-server/node_modules/@peculiar/asn1-schema/build/types/types/index.d.ts b/gun-server/node_modules/@peculiar/asn1-schema/build/types/types/index.d.ts new file mode 100644 index 0000000..28ceb71 --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/build/types/types/index.d.ts @@ -0,0 +1,2 @@ +export * from "./bit_string"; +export * from "./octet_string"; diff --git a/gun-server/node_modules/@peculiar/asn1-schema/build/types/types/octet_string.d.ts b/gun-server/node_modules/@peculiar/asn1-schema/build/types/types/octet_string.d.ts new file mode 100644 index 0000000..a419697 --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/build/types/types/octet_string.d.ts @@ -0,0 +1,15 @@ +import * as asn1js from "asn1js"; +import { BufferSource } from "pvtsutils"; +import { IAsnConvertible } from "../types"; +export declare class OctetString implements IAsnConvertible, ArrayBufferView { + buffer: ArrayBuffer; + get byteLength(): number; + get byteOffset(): number; + constructor(); + constructor(byteLength: number); + constructor(bytes: number[]); + constructor(bytes: BufferSource); + fromASN(asn: asn1js.OctetString): this; + toASN(): asn1js.OctetString; + toSchema(name: string): asn1js.OctetString; +} diff --git a/gun-server/node_modules/@peculiar/asn1-schema/package.json b/gun-server/node_modules/@peculiar/asn1-schema/package.json new file mode 100644 index 0000000..3da394c --- /dev/null +++ b/gun-server/node_modules/@peculiar/asn1-schema/package.json @@ -0,0 +1,56 @@ +{ + "name": "@peculiar/asn1-schema", + "version": "2.3.13", + "description": "Decorators for ASN.1 schemas building", + "files": [ + "build/**/*.{js,d.ts}", + "LICENSE", + "README.md" + ], + "bugs": { + "url": "https://github.com/PeculiarVentures/asn1-schema/issues" + }, + "homepage": "https://github.com/PeculiarVentures/asn1-schema/tree/master/packages/schema#readme", + "keywords": [ + "asn", + "serialize", + "parse", + "convert", + "decorator" + ], + "license": "MIT", + "author": "PeculiarVentures, LLC", + "main": "build/cjs/index.js", + "module": "build/es2015/index.js", + "types": "build/types/index.d.ts", + "publishConfig": { + "access": "public" + }, + "scripts": { + "test": "mocha", + "clear": "rimraf build", + "build": "npm run build:module && npm run build:types", + "build:module": "npm run build:cjs && npm run build:es2015", + "build:cjs": "tsc -p tsconfig.compile.json --removeComments --module commonjs --outDir build/cjs", + "build:es2015": "tsc -p tsconfig.compile.json --removeComments --module ES2015 --outDir build/es2015", + "prebuild:types": "rimraf build/types", + "build:types": "tsc -p tsconfig.compile.json --outDir build/types --declaration --emitDeclarationOnly", + "rebuild": "npm run clear && npm run build" + }, + "dependencies": { + "asn1js": "^3.0.5", + "pvtsutils": "^1.3.5", + "tslib": "^2.6.2" + }, + "contributors": [ + { + "email": "rmh@unmitigatedrisk.com", + "name": "Ryan Hurst" + }, + { + "email": "microshine@mail.ru", + "name": "Miroshin Stepan" + } + ], + "gitHead": "c0a11836bb6ffcc71607099c8de936b6ab86d164" +} diff --git a/gun-server/node_modules/@peculiar/json-schema/LICENSE b/gun-server/node_modules/@peculiar/json-schema/LICENSE new file mode 100644 index 0000000..ab60297 --- /dev/null +++ b/gun-server/node_modules/@peculiar/json-schema/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/gun-server/node_modules/@peculiar/json-schema/README.md b/gun-server/node_modules/@peculiar/json-schema/README.md new file mode 100644 index 0000000..67ad007 --- /dev/null +++ b/gun-server/node_modules/@peculiar/json-schema/README.md @@ -0,0 +1,158 @@ +# JSON-SCHEMA + +[![License](https://img.shields.io/badge/license-MIT-green.svg?style=flat)](https://raw.githubusercontent.com/PeculiarVentures/json-schema/master/LICENSE.md) +[![CircleCI](https://circleci.com/gh/PeculiarVentures/json-schema.svg?style=svg)](https://circleci.com/gh/PeculiarVentures/json-schema) +[![Coverage Status](https://coveralls.io/repos/github/PeculiarVentures/json-schema/badge.svg?branch=master&t=ddJivl)](https://coveralls.io/github/PeculiarVentures/json-schema?branch=master) +[![npm version](https://badge.fury.io/js/%40peculiar%2Fjson-schema.svg)](https://badge.fury.io/js/%40peculiar%2Fjson-schema) + +[![NPM](https://nodei.co/npm/@peculiar/json-schema.png)](https://nodei.co/npm/@peculiar/json-schema/) + +This package uses ES2015 [decorators](https://medium.com/google-developers/exploring-es7-decorators-76ecb65fb841) to simplify JSON [schema creation and use](https://json-schema.org/understanding-json-schema/index.html). + + +## Introduction + +JSON (JavaScript Object Notation) is a lightweight data-interchange format that was designed to be easy for humans to read and write but in practice, it is [minefield](http://seriot.ch/parsing_json.html) when it machines need to parse it. + +While the use of schemas can help with this problem their use can be complicated. When using `json-schema` this is addressed by using decorators to make both serialization and parsing of XML possible via a simple class that handles the schemas for you. + +This is important because validating input data before its use is important to do because all input data is evil. Using a schema helps you handle this data [safely](https://www.whitehatsec.com/blog/handling-untrusted-json-safely/). + + +## Installation + +Installation is handled via `npm`: + +``` +$ npm install @peculiar/json-schema +``` + +## Examples +### Node.js + +Creating a schema: +```js +import { JsonParser, JsonSerializer, JsonProp, JsonPropTypes, IJsonConverter } from "@peculiar/json-schema"; + +// custom data converter +const JsonBase64UrlConverter: IJsonConverter = { + fromJSON: (value: string) => base64UrlToBuffer(value), + toJSON: (value: Uint8Array) => bufferToBase64Url(value), +}; + +class EcPublicKey { + @JsonProp({ name: "kty" }) + keyType = "EC"; + + @JsonProp({ name: "crv" }) + namedCurve = ""; + + @JsonProp({ converter: JsonBase64UrlConverter }) + x = new Uint8Array(0); + + @JsonProp({ converter: JsonBase64UrlConverter }) + y = new Uint8Array(0); + + @JsonProp({ name: "ext", type: JsonPropTypes.Boolean, optional: true }) + extractable = false; + + @JsonProp({ name: "key_ops", type: JsonPropTypes.String, repeated: true, optional: true }) + usages: string[] = []; +} + +const json = `{ + "kty": "EC", + "crv": "P-256", + "x": "zCQ5BPHPCLZYgdpo1n-x_90P2Ij52d53YVwTh3ZdiMo", + "y": "pDfQTUx0-OiZc5ZuKMcA7v2Q7ZPKsQwzB58bft0JTko", + "ext": true +}`; + +const ecPubKey = JsonParser.parse(json, { targetSchema: EcPublicKey }); +console.log(ecPubKey); + +ecPubKey.usages.push("verify"); + +const jsonText = JsonSerializer.serialize(ecPubKey, undefined, undefined, 2); +console.log(jsonText); + +// Output +// +// EcPublicKey {keyType: "EC", namedCurve: "P-256", x: Uint8Array(32), y: Uint8Array(32), extractable: true, …} +// +// { +// "kty": "EC", +// "crv": "P-256", +// "x": "zCQ5BPHPCLZYgdpo1n+x/90P2Ij52d53YVwTh3ZdiMo=", +// "y": "pDfQTUx0+OiZc5ZuKMcA7v2Q7ZPKsQwzB58bft0JTko=", +// "ext": true, +// "key_ops": [ +// "verify" +// ] +// } +``` + +Extending a Schema: +```js +class BaseObject { + @JsonProp({ name: "i" }) + public id = 0; +} + +class Word extends BaseObject { + @JsonProp({ name: "t" }) + public text = ""; +} + +class Person extends BaseObject { + @JsonProp({ name: "n" }) + public name = 0; + @JsonProp({ name: "w", repeated: true, type: Word }) + public words = []; +} + +const json = `{ + "i":1, + "n":"Bob", + "w":[ + {"i":2,"t":"hello"}, + {"i":3,"t":"world"} + ] +}`; + +const person = JsonParser.parse(json, { targetSchema: Person }); +console.log(person); + +const word = new Word(); +word.id = 4; +word.text = "!!!"; + +const jsonText = JsonSerializer.serialize(person, undefined, undefined, 2); +console.log(jsonText); + +// Output +// +// Person {id: 1, name: "Bob", words: [Word {id: 2, text: "hello"}, Word {id: 3, text: "world"}]} +// { +// "i": 1, +// "n": "Bob", +// "w": [ +// { +// "i": 2, +// "t": "hello" +// }, +// { +// "i": 3, +// "t": "world" +// }, +// { +// "i": 4, +// "t": "!!!" +// } +// ] +// } +``` + +## API + +Use [index.d.ts](index.d.ts) file diff --git a/gun-server/node_modules/@peculiar/json-schema/build/index.es.js b/gun-server/node_modules/@peculiar/json-schema/build/index.es.js new file mode 100644 index 0000000..5177313 --- /dev/null +++ b/gun-server/node_modules/@peculiar/json-schema/build/index.es.js @@ -0,0 +1,484 @@ +/** + * Copyright (c) 2020, Peculiar Ventures, All rights reserved. + */ + +class JsonError extends Error { + constructor(message, innerError) { + super(innerError + ? `${message}. See the inner exception for more details.` + : message); + this.message = message; + this.innerError = innerError; + } +} + +class TransformError extends JsonError { + constructor(schema, message, innerError) { + super(message, innerError); + this.schema = schema; + } +} + +class ParserError extends TransformError { + constructor(schema, message, innerError) { + super(schema, `JSON doesn't match to '${schema.target.name}' schema. ${message}`, innerError); + } +} + +class ValidationError extends JsonError { +} + +class SerializerError extends JsonError { + constructor(schemaName, message, innerError) { + super(`Cannot serialize by '${schemaName}' schema. ${message}`, innerError); + this.schemaName = schemaName; + } +} + +class KeyError extends ParserError { + constructor(schema, keys, errors = {}) { + super(schema, "Some keys doesn't match to schema"); + this.keys = keys; + this.errors = errors; + } +} + +var JsonPropTypes; +(function (JsonPropTypes) { + JsonPropTypes[JsonPropTypes["Any"] = 0] = "Any"; + JsonPropTypes[JsonPropTypes["Boolean"] = 1] = "Boolean"; + JsonPropTypes[JsonPropTypes["Number"] = 2] = "Number"; + JsonPropTypes[JsonPropTypes["String"] = 3] = "String"; +})(JsonPropTypes || (JsonPropTypes = {})); + +function checkType(value, type) { + switch (type) { + case JsonPropTypes.Boolean: + return typeof value === "boolean"; + case JsonPropTypes.Number: + return typeof value === "number"; + case JsonPropTypes.String: + return typeof value === "string"; + } + return true; +} +function throwIfTypeIsWrong(value, type) { + if (!checkType(value, type)) { + throw new TypeError(`Value must be ${JsonPropTypes[type]}`); + } +} +function isConvertible(target) { + if (target && target.prototype) { + if (target.prototype.toJSON && target.prototype.fromJSON) { + return true; + } + else { + return isConvertible(target.prototype); + } + } + else { + return !!(target && target.toJSON && target.fromJSON); + } +} + +class JsonSchemaStorage { + constructor() { + this.items = new Map(); + } + has(target) { + return this.items.has(target) || !!this.findParentSchema(target); + } + get(target) { + const schema = this.items.get(target) || this.findParentSchema(target); + if (!schema) { + throw new Error("Cannot get schema for current target"); + } + return schema; + } + create(target) { + const schema = { names: {} }; + const parentSchema = this.findParentSchema(target); + if (parentSchema) { + Object.assign(schema, parentSchema); + schema.names = {}; + for (const name in parentSchema.names) { + schema.names[name] = Object.assign({}, parentSchema.names[name]); + } + } + schema.target = target; + return schema; + } + set(target, schema) { + this.items.set(target, schema); + return this; + } + findParentSchema(target) { + const parent = target.__proto__; + if (parent) { + const schema = this.items.get(parent); + return schema || this.findParentSchema(parent); + } + return null; + } +} + +const DEFAULT_SCHEMA = "default"; +const schemaStorage = new JsonSchemaStorage(); + +class PatternValidation { + constructor(pattern) { + this.pattern = new RegExp(pattern); + } + validate(value) { + const pattern = new RegExp(this.pattern.source, this.pattern.flags); + if (typeof value !== "string") { + throw new ValidationError("Incoming value must be string"); + } + if (!pattern.exec(value)) { + throw new ValidationError(`Value doesn't match to pattern '${pattern.toString()}'`); + } + } +} + +class InclusiveValidation { + constructor(min = Number.MIN_VALUE, max = Number.MAX_VALUE) { + this.min = min; + this.max = max; + } + validate(value) { + throwIfTypeIsWrong(value, JsonPropTypes.Number); + if (!(this.min <= value && value <= this.max)) { + const min = this.min === Number.MIN_VALUE ? "MIN" : this.min; + const max = this.max === Number.MAX_VALUE ? "MAX" : this.max; + throw new ValidationError(`Value doesn't match to diapason [${min},${max}]`); + } + } +} + +class ExclusiveValidation { + constructor(min = Number.MIN_VALUE, max = Number.MAX_VALUE) { + this.min = min; + this.max = max; + } + validate(value) { + throwIfTypeIsWrong(value, JsonPropTypes.Number); + if (!(this.min < value && value < this.max)) { + const min = this.min === Number.MIN_VALUE ? "MIN" : this.min; + const max = this.max === Number.MAX_VALUE ? "MAX" : this.max; + throw new ValidationError(`Value doesn't match to diapason (${min},${max})`); + } + } +} + +class LengthValidation { + constructor(length, minLength, maxLength) { + this.length = length; + this.minLength = minLength; + this.maxLength = maxLength; + } + validate(value) { + if (this.length !== undefined) { + if (value.length !== this.length) { + throw new ValidationError(`Value length must be exactly ${this.length}.`); + } + return; + } + if (this.minLength !== undefined) { + if (value.length < this.minLength) { + throw new ValidationError(`Value length must be more than ${this.minLength}.`); + } + } + if (this.maxLength !== undefined) { + if (value.length > this.maxLength) { + throw new ValidationError(`Value length must be less than ${this.maxLength}.`); + } + } + } +} + +class EnumerationValidation { + constructor(enumeration) { + this.enumeration = enumeration; + } + validate(value) { + throwIfTypeIsWrong(value, JsonPropTypes.String); + if (!this.enumeration.includes(value)) { + throw new ValidationError(`Value must be one of ${this.enumeration.map((v) => `'${v}'`).join(", ")}`); + } + } +} + +class JsonTransform { + static checkValues(data, schemaItem) { + const values = Array.isArray(data) ? data : [data]; + for (const value of values) { + for (const validation of schemaItem.validations) { + if (validation instanceof LengthValidation && schemaItem.repeated) { + validation.validate(data); + } + else { + validation.validate(value); + } + } + } + } + static checkTypes(value, schemaItem) { + if (schemaItem.repeated && !Array.isArray(value)) { + throw new TypeError("Value must be Array"); + } + if (typeof schemaItem.type === "number") { + const values = Array.isArray(value) ? value : [value]; + for (const v of values) { + throwIfTypeIsWrong(v, schemaItem.type); + } + } + } + static getSchemaByName(schema, name = DEFAULT_SCHEMA) { + return { ...schema.names[DEFAULT_SCHEMA], ...schema.names[name] }; + } +} + +class JsonSerializer extends JsonTransform { + static serialize(obj, options, replacer, space) { + const json = this.toJSON(obj, options); + return JSON.stringify(json, replacer, space); + } + static toJSON(obj, options = {}) { + let res; + let targetSchema = options.targetSchema; + const schemaName = options.schemaName || DEFAULT_SCHEMA; + if (isConvertible(obj)) { + return obj.toJSON(); + } + if (Array.isArray(obj)) { + res = []; + for (const item of obj) { + res.push(this.toJSON(item, options)); + } + } + else if (typeof obj === "object") { + if (targetSchema && !schemaStorage.has(targetSchema)) { + throw new JsonError("Cannot get schema for `targetSchema` param"); + } + targetSchema = (targetSchema || obj.constructor); + if (schemaStorage.has(targetSchema)) { + const schema = schemaStorage.get(targetSchema); + res = {}; + const namedSchema = this.getSchemaByName(schema, schemaName); + for (const key in namedSchema) { + try { + const item = namedSchema[key]; + const objItem = obj[key]; + let value; + if ((item.optional && objItem === undefined) + || (item.defaultValue !== undefined && objItem === item.defaultValue)) { + continue; + } + if (!item.optional && objItem === undefined) { + throw new SerializerError(targetSchema.name, `Property '${key}' is required.`); + } + if (typeof item.type === "number") { + if (item.converter) { + if (item.repeated) { + value = objItem.map((el) => item.converter.toJSON(el, obj)); + } + else { + value = item.converter.toJSON(objItem, obj); + } + } + else { + value = objItem; + } + } + else { + if (item.repeated) { + value = objItem.map((el) => this.toJSON(el, { schemaName })); + } + else { + value = this.toJSON(objItem, { schemaName }); + } + } + this.checkTypes(value, item); + this.checkValues(value, item); + res[item.name || key] = value; + } + catch (e) { + if (e instanceof SerializerError) { + throw e; + } + else { + throw new SerializerError(schema.target.name, `Property '${key}' is wrong. ${e.message}`, e); + } + } + } + } + else { + res = {}; + for (const key in obj) { + res[key] = this.toJSON(obj[key], { schemaName }); + } + } + } + else { + res = obj; + } + return res; + } +} + +class JsonParser extends JsonTransform { + static parse(data, options) { + const obj = JSON.parse(data); + return this.fromJSON(obj, options); + } + static fromJSON(target, options) { + const targetSchema = options.targetSchema; + const schemaName = options.schemaName || DEFAULT_SCHEMA; + const obj = new targetSchema(); + if (isConvertible(obj)) { + return obj.fromJSON(target); + } + const schema = schemaStorage.get(targetSchema); + const namedSchema = this.getSchemaByName(schema, schemaName); + const keyErrors = {}; + if (options.strictProperty && !Array.isArray(target)) { + JsonParser.checkStrictProperty(target, namedSchema, schema); + } + for (const key in namedSchema) { + try { + const item = namedSchema[key]; + const name = item.name || key; + const value = target[name]; + if (value === undefined && (item.optional || item.defaultValue !== undefined)) { + continue; + } + if (!item.optional && value === undefined) { + throw new ParserError(schema, `Property '${name}' is required.`); + } + this.checkTypes(value, item); + this.checkValues(value, item); + if (typeof (item.type) === "number") { + if (item.converter) { + if (item.repeated) { + obj[key] = value.map((el) => item.converter.fromJSON(el, obj)); + } + else { + obj[key] = item.converter.fromJSON(value, obj); + } + } + else { + obj[key] = value; + } + } + else { + const newOptions = { + ...options, + targetSchema: item.type, + schemaName, + }; + if (item.repeated) { + obj[key] = value.map((el) => this.fromJSON(el, newOptions)); + } + else { + obj[key] = this.fromJSON(value, newOptions); + } + } + } + catch (e) { + if (!(e instanceof ParserError)) { + e = new ParserError(schema, `Property '${key}' is wrong. ${e.message}`, e); + } + if (options.strictAllKeys) { + keyErrors[key] = e; + } + else { + throw e; + } + } + } + const keys = Object.keys(keyErrors); + if (keys.length) { + throw new KeyError(schema, keys, keyErrors); + } + return obj; + } + static checkStrictProperty(target, namedSchema, schema) { + const jsonProps = Object.keys(target); + const schemaProps = Object.keys(namedSchema); + const keys = []; + for (const key of jsonProps) { + if (schemaProps.indexOf(key) === -1) { + keys.push(key); + } + } + if (keys.length) { + throw new KeyError(schema, keys); + } + } +} + +function getValidations(item) { + const validations = []; + if (item.pattern) { + validations.push(new PatternValidation(item.pattern)); + } + if (item.type === JsonPropTypes.Number || item.type === JsonPropTypes.Any) { + if (item.minInclusive !== undefined || item.maxInclusive !== undefined) { + validations.push(new InclusiveValidation(item.minInclusive, item.maxInclusive)); + } + if (item.minExclusive !== undefined || item.maxExclusive !== undefined) { + validations.push(new ExclusiveValidation(item.minExclusive, item.maxExclusive)); + } + if (item.enumeration !== undefined) { + validations.push(new EnumerationValidation(item.enumeration)); + } + } + if (item.type === JsonPropTypes.String || item.repeated || item.type === JsonPropTypes.Any) { + if (item.length !== undefined || item.minLength !== undefined || item.maxLength !== undefined) { + validations.push(new LengthValidation(item.length, item.minLength, item.maxLength)); + } + } + return validations; +} +const JsonProp = (options = {}) => (target, propertyKey) => { + const errorMessage = `Cannot set type for ${propertyKey} property of ${target.constructor.name} schema`; + let schema; + if (!schemaStorage.has(target.constructor)) { + schema = schemaStorage.create(target.constructor); + schemaStorage.set(target.constructor, schema); + } + else { + schema = schemaStorage.get(target.constructor); + if (schema.target !== target.constructor) { + schema = schemaStorage.create(target.constructor); + schemaStorage.set(target.constructor, schema); + } + } + const defaultSchema = { + type: JsonPropTypes.Any, + validations: [], + }; + const copyOptions = Object.assign(defaultSchema, options); + copyOptions.validations = getValidations(copyOptions); + if (typeof copyOptions.type !== "number") { + if (!schemaStorage.has(copyOptions.type) && !isConvertible(copyOptions.type)) { + throw new Error(`${errorMessage}. Assigning type doesn't have schema.`); + } + } + let schemaNames; + if (Array.isArray(options.schema)) { + schemaNames = options.schema; + } + else { + schemaNames = [options.schema || DEFAULT_SCHEMA]; + } + for (const schemaName of schemaNames) { + if (!schema.names[schemaName]) { + schema.names[schemaName] = {}; + } + const namedSchema = schema.names[schemaName]; + namedSchema[propertyKey] = copyOptions; + } +}; + +export { JsonError, JsonParser, JsonProp, JsonPropTypes, JsonSerializer, KeyError, ParserError, SerializerError, TransformError, ValidationError }; diff --git a/gun-server/node_modules/@peculiar/json-schema/build/index.js b/gun-server/node_modules/@peculiar/json-schema/build/index.js new file mode 100644 index 0000000..69e64dc --- /dev/null +++ b/gun-server/node_modules/@peculiar/json-schema/build/index.js @@ -0,0 +1,495 @@ +/** + * Copyright (c) 2020, Peculiar Ventures, All rights reserved. + */ + +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +class JsonError extends Error { + constructor(message, innerError) { + super(innerError + ? `${message}. See the inner exception for more details.` + : message); + this.message = message; + this.innerError = innerError; + } +} + +class TransformError extends JsonError { + constructor(schema, message, innerError) { + super(message, innerError); + this.schema = schema; + } +} + +class ParserError extends TransformError { + constructor(schema, message, innerError) { + super(schema, `JSON doesn't match to '${schema.target.name}' schema. ${message}`, innerError); + } +} + +class ValidationError extends JsonError { +} + +class SerializerError extends JsonError { + constructor(schemaName, message, innerError) { + super(`Cannot serialize by '${schemaName}' schema. ${message}`, innerError); + this.schemaName = schemaName; + } +} + +class KeyError extends ParserError { + constructor(schema, keys, errors = {}) { + super(schema, "Some keys doesn't match to schema"); + this.keys = keys; + this.errors = errors; + } +} + +(function (JsonPropTypes) { + JsonPropTypes[JsonPropTypes["Any"] = 0] = "Any"; + JsonPropTypes[JsonPropTypes["Boolean"] = 1] = "Boolean"; + JsonPropTypes[JsonPropTypes["Number"] = 2] = "Number"; + JsonPropTypes[JsonPropTypes["String"] = 3] = "String"; +})(exports.JsonPropTypes || (exports.JsonPropTypes = {})); + +function checkType(value, type) { + switch (type) { + case exports.JsonPropTypes.Boolean: + return typeof value === "boolean"; + case exports.JsonPropTypes.Number: + return typeof value === "number"; + case exports.JsonPropTypes.String: + return typeof value === "string"; + } + return true; +} +function throwIfTypeIsWrong(value, type) { + if (!checkType(value, type)) { + throw new TypeError(`Value must be ${exports.JsonPropTypes[type]}`); + } +} +function isConvertible(target) { + if (target && target.prototype) { + if (target.prototype.toJSON && target.prototype.fromJSON) { + return true; + } + else { + return isConvertible(target.prototype); + } + } + else { + return !!(target && target.toJSON && target.fromJSON); + } +} + +class JsonSchemaStorage { + constructor() { + this.items = new Map(); + } + has(target) { + return this.items.has(target) || !!this.findParentSchema(target); + } + get(target) { + const schema = this.items.get(target) || this.findParentSchema(target); + if (!schema) { + throw new Error("Cannot get schema for current target"); + } + return schema; + } + create(target) { + const schema = { names: {} }; + const parentSchema = this.findParentSchema(target); + if (parentSchema) { + Object.assign(schema, parentSchema); + schema.names = {}; + for (const name in parentSchema.names) { + schema.names[name] = Object.assign({}, parentSchema.names[name]); + } + } + schema.target = target; + return schema; + } + set(target, schema) { + this.items.set(target, schema); + return this; + } + findParentSchema(target) { + const parent = target.__proto__; + if (parent) { + const schema = this.items.get(parent); + return schema || this.findParentSchema(parent); + } + return null; + } +} + +const DEFAULT_SCHEMA = "default"; +const schemaStorage = new JsonSchemaStorage(); + +class PatternValidation { + constructor(pattern) { + this.pattern = new RegExp(pattern); + } + validate(value) { + const pattern = new RegExp(this.pattern.source, this.pattern.flags); + if (typeof value !== "string") { + throw new ValidationError("Incoming value must be string"); + } + if (!pattern.exec(value)) { + throw new ValidationError(`Value doesn't match to pattern '${pattern.toString()}'`); + } + } +} + +class InclusiveValidation { + constructor(min = Number.MIN_VALUE, max = Number.MAX_VALUE) { + this.min = min; + this.max = max; + } + validate(value) { + throwIfTypeIsWrong(value, exports.JsonPropTypes.Number); + if (!(this.min <= value && value <= this.max)) { + const min = this.min === Number.MIN_VALUE ? "MIN" : this.min; + const max = this.max === Number.MAX_VALUE ? "MAX" : this.max; + throw new ValidationError(`Value doesn't match to diapason [${min},${max}]`); + } + } +} + +class ExclusiveValidation { + constructor(min = Number.MIN_VALUE, max = Number.MAX_VALUE) { + this.min = min; + this.max = max; + } + validate(value) { + throwIfTypeIsWrong(value, exports.JsonPropTypes.Number); + if (!(this.min < value && value < this.max)) { + const min = this.min === Number.MIN_VALUE ? "MIN" : this.min; + const max = this.max === Number.MAX_VALUE ? "MAX" : this.max; + throw new ValidationError(`Value doesn't match to diapason (${min},${max})`); + } + } +} + +class LengthValidation { + constructor(length, minLength, maxLength) { + this.length = length; + this.minLength = minLength; + this.maxLength = maxLength; + } + validate(value) { + if (this.length !== undefined) { + if (value.length !== this.length) { + throw new ValidationError(`Value length must be exactly ${this.length}.`); + } + return; + } + if (this.minLength !== undefined) { + if (value.length < this.minLength) { + throw new ValidationError(`Value length must be more than ${this.minLength}.`); + } + } + if (this.maxLength !== undefined) { + if (value.length > this.maxLength) { + throw new ValidationError(`Value length must be less than ${this.maxLength}.`); + } + } + } +} + +class EnumerationValidation { + constructor(enumeration) { + this.enumeration = enumeration; + } + validate(value) { + throwIfTypeIsWrong(value, exports.JsonPropTypes.String); + if (!this.enumeration.includes(value)) { + throw new ValidationError(`Value must be one of ${this.enumeration.map((v) => `'${v}'`).join(", ")}`); + } + } +} + +class JsonTransform { + static checkValues(data, schemaItem) { + const values = Array.isArray(data) ? data : [data]; + for (const value of values) { + for (const validation of schemaItem.validations) { + if (validation instanceof LengthValidation && schemaItem.repeated) { + validation.validate(data); + } + else { + validation.validate(value); + } + } + } + } + static checkTypes(value, schemaItem) { + if (schemaItem.repeated && !Array.isArray(value)) { + throw new TypeError("Value must be Array"); + } + if (typeof schemaItem.type === "number") { + const values = Array.isArray(value) ? value : [value]; + for (const v of values) { + throwIfTypeIsWrong(v, schemaItem.type); + } + } + } + static getSchemaByName(schema, name = DEFAULT_SCHEMA) { + return { ...schema.names[DEFAULT_SCHEMA], ...schema.names[name] }; + } +} + +class JsonSerializer extends JsonTransform { + static serialize(obj, options, replacer, space) { + const json = this.toJSON(obj, options); + return JSON.stringify(json, replacer, space); + } + static toJSON(obj, options = {}) { + let res; + let targetSchema = options.targetSchema; + const schemaName = options.schemaName || DEFAULT_SCHEMA; + if (isConvertible(obj)) { + return obj.toJSON(); + } + if (Array.isArray(obj)) { + res = []; + for (const item of obj) { + res.push(this.toJSON(item, options)); + } + } + else if (typeof obj === "object") { + if (targetSchema && !schemaStorage.has(targetSchema)) { + throw new JsonError("Cannot get schema for `targetSchema` param"); + } + targetSchema = (targetSchema || obj.constructor); + if (schemaStorage.has(targetSchema)) { + const schema = schemaStorage.get(targetSchema); + res = {}; + const namedSchema = this.getSchemaByName(schema, schemaName); + for (const key in namedSchema) { + try { + const item = namedSchema[key]; + const objItem = obj[key]; + let value; + if ((item.optional && objItem === undefined) + || (item.defaultValue !== undefined && objItem === item.defaultValue)) { + continue; + } + if (!item.optional && objItem === undefined) { + throw new SerializerError(targetSchema.name, `Property '${key}' is required.`); + } + if (typeof item.type === "number") { + if (item.converter) { + if (item.repeated) { + value = objItem.map((el) => item.converter.toJSON(el, obj)); + } + else { + value = item.converter.toJSON(objItem, obj); + } + } + else { + value = objItem; + } + } + else { + if (item.repeated) { + value = objItem.map((el) => this.toJSON(el, { schemaName })); + } + else { + value = this.toJSON(objItem, { schemaName }); + } + } + this.checkTypes(value, item); + this.checkValues(value, item); + res[item.name || key] = value; + } + catch (e) { + if (e instanceof SerializerError) { + throw e; + } + else { + throw new SerializerError(schema.target.name, `Property '${key}' is wrong. ${e.message}`, e); + } + } + } + } + else { + res = {}; + for (const key in obj) { + res[key] = this.toJSON(obj[key], { schemaName }); + } + } + } + else { + res = obj; + } + return res; + } +} + +class JsonParser extends JsonTransform { + static parse(data, options) { + const obj = JSON.parse(data); + return this.fromJSON(obj, options); + } + static fromJSON(target, options) { + const targetSchema = options.targetSchema; + const schemaName = options.schemaName || DEFAULT_SCHEMA; + const obj = new targetSchema(); + if (isConvertible(obj)) { + return obj.fromJSON(target); + } + const schema = schemaStorage.get(targetSchema); + const namedSchema = this.getSchemaByName(schema, schemaName); + const keyErrors = {}; + if (options.strictProperty && !Array.isArray(target)) { + JsonParser.checkStrictProperty(target, namedSchema, schema); + } + for (const key in namedSchema) { + try { + const item = namedSchema[key]; + const name = item.name || key; + const value = target[name]; + if (value === undefined && (item.optional || item.defaultValue !== undefined)) { + continue; + } + if (!item.optional && value === undefined) { + throw new ParserError(schema, `Property '${name}' is required.`); + } + this.checkTypes(value, item); + this.checkValues(value, item); + if (typeof (item.type) === "number") { + if (item.converter) { + if (item.repeated) { + obj[key] = value.map((el) => item.converter.fromJSON(el, obj)); + } + else { + obj[key] = item.converter.fromJSON(value, obj); + } + } + else { + obj[key] = value; + } + } + else { + const newOptions = { + ...options, + targetSchema: item.type, + schemaName, + }; + if (item.repeated) { + obj[key] = value.map((el) => this.fromJSON(el, newOptions)); + } + else { + obj[key] = this.fromJSON(value, newOptions); + } + } + } + catch (e) { + if (!(e instanceof ParserError)) { + e = new ParserError(schema, `Property '${key}' is wrong. ${e.message}`, e); + } + if (options.strictAllKeys) { + keyErrors[key] = e; + } + else { + throw e; + } + } + } + const keys = Object.keys(keyErrors); + if (keys.length) { + throw new KeyError(schema, keys, keyErrors); + } + return obj; + } + static checkStrictProperty(target, namedSchema, schema) { + const jsonProps = Object.keys(target); + const schemaProps = Object.keys(namedSchema); + const keys = []; + for (const key of jsonProps) { + if (schemaProps.indexOf(key) === -1) { + keys.push(key); + } + } + if (keys.length) { + throw new KeyError(schema, keys); + } + } +} + +function getValidations(item) { + const validations = []; + if (item.pattern) { + validations.push(new PatternValidation(item.pattern)); + } + if (item.type === exports.JsonPropTypes.Number || item.type === exports.JsonPropTypes.Any) { + if (item.minInclusive !== undefined || item.maxInclusive !== undefined) { + validations.push(new InclusiveValidation(item.minInclusive, item.maxInclusive)); + } + if (item.minExclusive !== undefined || item.maxExclusive !== undefined) { + validations.push(new ExclusiveValidation(item.minExclusive, item.maxExclusive)); + } + if (item.enumeration !== undefined) { + validations.push(new EnumerationValidation(item.enumeration)); + } + } + if (item.type === exports.JsonPropTypes.String || item.repeated || item.type === exports.JsonPropTypes.Any) { + if (item.length !== undefined || item.minLength !== undefined || item.maxLength !== undefined) { + validations.push(new LengthValidation(item.length, item.minLength, item.maxLength)); + } + } + return validations; +} +const JsonProp = (options = {}) => (target, propertyKey) => { + const errorMessage = `Cannot set type for ${propertyKey} property of ${target.constructor.name} schema`; + let schema; + if (!schemaStorage.has(target.constructor)) { + schema = schemaStorage.create(target.constructor); + schemaStorage.set(target.constructor, schema); + } + else { + schema = schemaStorage.get(target.constructor); + if (schema.target !== target.constructor) { + schema = schemaStorage.create(target.constructor); + schemaStorage.set(target.constructor, schema); + } + } + const defaultSchema = { + type: exports.JsonPropTypes.Any, + validations: [], + }; + const copyOptions = Object.assign(defaultSchema, options); + copyOptions.validations = getValidations(copyOptions); + if (typeof copyOptions.type !== "number") { + if (!schemaStorage.has(copyOptions.type) && !isConvertible(copyOptions.type)) { + throw new Error(`${errorMessage}. Assigning type doesn't have schema.`); + } + } + let schemaNames; + if (Array.isArray(options.schema)) { + schemaNames = options.schema; + } + else { + schemaNames = [options.schema || DEFAULT_SCHEMA]; + } + for (const schemaName of schemaNames) { + if (!schema.names[schemaName]) { + schema.names[schemaName] = {}; + } + const namedSchema = schema.names[schemaName]; + namedSchema[propertyKey] = copyOptions; + } +}; + +exports.JsonError = JsonError; +exports.JsonParser = JsonParser; +exports.JsonProp = JsonProp; +exports.JsonSerializer = JsonSerializer; +exports.KeyError = KeyError; +exports.ParserError = ParserError; +exports.SerializerError = SerializerError; +exports.TransformError = TransformError; +exports.ValidationError = ValidationError; diff --git a/gun-server/node_modules/@peculiar/json-schema/build/types/decorators.d.ts b/gun-server/node_modules/@peculiar/json-schema/build/types/decorators.d.ts new file mode 100644 index 0000000..12c28f9 --- /dev/null +++ b/gun-server/node_modules/@peculiar/json-schema/build/types/decorators.d.ts @@ -0,0 +1,51 @@ +import { JsonPropTypes } from "./prop_types"; +import { IEmptyConstructor, IJsonConverter } from "./types"; +export interface IJsonPropOptions { + type?: JsonPropTypes | IEmptyConstructor; + optional?: boolean; + defaultValue?: any; + converter?: IJsonConverter; + repeated?: boolean; + name?: string; + /** + * Defines name of schema + */ + schema?: string | string[]; + /** + * Defines regular expression for text + */ + pattern?: string | RegExp; + /** + * Defines a list of acceptable values + */ + enumeration?: string[]; + /** + * Specifies the exact number of characters or list items allowed. Must be equal to or greater than zero + */ + length?: number; + /** + * Specifies the minimum number of characters or list items allowed. Must be equal to or greater than zero + */ + minLength?: number; + /** + * Specifies the maximum number of characters or list items allowed. Must be equal to or greater than zero + */ + maxLength?: number; + /** + * Specifies the lower bounds for numeric values (the value must be greater than or equal to this value) + */ + minInclusive?: number; + /** + * Specifies the upper bounds for numeric values (the value must be less than or equal to this value) + */ + maxInclusive?: number; + /** + * Specifies the lower bounds for numeric values (the value must be greater than this value) + */ + minExclusive?: number; + /** + * Specifies the upper bounds for numeric values (the value must be less than this value) + */ + maxExclusive?: number; +} +export declare const JsonProp: (options?: IJsonPropOptions) => (target: object, propertyKey: string) => void; diff --git a/gun-server/node_modules/@peculiar/json-schema/build/types/errors/index.d.ts b/gun-server/node_modules/@peculiar/json-schema/build/types/errors/index.d.ts new file mode 100644 index 0000000..6889cbe --- /dev/null +++ b/gun-server/node_modules/@peculiar/json-schema/build/types/errors/index.d.ts @@ -0,0 +1,6 @@ +export * from "./json_error"; +export * from "./parser_error"; +export * from "./validation_error"; +export * from "./serializer_error"; +export * from "./transform_error"; +export * from "./key_error"; diff --git a/gun-server/node_modules/@peculiar/json-schema/build/types/errors/json_error.d.ts b/gun-server/node_modules/@peculiar/json-schema/build/types/errors/json_error.d.ts new file mode 100644 index 0000000..f04a501 --- /dev/null +++ b/gun-server/node_modules/@peculiar/json-schema/build/types/errors/json_error.d.ts @@ -0,0 +1,5 @@ +export declare class JsonError extends Error { + message: string; + innerError?: Error | undefined; + constructor(message: string, innerError?: Error | undefined); +} diff --git a/gun-server/node_modules/@peculiar/json-schema/build/types/errors/key_error.d.ts b/gun-server/node_modules/@peculiar/json-schema/build/types/errors/key_error.d.ts new file mode 100644 index 0000000..0dc5d77 --- /dev/null +++ b/gun-server/node_modules/@peculiar/json-schema/build/types/errors/key_error.d.ts @@ -0,0 +1,10 @@ +import { IJsonSchema } from "../schema"; +import { ParserError } from "./parser_error"; +export interface IKeyErrors { + [key: string]: Error; +} +export declare class KeyError extends ParserError { + keys: string[]; + errors: IKeyErrors; + constructor(schema: IJsonSchema, keys: string[], errors?: IKeyErrors); +} diff --git a/gun-server/node_modules/@peculiar/json-schema/build/types/errors/parser_error.d.ts b/gun-server/node_modules/@peculiar/json-schema/build/types/errors/parser_error.d.ts new file mode 100644 index 0000000..3a0cf50 --- /dev/null +++ b/gun-server/node_modules/@peculiar/json-schema/build/types/errors/parser_error.d.ts @@ -0,0 +1,5 @@ +import { IJsonSchema } from "../schema"; +import { TransformError } from "./transform_error"; +export declare class ParserError extends TransformError { + constructor(schema: IJsonSchema, message: string, innerError?: Error); +} diff --git a/gun-server/node_modules/@peculiar/json-schema/build/types/errors/serializer_error.d.ts b/gun-server/node_modules/@peculiar/json-schema/build/types/errors/serializer_error.d.ts new file mode 100644 index 0000000..01c3021 --- /dev/null +++ b/gun-server/node_modules/@peculiar/json-schema/build/types/errors/serializer_error.d.ts @@ -0,0 +1,5 @@ +import { JsonError } from "./json_error"; +export declare class SerializerError extends JsonError { + schemaName: string; + constructor(schemaName: string, message: string, innerError?: Error); +} diff --git a/gun-server/node_modules/@peculiar/json-schema/build/types/errors/transform_error.d.ts b/gun-server/node_modules/@peculiar/json-schema/build/types/errors/transform_error.d.ts new file mode 100644 index 0000000..d0d6442 --- /dev/null +++ b/gun-server/node_modules/@peculiar/json-schema/build/types/errors/transform_error.d.ts @@ -0,0 +1,6 @@ +import { IJsonSchema } from "../schema"; +import { JsonError } from "./json_error"; +export declare class TransformError extends JsonError { + schema: IJsonSchema; + constructor(schema: IJsonSchema, message: string, innerError?: Error); +} diff --git a/gun-server/node_modules/@peculiar/json-schema/build/types/errors/validation_error.d.ts b/gun-server/node_modules/@peculiar/json-schema/build/types/errors/validation_error.d.ts new file mode 100644 index 0000000..c69264e --- /dev/null +++ b/gun-server/node_modules/@peculiar/json-schema/build/types/errors/validation_error.d.ts @@ -0,0 +1,3 @@ +import { JsonError } from "./json_error"; +export declare class ValidationError extends JsonError { +} diff --git a/gun-server/node_modules/@peculiar/json-schema/build/types/helper.d.ts b/gun-server/node_modules/@peculiar/json-schema/build/types/helper.d.ts new file mode 100644 index 0000000..5948dbe --- /dev/null +++ b/gun-server/node_modules/@peculiar/json-schema/build/types/helper.d.ts @@ -0,0 +1,5 @@ +import { JsonPropTypes } from "./prop_types"; +import { IJsonConvertible } from "./types"; +export declare function checkType(value: any, type: JsonPropTypes): boolean; +export declare function throwIfTypeIsWrong(value: any, type: JsonPropTypes): void; +export declare function isConvertible(target: any): target is IJsonConvertible; diff --git a/gun-server/node_modules/@peculiar/json-schema/build/types/index.d.ts b/gun-server/node_modules/@peculiar/json-schema/build/types/index.d.ts new file mode 100644 index 0000000..17bfbbf --- /dev/null +++ b/gun-server/node_modules/@peculiar/json-schema/build/types/index.d.ts @@ -0,0 +1,6 @@ +export * from "./serializer"; +export * from "./parser"; +export * from "./decorators"; +export { JsonPropTypes } from "./prop_types"; +export * from "./types"; +export * from "./errors"; diff --git a/gun-server/node_modules/@peculiar/json-schema/build/types/parser.d.ts b/gun-server/node_modules/@peculiar/json-schema/build/types/parser.d.ts new file mode 100644 index 0000000..fe92f9a --- /dev/null +++ b/gun-server/node_modules/@peculiar/json-schema/build/types/parser.d.ts @@ -0,0 +1,26 @@ +import { JsonTransform } from "./transform"; +import { IEmptyConstructor } from "./types"; +export interface IJsonParserOptions { + targetSchema: IEmptyConstructor; + schemaName?: string; + /** + * Enable strict checking of properties. Throw exception if incoming JSON has odd fields + */ + strictProperty?: boolean; + /** + * Checks all properties for object and throws KeyError with list of wrong keys + */ + strictAllKeys?: boolean; +} +export declare class JsonParser extends JsonTransform { + static parse(data: string, options: IJsonParserOptions): T; + static fromJSON(target: any, options: IJsonParserOptions): T; + /** + * Checks for odd properties in target object. + * @param target Target object + * @param namedSchema Named schema with a list of properties + * @param schema + * @throws Throws ParserError exception whenever target object has odd property + */ + private static checkStrictProperty; +} diff --git a/gun-server/node_modules/@peculiar/json-schema/build/types/prop_types.d.ts b/gun-server/node_modules/@peculiar/json-schema/build/types/prop_types.d.ts new file mode 100644 index 0000000..00491b4 --- /dev/null +++ b/gun-server/node_modules/@peculiar/json-schema/build/types/prop_types.d.ts @@ -0,0 +1,6 @@ +export declare enum JsonPropTypes { + Any = 0, + Boolean = 1, + Number = 2, + String = 3 +} diff --git a/gun-server/node_modules/@peculiar/json-schema/build/types/schema.d.ts b/gun-server/node_modules/@peculiar/json-schema/build/types/schema.d.ts new file mode 100644 index 0000000..f166bd1 --- /dev/null +++ b/gun-server/node_modules/@peculiar/json-schema/build/types/schema.d.ts @@ -0,0 +1,35 @@ +import { JsonPropTypes } from "./prop_types"; +import { IEmptyConstructor, IJsonConverter, IValidation } from "./types"; +export interface IValidationEvent { + propName: string; + value: any; +} +export interface IJsonSchemaItem { + type: JsonPropTypes | IEmptyConstructor; + optional?: boolean; + defaultValue?: any; + converter?: IJsonConverter; + repeated?: boolean; + name?: string; + validations: IValidation[]; +} +export interface IJsonSchema { + target: IEmptyConstructor; + names: { + [key: string]: { + [key: string]: IJsonSchemaItem; + }; + }; +} +export declare class JsonSchemaStorage { + protected items: Map; + has(target: object): boolean; + get(target: object): IJsonSchema; + /** + * Creates new schema + * @param target Target object + */ + create(target: object): IJsonSchema; + set(target: object, schema: IJsonSchema): this; + protected findParentSchema(target: object): IJsonSchema | null; +} diff --git a/gun-server/node_modules/@peculiar/json-schema/build/types/serializer.d.ts b/gun-server/node_modules/@peculiar/json-schema/build/types/serializer.d.ts new file mode 100644 index 0000000..5358dcf --- /dev/null +++ b/gun-server/node_modules/@peculiar/json-schema/build/types/serializer.d.ts @@ -0,0 +1,10 @@ +import { JsonTransform } from "./transform"; +import { IEmptyConstructor } from "./types"; +export interface IJsonSerializerOptions { + targetSchema?: IEmptyConstructor; + schemaName?: string; +} +export declare class JsonSerializer extends JsonTransform { + static serialize(obj: any, options?: IJsonSerializerOptions, replacer?: (key: string, value: any) => any, space?: string | number): string; + static toJSON(obj: any, options?: IJsonSerializerOptions): any; +} diff --git a/gun-server/node_modules/@peculiar/json-schema/build/types/storage.d.ts b/gun-server/node_modules/@peculiar/json-schema/build/types/storage.d.ts new file mode 100644 index 0000000..cf82b1c --- /dev/null +++ b/gun-server/node_modules/@peculiar/json-schema/build/types/storage.d.ts @@ -0,0 +1,6 @@ +import { JsonSchemaStorage } from "./schema"; +/** + * Name of default schema + */ +export declare const DEFAULT_SCHEMA = "default"; +export declare const schemaStorage: JsonSchemaStorage; diff --git a/gun-server/node_modules/@peculiar/json-schema/build/types/transform.d.ts b/gun-server/node_modules/@peculiar/json-schema/build/types/transform.d.ts new file mode 100644 index 0000000..af00a5b --- /dev/null +++ b/gun-server/node_modules/@peculiar/json-schema/build/types/transform.d.ts @@ -0,0 +1,9 @@ +import { IJsonSchema, IJsonSchemaItem } from "./schema"; +export interface IJsonNamedSchema { + [key: string]: IJsonSchemaItem; +} +export declare class JsonTransform { + protected static checkValues(data: any, schemaItem: IJsonSchemaItem): void; + protected static checkTypes(value: any, schemaItem: IJsonSchemaItem): void; + protected static getSchemaByName(schema: IJsonSchema, name?: string): IJsonNamedSchema; +} diff --git a/gun-server/node_modules/@peculiar/json-schema/build/types/types.d.ts b/gun-server/node_modules/@peculiar/json-schema/build/types/types.d.ts new file mode 100644 index 0000000..1b06d69 --- /dev/null +++ b/gun-server/node_modules/@peculiar/json-schema/build/types/types.d.ts @@ -0,0 +1,12 @@ +export declare type IEmptyConstructor = new () => T; +export interface IJsonConverter { + fromJSON(value: S, target: any): T; + toJSON(value: T, target: any): S; +} +export interface IJsonConvertible { + fromJSON(json: T): this; + toJSON(): T; +} +export interface IValidation { + validate(value: any): void; +} diff --git a/gun-server/node_modules/@peculiar/json-schema/build/types/validations/enumeration.d.ts b/gun-server/node_modules/@peculiar/json-schema/build/types/validations/enumeration.d.ts new file mode 100644 index 0000000..68930e0 --- /dev/null +++ b/gun-server/node_modules/@peculiar/json-schema/build/types/validations/enumeration.d.ts @@ -0,0 +1,6 @@ +import { IValidation } from "../types"; +export declare class EnumerationValidation implements IValidation { + private enumeration; + constructor(enumeration: string[]); + validate(value: any): void; +} diff --git a/gun-server/node_modules/@peculiar/json-schema/build/types/validations/exclusive.d.ts b/gun-server/node_modules/@peculiar/json-schema/build/types/validations/exclusive.d.ts new file mode 100644 index 0000000..7818b4a --- /dev/null +++ b/gun-server/node_modules/@peculiar/json-schema/build/types/validations/exclusive.d.ts @@ -0,0 +1,7 @@ +import { IValidation } from "../types"; +export declare class ExclusiveValidation implements IValidation { + private min; + private max; + constructor(min?: number, max?: number); + validate(value: any): void; +} diff --git a/gun-server/node_modules/@peculiar/json-schema/build/types/validations/inclusive.d.ts b/gun-server/node_modules/@peculiar/json-schema/build/types/validations/inclusive.d.ts new file mode 100644 index 0000000..c7be415 --- /dev/null +++ b/gun-server/node_modules/@peculiar/json-schema/build/types/validations/inclusive.d.ts @@ -0,0 +1,7 @@ +import { IValidation } from "../types"; +export declare class InclusiveValidation implements IValidation { + private min; + private max; + constructor(min?: number, max?: number); + validate(value: any): void; +} diff --git a/gun-server/node_modules/@peculiar/json-schema/build/types/validations/index.d.ts b/gun-server/node_modules/@peculiar/json-schema/build/types/validations/index.d.ts new file mode 100644 index 0000000..62aa539 --- /dev/null +++ b/gun-server/node_modules/@peculiar/json-schema/build/types/validations/index.d.ts @@ -0,0 +1,5 @@ +export * from "./pattern"; +export * from "./inclusive"; +export * from "./exclusive"; +export * from "./length"; +export * from "./enumeration"; diff --git a/gun-server/node_modules/@peculiar/json-schema/build/types/validations/length.d.ts b/gun-server/node_modules/@peculiar/json-schema/build/types/validations/length.d.ts new file mode 100644 index 0000000..11fbcf1 --- /dev/null +++ b/gun-server/node_modules/@peculiar/json-schema/build/types/validations/length.d.ts @@ -0,0 +1,8 @@ +import { IValidation } from "../types"; +export declare class LengthValidation implements IValidation { + private length?; + private minLength?; + private maxLength?; + constructor(length?: number | undefined, minLength?: number | undefined, maxLength?: number | undefined); + validate(value: any): void; +} diff --git a/gun-server/node_modules/@peculiar/json-schema/build/types/validations/pattern.d.ts b/gun-server/node_modules/@peculiar/json-schema/build/types/validations/pattern.d.ts new file mode 100644 index 0000000..7cd0c4c --- /dev/null +++ b/gun-server/node_modules/@peculiar/json-schema/build/types/validations/pattern.d.ts @@ -0,0 +1,6 @@ +import { IValidation } from "../types"; +export declare class PatternValidation implements IValidation { + private pattern; + constructor(pattern: string | RegExp); + validate(value: any): void; +} diff --git a/gun-server/node_modules/@peculiar/json-schema/package.json b/gun-server/node_modules/@peculiar/json-schema/package.json new file mode 100644 index 0000000..68cf403 --- /dev/null +++ b/gun-server/node_modules/@peculiar/json-schema/package.json @@ -0,0 +1,95 @@ +{ + "name": "@peculiar/json-schema", + "version": "1.1.12", + "description": "This package uses ES2015 decorators to simplify JSON schema creation and use", + "main": "build/index.js", + "module": "build/index.es.js", + "types": "build/types/index.d.ts", + "scripts": { + "test": "mocha", + "prepare": "npm run build", + "lint": "tslint -p .", + "lint:fix": "tslint --fix -p .", + "build": "npm run build:module && npm run build:types", + "build:module": "rollup -c", + "build:types": "tsc -p tsconfig.types.json", + "clear": "rimraf build/*", + "rebuild": "npm run clear && npm run build", + "prepub": "npm run lint && npm run build", + "pub": "npm version patch && npm publish", + "postpub": "git push && git push --tags origin master", + "prepub:next": "npm run lint && npm run build", + "pub:next": "npm version prerelease --preid=next && npm publish --tag next", + "postpub:next": "git push", + "coverage": "nyc npm test", + "coveralls": "nyc report --reporter=text-lcov | coveralls" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/PeculiarVentures/json-schema.git" + }, + "keywords": [ + "json", + "stringify", + "serialize", + "parse", + "convert", + "decorator" + ], + "author": "PeculiarVentures, Inc", + "contributors": [ + { + "email": "rmh@unmitigatedrisk.com", + "name": "Ryan Hurst" + }, + { + "email": "microshine@mail.ru", + "name": "Miroshin Stepan" + } + ], + "license": "MIT", + "bugs": { + "url": "https://github.com/PeculiarVentures/json-schema/issues" + }, + "homepage": "https://github.com/PeculiarVentures/json-schema#readme", + "engines": { + "node": ">=8.0.0" + }, + "devDependencies": { + "@types/mocha": "^8.0.0", + "@types/node": "^12.12.51", + "mocha": "^8.0.1", + "rimraf": "^3.0.2", + "rollup": "^2.22.2", + "rollup-plugin-typescript2": "^0.27.1", + "ts-node": "^8.10.2", + "tslint": "^6.1.2", + "typescript": "^3.9.7" + }, + "dependencies": { + "tslib": "^2.0.0" + }, + "nyc": { + "extension": [ + ".ts", + ".tsx" + ], + "include": [ + "src/**/*.ts" + ], + "exclude": [ + "**/*.d.ts" + ], + "reporter": [ + "text-summary", + "html" + ] + }, + "mocha": { + "require": "ts-node/register", + "extension": [ + "ts" + ], + "watch-files": "test/**/*.ts" + } +} diff --git a/gun-server/node_modules/@peculiar/webcrypto/LICENSE.md b/gun-server/node_modules/@peculiar/webcrypto/LICENSE.md new file mode 100644 index 0000000..1eb26e2 --- /dev/null +++ b/gun-server/node_modules/@peculiar/webcrypto/LICENSE.md @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Peculiar Ventures, LLC + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/gun-server/node_modules/@peculiar/webcrypto/README.md b/gun-server/node_modules/@peculiar/webcrypto/README.md new file mode 100644 index 0000000..4102468 --- /dev/null +++ b/gun-server/node_modules/@peculiar/webcrypto/README.md @@ -0,0 +1,89 @@ +# @peculiar/webcrypto + +[![License](https://img.shields.io/badge/license-MIT-green.svg?style=flat)](https://raw.githubusercontent.com/PeculiarVentures/webcrypto/master/LICENSE.md) +![test](https://github.com/PeculiarVentures/webcrypto/workflows/test/badge.svg) +[![Coverage Status](https://coveralls.io/repos/github/PeculiarVentures/webcrypto/badge.svg?branch=master)](https://coveralls.io/github/PeculiarVentures/webcrypto?branch=master) +[![npm version](https://badge.fury.io/js/%40peculiar%2Fwebcrypto.svg)](https://badge.fury.io/js/%40peculiar%2Fwebcrypto) + +We wanted to be able to write Javascript that used crypto on both the client and the server but we did not want to rely on Javascript implementations of crypto. The only native cryptography available in browser is [Web Crypto](http://caniuse.com/#search=cryptography), this resulted in us creating a `@peculiar/webcrypto`. + +## Table Of Contents + +* [WARNING](#warning) +* [Installing](#installing) +* [Using](#using) +* [Examples](#examples) +* [Bug Reporting](#bug-reporting) +* [Related](#related) + +## WARNING + +**At this time this solution should be considered suitable for research and experimentation, further code and security review is needed before utilization in a production application.** + +**Module is based on NodeJS v10 Crypto API. It would work only with Node v10 and higher.** + +## Installing + +``` +npm install @peculiar/webcrypto +``` + +## Supported algorithms + +| Algorithm name | generateKey | digest | export/import | sign/verify | encrypt/decrypt | wrapKey/unwrapKey | derive | +|-------------------|-------------|---------|---------------|-------------|-----------------|-------------------|---------| +| SHA-1 | | X | | | | | | +| SHA-256 | | X | | | | | | +| SHA-384 | | X | | | | | | +| SHA-512 | | X | | | | | | +| HMAC | X | | X | X | | | | +| RSASSA-PKCS1-v1_5 | X | | X | X | | | | +| RSAES-PKCS1-v1_52| X | | X | | X | X | | +| RSA-PSS | X | | X | X | | | | +| RSA-OAEP | X | | X | | X | X | | +| AES-CMAC | X | | X | X | | | | +| AES-CBC | X | | X | | X | X | | +| AES-CTR | X | | X | | X | X | | +| AES-ECB | X | | X | | X | X | | +| AES-GCM | X | | X | | X | X | | +| AES-KW | X | | X | | | X | | +| ECDSA1 | X | | X | X | | | | +| ECDH1 | X | | X | | | | X | +| EdDSA2,3 | X | | X | X | | | | +| ECDH-ES2,4 | X | | X | | | | X | +| HKDF | | | X | | | | X | +| PBKDF2 | | | X | | | | X | +| DES-CBC2| X | | X | | X | X | | +| DES-EDE3-CBC2| X | | X | | X | X | | +| shake1282| | X | | | | | | +| shake2562| | X | | | | | | + +1 Mechanism supports extended list of named curves `P-256`, `P-384`, `P-521`, `K-256`, +`brainpoolP160r1`, `brainpoolP160t1`, `brainpoolP192r1`, `brainpoolP192t1`, `brainpoolP224r1`, `brainpoolP224t1`, `brainpoolP256r1`, `brainpoolP256t1`, `brainpoolP320r1`, `brainpoolP320t1`, `brainpoolP384r1`, `brainpoolP384t1`, `brainpoolP512r1`, and `brainpoolP512t1` + +2 Mechanism is not defined by the WebCrypto specifications. Use of mechanism in a safe way is hard, it was added for the purpose of enabling interoperability with an existing system. We recommend against its use unless needed for interoperability. + +3 Mechanism supports extended list of named curves `Ed25519`, and `Ed448` + +4 Mechanism supports extended list of named curves `X25519`, and `X448` + +## Using + +```javascript +const { Crypto } = require("@peculiar/webcrypto"); + +const crypto = new Crypto(); +``` + +## Examples + +See [WebCrypto Docs](https://github.com/PeculiarVentures/webcrypto-docs/blob/master/README.md) for examples + +## Bug Reporting +Please report bugs either as pull requests or as issues in the issue tracker. `@peculiar/webcrypto` has a full disclosure vulnerability policy. Please do NOT attempt to report any security vulnerability in this code privately to anybody. + + +## Related + - [node-webcrypto-ossl](https://github.com/PeculiarVentures/node-webcrypto-ossl) + - [node-webcrypto-p11](https://github.com/PeculiarVentures/node-webcrypto-p11) + - [webcrypto-liner](https://github.com/PeculiarVentures/webcrypto-liner) diff --git a/gun-server/node_modules/@peculiar/webcrypto/build/webcrypto.es.js b/gun-server/node_modules/@peculiar/webcrypto/build/webcrypto.es.js new file mode 100644 index 0000000..dc81f75 --- /dev/null +++ b/gun-server/node_modules/@peculiar/webcrypto/build/webcrypto.es.js @@ -0,0 +1,2522 @@ +/*! + Copyright (c) Peculiar Ventures, LLC +*/ + +import * as core from 'webcrypto-core'; +import { BufferSourceConverter as BufferSourceConverter$1 } from 'webcrypto-core'; +export { CryptoKey } from 'webcrypto-core'; +import { Buffer as Buffer$1 } from 'buffer'; +import crypto from 'crypto'; +import * as process from 'process'; +import { __decorate } from 'tslib'; +import { JsonProp, JsonPropTypes, JsonSerializer, JsonParser } from '@peculiar/json-schema'; +import { Convert, BufferSourceConverter } from 'pvtsutils'; +import { AsnParser, AsnSerializer, AsnConvert } from '@peculiar/asn1-schema'; + +const JsonBase64UrlConverter = { + fromJSON: (value) => Buffer$1.from(Convert.FromBase64Url(value)), + toJSON: (value) => Convert.ToBase64Url(value), +}; + +class CryptoKey extends core.CryptoKey { + constructor() { + super(...arguments); + this.data = Buffer$1.alloc(0); + this.algorithm = { name: "" }; + this.extractable = false; + this.type = "secret"; + this.usages = []; + this.kty = "oct"; + this.alg = ""; + } +} +__decorate([ + JsonProp({ name: "ext", type: JsonPropTypes.Boolean, optional: true }) +], CryptoKey.prototype, "extractable", void 0); +__decorate([ + JsonProp({ name: "key_ops", type: JsonPropTypes.String, repeated: true, optional: true }) +], CryptoKey.prototype, "usages", void 0); +__decorate([ + JsonProp({ type: JsonPropTypes.String }) +], CryptoKey.prototype, "kty", void 0); +__decorate([ + JsonProp({ type: JsonPropTypes.String, optional: true }) +], CryptoKey.prototype, "alg", void 0); + +class SymmetricKey extends CryptoKey { + constructor() { + super(...arguments); + this.kty = "oct"; + this.type = "secret"; + } +} + +class AsymmetricKey extends CryptoKey { +} + +class AesCryptoKey extends SymmetricKey { + get alg() { + switch (this.algorithm.name.toUpperCase()) { + case "AES-CBC": + return `A${this.algorithm.length}CBC`; + case "AES-CTR": + return `A${this.algorithm.length}CTR`; + case "AES-GCM": + return `A${this.algorithm.length}GCM`; + case "AES-KW": + return `A${this.algorithm.length}KW`; + case "AES-CMAC": + return `A${this.algorithm.length}CMAC`; + case "AES-ECB": + return `A${this.algorithm.length}ECB`; + default: + throw new core.AlgorithmError("Unsupported algorithm name"); + } + } + set alg(value) { + } +} +__decorate([ + JsonProp({ name: "k", converter: JsonBase64UrlConverter }) +], AesCryptoKey.prototype, "data", void 0); + +class AesCrypto { + static async generateKey(algorithm, extractable, keyUsages) { + const key = new AesCryptoKey(); + key.algorithm = algorithm; + key.extractable = extractable; + key.usages = keyUsages; + key.data = crypto.randomBytes(algorithm.length >> 3); + return key; + } + static async exportKey(format, key) { + if (!(key instanceof AesCryptoKey)) { + throw new Error("key: Is not AesCryptoKey"); + } + switch (format.toLowerCase()) { + case "jwk": + return JsonSerializer.toJSON(key); + case "raw": + return new Uint8Array(key.data).buffer; + default: + throw new core.OperationError("format: Must be 'jwk' or 'raw'"); + } + } + static async importKey(format, keyData, algorithm, extractable, keyUsages) { + let key; + switch (format.toLowerCase()) { + case "jwk": + key = JsonParser.fromJSON(keyData, { targetSchema: AesCryptoKey }); + break; + case "raw": + key = new AesCryptoKey(); + key.data = Buffer$1.from(keyData); + break; + default: + throw new core.OperationError("format: Must be 'jwk' or 'raw'"); + } + key.algorithm = algorithm; + key.algorithm.length = key.data.length << 3; + key.extractable = extractable; + key.usages = keyUsages; + switch (key.algorithm.length) { + case 128: + case 192: + case 256: + break; + default: + throw new core.OperationError("keyData: Is wrong key length"); + } + return key; + } + static async encrypt(algorithm, key, data) { + switch (algorithm.name.toUpperCase()) { + case "AES-CBC": + return this.encryptAesCBC(algorithm, key, Buffer$1.from(data)); + case "AES-CTR": + return this.encryptAesCTR(algorithm, key, Buffer$1.from(data)); + case "AES-GCM": + return this.encryptAesGCM(algorithm, key, Buffer$1.from(data)); + case "AES-KW": + return this.encryptAesKW(algorithm, key, Buffer$1.from(data)); + case "AES-ECB": + return this.encryptAesECB(algorithm, key, Buffer$1.from(data)); + default: + throw new core.OperationError("algorithm: Is not recognized"); + } + } + static async decrypt(algorithm, key, data) { + if (!(key instanceof AesCryptoKey)) { + throw new Error("key: Is not AesCryptoKey"); + } + switch (algorithm.name.toUpperCase()) { + case "AES-CBC": + return this.decryptAesCBC(algorithm, key, Buffer$1.from(data)); + case "AES-CTR": + return this.decryptAesCTR(algorithm, key, Buffer$1.from(data)); + case "AES-GCM": + return this.decryptAesGCM(algorithm, key, Buffer$1.from(data)); + case "AES-KW": + return this.decryptAesKW(algorithm, key, Buffer$1.from(data)); + case "AES-ECB": + return this.decryptAesECB(algorithm, key, Buffer$1.from(data)); + default: + throw new core.OperationError("algorithm: Is not recognized"); + } + } + static async encryptAesCBC(algorithm, key, data) { + const cipher = crypto.createCipheriv(`aes-${key.algorithm.length}-cbc`, key.data, new Uint8Array(algorithm.iv)); + let enc = cipher.update(data); + enc = Buffer$1.concat([enc, cipher.final()]); + const res = new Uint8Array(enc).buffer; + return res; + } + static async decryptAesCBC(algorithm, key, data) { + const decipher = crypto.createDecipheriv(`aes-${key.algorithm.length}-cbc`, key.data, new Uint8Array(algorithm.iv)); + let dec = decipher.update(data); + dec = Buffer$1.concat([dec, decipher.final()]); + return new Uint8Array(dec).buffer; + } + static async encryptAesCTR(algorithm, key, data) { + const cipher = crypto.createCipheriv(`aes-${key.algorithm.length}-ctr`, key.data, Buffer$1.from(algorithm.counter)); + let enc = cipher.update(data); + enc = Buffer$1.concat([enc, cipher.final()]); + const res = new Uint8Array(enc).buffer; + return res; + } + static async decryptAesCTR(algorithm, key, data) { + const decipher = crypto.createDecipheriv(`aes-${key.algorithm.length}-ctr`, key.data, new Uint8Array(algorithm.counter)); + let dec = decipher.update(data); + dec = Buffer$1.concat([dec, decipher.final()]); + return new Uint8Array(dec).buffer; + } + static async encryptAesGCM(algorithm, key, data) { + const cipher = crypto.createCipheriv(`aes-${key.algorithm.length}-gcm`, key.data, Buffer$1.from(algorithm.iv), { + authTagLength: (algorithm.tagLength || 128) >> 3, + }); + if (algorithm.additionalData) { + cipher.setAAD(Buffer$1.from(algorithm.additionalData)); + } + let enc = cipher.update(data); + enc = Buffer$1.concat([enc, cipher.final(), cipher.getAuthTag()]); + const res = new Uint8Array(enc).buffer; + return res; + } + static async decryptAesGCM(algorithm, key, data) { + const tagLength = (algorithm.tagLength || 128) >> 3; + const decipher = crypto.createDecipheriv(`aes-${key.algorithm.length}-gcm`, key.data, new Uint8Array(algorithm.iv), { + authTagLength: tagLength, + }); + const enc = data.slice(0, data.length - tagLength); + const tag = data.slice(data.length - tagLength); + if (algorithm.additionalData) { + decipher.setAAD(Buffer$1.from(algorithm.additionalData)); + } + decipher.setAuthTag(tag); + let dec = decipher.update(enc); + dec = Buffer$1.concat([dec, decipher.final()]); + return new Uint8Array(dec).buffer; + } + static async encryptAesKW(algorithm, key, data) { + const cipher = crypto.createCipheriv(`id-aes${key.algorithm.length}-wrap`, key.data, this.AES_KW_IV); + let enc = cipher.update(data); + enc = Buffer$1.concat([enc, cipher.final()]); + return new Uint8Array(enc).buffer; + } + static async decryptAesKW(algorithm, key, data) { + const decipher = crypto.createDecipheriv(`id-aes${key.algorithm.length}-wrap`, key.data, this.AES_KW_IV); + let dec = decipher.update(data); + dec = Buffer$1.concat([dec, decipher.final()]); + return new Uint8Array(dec).buffer; + } + static async encryptAesECB(algorithm, key, data) { + const cipher = crypto.createCipheriv(`aes-${key.algorithm.length}-ecb`, key.data, new Uint8Array(0)); + let enc = cipher.update(data); + enc = Buffer$1.concat([enc, cipher.final()]); + const res = new Uint8Array(enc).buffer; + return res; + } + static async decryptAesECB(algorithm, key, data) { + const decipher = crypto.createDecipheriv(`aes-${key.algorithm.length}-ecb`, key.data, new Uint8Array(0)); + let dec = decipher.update(data); + dec = Buffer$1.concat([dec, decipher.final()]); + return new Uint8Array(dec).buffer; + } +} +AesCrypto.AES_KW_IV = Buffer$1.from("A6A6A6A6A6A6A6A6", "hex"); + +const keyStorage = new WeakMap(); +function getCryptoKey(key) { + const res = keyStorage.get(key); + if (!res) { + throw new core.OperationError("Cannot get CryptoKey from secure storage"); + } + return res; +} +function setCryptoKey(value) { + const key = core.CryptoKey.create(value.algorithm, value.type, value.extractable, value.usages); + Object.freeze(key); + keyStorage.set(key, value); + return key; +} + +class AesCbcProvider extends core.AesCbcProvider { + async onGenerateKey(algorithm, extractable, keyUsages) { + const key = await AesCrypto.generateKey({ + name: this.name, + length: algorithm.length, + }, extractable, keyUsages); + return setCryptoKey(key); + } + async onEncrypt(algorithm, key, data) { + return AesCrypto.encrypt(algorithm, getCryptoKey(key), new Uint8Array(data)); + } + async onDecrypt(algorithm, key, data) { + return AesCrypto.decrypt(algorithm, getCryptoKey(key), new Uint8Array(data)); + } + async onExportKey(format, key) { + return AesCrypto.exportKey(format, getCryptoKey(key)); + } + async onImportKey(format, keyData, algorithm, extractable, keyUsages) { + const key = await AesCrypto.importKey(format, keyData, { name: algorithm.name }, extractable, keyUsages); + return setCryptoKey(key); + } + checkCryptoKey(key, keyUsage) { + super.checkCryptoKey(key, keyUsage); + if (!(getCryptoKey(key) instanceof AesCryptoKey)) { + throw new TypeError("key: Is not a AesCryptoKey"); + } + } +} + +const zero = Buffer$1.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); +const rb = Buffer$1.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 135]); +const blockSize = 16; +function bitShiftLeft(buffer) { + const shifted = Buffer$1.alloc(buffer.length); + const last = buffer.length - 1; + for (let index = 0; index < last; index++) { + shifted[index] = buffer[index] << 1; + if (buffer[index + 1] & 0x80) { + shifted[index] += 0x01; + } + } + shifted[last] = buffer[last] << 1; + return shifted; +} +function xor(a, b) { + const length = Math.min(a.length, b.length); + const output = Buffer$1.alloc(length); + for (let index = 0; index < length; index++) { + output[index] = a[index] ^ b[index]; + } + return output; +} +function aes(key, message) { + const cipher = crypto.createCipheriv(`aes${key.length << 3}`, key, zero); + const result = cipher.update(message); + cipher.final(); + return result; +} +function getMessageBlock(message, blockIndex) { + const block = Buffer$1.alloc(blockSize); + const start = blockIndex * blockSize; + const end = start + blockSize; + message.copy(block, 0, start, end); + return block; +} +function getPaddedMessageBlock(message, blockIndex) { + const block = Buffer$1.alloc(blockSize); + const start = blockIndex * blockSize; + const end = message.length; + block.fill(0); + message.copy(block, 0, start, end); + block[end - start] = 0x80; + return block; +} +function generateSubkeys(key) { + const l = aes(key, zero); + let subkey1 = bitShiftLeft(l); + if (l[0] & 0x80) { + subkey1 = xor(subkey1, rb); + } + let subkey2 = bitShiftLeft(subkey1); + if (subkey1[0] & 0x80) { + subkey2 = xor(subkey2, rb); + } + return { subkey1, subkey2 }; +} +function aesCmac(key, message) { + const subkeys = generateSubkeys(key); + let blockCount = Math.ceil(message.length / blockSize); + let lastBlockCompleteFlag; + let lastBlock; + if (blockCount === 0) { + blockCount = 1; + lastBlockCompleteFlag = false; + } + else { + lastBlockCompleteFlag = (message.length % blockSize === 0); + } + const lastBlockIndex = blockCount - 1; + if (lastBlockCompleteFlag) { + lastBlock = xor(getMessageBlock(message, lastBlockIndex), subkeys.subkey1); + } + else { + lastBlock = xor(getPaddedMessageBlock(message, lastBlockIndex), subkeys.subkey2); + } + let x = zero; + let y; + for (let index = 0; index < lastBlockIndex; index++) { + y = xor(x, getMessageBlock(message, index)); + x = aes(key, y); + } + y = xor(lastBlock, x); + return aes(key, y); +} +class AesCmacProvider extends core.AesCmacProvider { + async onGenerateKey(algorithm, extractable, keyUsages) { + const key = await AesCrypto.generateKey({ + name: this.name, + length: algorithm.length, + }, extractable, keyUsages); + return setCryptoKey(key); + } + async onSign(algorithm, key, data) { + const result = aesCmac(getCryptoKey(key).data, Buffer$1.from(data)); + return new Uint8Array(result).buffer; + } + async onVerify(algorithm, key, signature, data) { + const signature2 = await this.sign(algorithm, key, data); + return Buffer$1.from(signature).compare(Buffer$1.from(signature2)) === 0; + } + async onExportKey(format, key) { + return AesCrypto.exportKey(format, getCryptoKey(key)); + } + async onImportKey(format, keyData, algorithm, extractable, keyUsages) { + const res = await AesCrypto.importKey(format, keyData, { name: algorithm.name }, extractable, keyUsages); + return setCryptoKey(res); + } + checkCryptoKey(key, keyUsage) { + super.checkCryptoKey(key, keyUsage); + if (!(getCryptoKey(key) instanceof AesCryptoKey)) { + throw new TypeError("key: Is not a AesCryptoKey"); + } + } +} + +class AesCtrProvider extends core.AesCtrProvider { + async onGenerateKey(algorithm, extractable, keyUsages) { + const key = await AesCrypto.generateKey({ + name: this.name, + length: algorithm.length, + }, extractable, keyUsages); + return setCryptoKey(key); + } + async onEncrypt(algorithm, key, data) { + return AesCrypto.encrypt(algorithm, getCryptoKey(key), new Uint8Array(data)); + } + async onDecrypt(algorithm, key, data) { + return AesCrypto.decrypt(algorithm, getCryptoKey(key), new Uint8Array(data)); + } + async onExportKey(format, key) { + return AesCrypto.exportKey(format, getCryptoKey(key)); + } + async onImportKey(format, keyData, algorithm, extractable, keyUsages) { + const res = await AesCrypto.importKey(format, keyData, { name: algorithm.name }, extractable, keyUsages); + return setCryptoKey(res); + } + checkCryptoKey(key, keyUsage) { + super.checkCryptoKey(key, keyUsage); + if (!(getCryptoKey(key) instanceof AesCryptoKey)) { + throw new TypeError("key: Is not a AesCryptoKey"); + } + } +} + +class AesGcmProvider extends core.AesGcmProvider { + async onGenerateKey(algorithm, extractable, keyUsages) { + const key = await AesCrypto.generateKey({ + name: this.name, + length: algorithm.length, + }, extractable, keyUsages); + return setCryptoKey(key); + } + async onEncrypt(algorithm, key, data) { + return AesCrypto.encrypt(algorithm, getCryptoKey(key), new Uint8Array(data)); + } + async onDecrypt(algorithm, key, data) { + return AesCrypto.decrypt(algorithm, getCryptoKey(key), new Uint8Array(data)); + } + async onExportKey(format, key) { + return AesCrypto.exportKey(format, getCryptoKey(key)); + } + async onImportKey(format, keyData, algorithm, extractable, keyUsages) { + const res = await AesCrypto.importKey(format, keyData, { name: algorithm.name }, extractable, keyUsages); + return setCryptoKey(res); + } + checkCryptoKey(key, keyUsage) { + super.checkCryptoKey(key, keyUsage); + if (!(getCryptoKey(key) instanceof AesCryptoKey)) { + throw new TypeError("key: Is not a AesCryptoKey"); + } + } +} + +class AesKwProvider extends core.AesKwProvider { + async onGenerateKey(algorithm, extractable, keyUsages) { + const res = await AesCrypto.generateKey({ + name: this.name, + length: algorithm.length, + }, extractable, keyUsages); + return setCryptoKey(res); + } + async onExportKey(format, key) { + return AesCrypto.exportKey(format, getCryptoKey(key)); + } + async onImportKey(format, keyData, algorithm, extractable, keyUsages) { + const res = await AesCrypto.importKey(format, keyData, { name: algorithm.name }, extractable, keyUsages); + return setCryptoKey(res); + } + async onEncrypt(algorithm, key, data) { + return AesCrypto.encrypt(algorithm, getCryptoKey(key), new Uint8Array(data)); + } + async onDecrypt(algorithm, key, data) { + return AesCrypto.decrypt(algorithm, getCryptoKey(key), new Uint8Array(data)); + } + checkCryptoKey(key, keyUsage) { + super.checkCryptoKey(key, keyUsage); + if (!(getCryptoKey(key) instanceof AesCryptoKey)) { + throw new TypeError("key: Is not a AesCryptoKey"); + } + } +} + +class AesEcbProvider extends core.AesEcbProvider { + async onGenerateKey(algorithm, extractable, keyUsages) { + const key = await AesCrypto.generateKey({ + name: this.name, + length: algorithm.length, + }, extractable, keyUsages); + return setCryptoKey(key); + } + async onEncrypt(algorithm, key, data) { + return AesCrypto.encrypt(algorithm, getCryptoKey(key), new Uint8Array(data)); + } + async onDecrypt(algorithm, key, data) { + return AesCrypto.decrypt(algorithm, getCryptoKey(key), new Uint8Array(data)); + } + async onExportKey(format, key) { + return AesCrypto.exportKey(format, getCryptoKey(key)); + } + async onImportKey(format, keyData, algorithm, extractable, keyUsages) { + const res = await AesCrypto.importKey(format, keyData, { name: algorithm.name }, extractable, keyUsages); + return setCryptoKey(res); + } + checkCryptoKey(key, keyUsage) { + super.checkCryptoKey(key, keyUsage); + if (!(getCryptoKey(key) instanceof AesCryptoKey)) { + throw new TypeError("key: Is not a AesCryptoKey"); + } + } +} + +class DesCryptoKey extends SymmetricKey { + get alg() { + switch (this.algorithm.name.toUpperCase()) { + case "DES-CBC": + return `DES-CBC`; + case "DES-EDE3-CBC": + return `3DES-CBC`; + default: + throw new core.AlgorithmError("Unsupported algorithm name"); + } + } + set alg(value) { + } +} +__decorate([ + JsonProp({ name: "k", converter: JsonBase64UrlConverter }) +], DesCryptoKey.prototype, "data", void 0); + +class DesCrypto { + static async generateKey(algorithm, extractable, keyUsages) { + const key = new DesCryptoKey(); + key.algorithm = algorithm; + key.extractable = extractable; + key.usages = keyUsages; + key.data = crypto.randomBytes(algorithm.length >> 3); + return key; + } + static async exportKey(format, key) { + switch (format.toLowerCase()) { + case "jwk": + return JsonSerializer.toJSON(key); + case "raw": + return new Uint8Array(key.data).buffer; + default: + throw new core.OperationError("format: Must be 'jwk' or 'raw'"); + } + } + static async importKey(format, keyData, algorithm, extractable, keyUsages) { + let key; + switch (format.toLowerCase()) { + case "jwk": + key = JsonParser.fromJSON(keyData, { targetSchema: DesCryptoKey }); + break; + case "raw": + key = new DesCryptoKey(); + key.data = Buffer$1.from(keyData); + break; + default: + throw new core.OperationError("format: Must be 'jwk' or 'raw'"); + } + key.algorithm = algorithm; + key.extractable = extractable; + key.usages = keyUsages; + return key; + } + static async encrypt(algorithm, key, data) { + switch (algorithm.name.toUpperCase()) { + case "DES-CBC": + return this.encryptDesCBC(algorithm, key, Buffer$1.from(data)); + case "DES-EDE3-CBC": + return this.encryptDesEDE3CBC(algorithm, key, Buffer$1.from(data)); + default: + throw new core.OperationError("algorithm: Is not recognized"); + } + } + static async decrypt(algorithm, key, data) { + if (!(key instanceof DesCryptoKey)) { + throw new Error("key: Is not DesCryptoKey"); + } + switch (algorithm.name.toUpperCase()) { + case "DES-CBC": + return this.decryptDesCBC(algorithm, key, Buffer$1.from(data)); + case "DES-EDE3-CBC": + return this.decryptDesEDE3CBC(algorithm, key, Buffer$1.from(data)); + default: + throw new core.OperationError("algorithm: Is not recognized"); + } + } + static async encryptDesCBC(algorithm, key, data) { + const cipher = crypto.createCipheriv(`des-cbc`, key.data, new Uint8Array(algorithm.iv)); + let enc = cipher.update(data); + enc = Buffer$1.concat([enc, cipher.final()]); + const res = new Uint8Array(enc).buffer; + return res; + } + static async decryptDesCBC(algorithm, key, data) { + const decipher = crypto.createDecipheriv(`des-cbc`, key.data, new Uint8Array(algorithm.iv)); + let dec = decipher.update(data); + dec = Buffer$1.concat([dec, decipher.final()]); + return new Uint8Array(dec).buffer; + } + static async encryptDesEDE3CBC(algorithm, key, data) { + const cipher = crypto.createCipheriv(`des-ede3-cbc`, key.data, Buffer$1.from(algorithm.iv)); + let enc = cipher.update(data); + enc = Buffer$1.concat([enc, cipher.final()]); + const res = new Uint8Array(enc).buffer; + return res; + } + static async decryptDesEDE3CBC(algorithm, key, data) { + const decipher = crypto.createDecipheriv(`des-ede3-cbc`, key.data, new Uint8Array(algorithm.iv)); + let dec = decipher.update(data); + dec = Buffer$1.concat([dec, decipher.final()]); + return new Uint8Array(dec).buffer; + } +} + +class DesCbcProvider extends core.DesProvider { + constructor() { + super(...arguments); + this.keySizeBits = 64; + this.ivSize = 8; + this.name = "DES-CBC"; + } + async onGenerateKey(algorithm, extractable, keyUsages) { + const key = await DesCrypto.generateKey({ + name: this.name, + length: this.keySizeBits, + }, extractable, keyUsages); + return setCryptoKey(key); + } + async onEncrypt(algorithm, key, data) { + return DesCrypto.encrypt(algorithm, getCryptoKey(key), new Uint8Array(data)); + } + async onDecrypt(algorithm, key, data) { + return DesCrypto.decrypt(algorithm, getCryptoKey(key), new Uint8Array(data)); + } + async onExportKey(format, key) { + return DesCrypto.exportKey(format, getCryptoKey(key)); + } + async onImportKey(format, keyData, algorithm, extractable, keyUsages) { + const key = await DesCrypto.importKey(format, keyData, { name: this.name, length: this.keySizeBits }, extractable, keyUsages); + if (key.data.length !== (this.keySizeBits >> 3)) { + throw new core.OperationError("keyData: Wrong key size"); + } + return setCryptoKey(key); + } + checkCryptoKey(key, keyUsage) { + super.checkCryptoKey(key, keyUsage); + if (!(getCryptoKey(key) instanceof DesCryptoKey)) { + throw new TypeError("key: Is not a DesCryptoKey"); + } + } +} + +class DesEde3CbcProvider extends core.DesProvider { + constructor() { + super(...arguments); + this.keySizeBits = 192; + this.ivSize = 8; + this.name = "DES-EDE3-CBC"; + } + async onGenerateKey(algorithm, extractable, keyUsages) { + const key = await DesCrypto.generateKey({ + name: this.name, + length: this.keySizeBits, + }, extractable, keyUsages); + return setCryptoKey(key); + } + async onEncrypt(algorithm, key, data) { + return DesCrypto.encrypt(algorithm, getCryptoKey(key), new Uint8Array(data)); + } + async onDecrypt(algorithm, key, data) { + return DesCrypto.decrypt(algorithm, getCryptoKey(key), new Uint8Array(data)); + } + async onExportKey(format, key) { + return DesCrypto.exportKey(format, getCryptoKey(key)); + } + async onImportKey(format, keyData, algorithm, extractable, keyUsages) { + const key = await DesCrypto.importKey(format, keyData, { name: this.name, length: this.keySizeBits }, extractable, keyUsages); + if (key.data.length !== (this.keySizeBits >> 3)) { + throw new core.OperationError("keyData: Wrong key size"); + } + return setCryptoKey(key); + } + checkCryptoKey(key, keyUsage) { + super.checkCryptoKey(key, keyUsage); + if (!(getCryptoKey(key) instanceof DesCryptoKey)) { + throw new TypeError("key: Is not a DesCryptoKey"); + } + } +} + +function getJwkAlgorithm(algorithm) { + switch (algorithm.name.toUpperCase()) { + case "RSA-OAEP": { + const mdSize = /(\d+)$/.exec(algorithm.hash.name)[1]; + return `RSA-OAEP${mdSize !== "1" ? `-${mdSize}` : ""}`; + } + case "RSASSA-PKCS1-V1_5": + return `RS${/(\d+)$/.exec(algorithm.hash.name)[1]}`; + case "RSA-PSS": + return `PS${/(\d+)$/.exec(algorithm.hash.name)[1]}`; + case "RSA-PKCS1": + return `RS1`; + default: + throw new core.OperationError("algorithm: Is not recognized"); + } +} + +class RsaPrivateKey extends AsymmetricKey { + constructor() { + super(...arguments); + this.type = "private"; + } + getKey() { + const keyInfo = AsnParser.parse(this.data, core.asn1.PrivateKeyInfo); + return AsnParser.parse(keyInfo.privateKey, core.asn1.RsaPrivateKey); + } + toJSON() { + const key = this.getKey(); + const json = { + kty: "RSA", + alg: getJwkAlgorithm(this.algorithm), + key_ops: this.usages, + ext: this.extractable, + }; + return Object.assign(json, JsonSerializer.toJSON(key)); + } + fromJSON(json) { + const key = JsonParser.fromJSON(json, { targetSchema: core.asn1.RsaPrivateKey }); + const keyInfo = new core.asn1.PrivateKeyInfo(); + keyInfo.privateKeyAlgorithm.algorithm = "1.2.840.113549.1.1.1"; + keyInfo.privateKeyAlgorithm.parameters = null; + keyInfo.privateKey = AsnSerializer.serialize(key); + this.data = Buffer$1.from(AsnSerializer.serialize(keyInfo)); + } +} + +class RsaPublicKey extends AsymmetricKey { + constructor() { + super(...arguments); + this.type = "public"; + } + getKey() { + const keyInfo = AsnParser.parse(this.data, core.asn1.PublicKeyInfo); + return AsnParser.parse(keyInfo.publicKey, core.asn1.RsaPublicKey); + } + toJSON() { + const key = this.getKey(); + const json = { + kty: "RSA", + alg: getJwkAlgorithm(this.algorithm), + key_ops: this.usages, + ext: this.extractable, + }; + return Object.assign(json, JsonSerializer.toJSON(key)); + } + fromJSON(json) { + const key = JsonParser.fromJSON(json, { targetSchema: core.asn1.RsaPublicKey }); + const keyInfo = new core.asn1.PublicKeyInfo(); + keyInfo.publicKeyAlgorithm.algorithm = "1.2.840.113549.1.1.1"; + keyInfo.publicKeyAlgorithm.parameters = null; + keyInfo.publicKey = AsnSerializer.serialize(key); + this.data = Buffer$1.from(AsnSerializer.serialize(keyInfo)); + } +} + +class RsaCrypto { + static async generateKey(algorithm, extractable, keyUsages) { + const privateKey = new RsaPrivateKey(); + privateKey.algorithm = algorithm; + privateKey.extractable = extractable; + privateKey.usages = keyUsages.filter((usage) => this.privateKeyUsages.indexOf(usage) !== -1); + const publicKey = new RsaPublicKey(); + publicKey.algorithm = algorithm; + publicKey.extractable = true; + publicKey.usages = keyUsages.filter((usage) => this.publicKeyUsages.indexOf(usage) !== -1); + const publicExponent = Buffer$1.concat([ + Buffer$1.alloc(4 - algorithm.publicExponent.byteLength, 0), + Buffer$1.from(algorithm.publicExponent), + ]).readInt32BE(0); + const keys = crypto.generateKeyPairSync("rsa", { + modulusLength: algorithm.modulusLength, + publicExponent, + publicKeyEncoding: { + format: "der", + type: "spki", + }, + privateKeyEncoding: { + format: "der", + type: "pkcs8", + }, + }); + privateKey.data = keys.privateKey; + publicKey.data = keys.publicKey; + const res = { + privateKey, + publicKey, + }; + return res; + } + static async exportKey(format, key) { + switch (format.toLowerCase()) { + case "jwk": + return JsonSerializer.toJSON(key); + case "pkcs8": + case "spki": + return new Uint8Array(key.data).buffer; + default: + throw new core.OperationError("format: Must be 'jwk', 'pkcs8' or 'spki'"); + } + } + static async importKey(format, keyData, algorithm, extractable, keyUsages) { + switch (format.toLowerCase()) { + case "jwk": { + const jwk = keyData; + if (jwk.d) { + const asnKey = JsonParser.fromJSON(keyData, { targetSchema: core.asn1.RsaPrivateKey }); + return this.importPrivateKey(asnKey, algorithm, extractable, keyUsages); + } + else { + const asnKey = JsonParser.fromJSON(keyData, { targetSchema: core.asn1.RsaPublicKey }); + return this.importPublicKey(asnKey, algorithm, extractable, keyUsages); + } + } + case "spki": { + const keyInfo = AsnParser.parse(new Uint8Array(keyData), core.asn1.PublicKeyInfo); + const asnKey = AsnParser.parse(keyInfo.publicKey, core.asn1.RsaPublicKey); + return this.importPublicKey(asnKey, algorithm, extractable, keyUsages); + } + case "pkcs8": { + const keyInfo = AsnParser.parse(new Uint8Array(keyData), core.asn1.PrivateKeyInfo); + const asnKey = AsnParser.parse(keyInfo.privateKey, core.asn1.RsaPrivateKey); + return this.importPrivateKey(asnKey, algorithm, extractable, keyUsages); + } + default: + throw new core.OperationError("format: Must be 'jwk', 'pkcs8' or 'spki'"); + } + } + static async sign(algorithm, key, data) { + switch (algorithm.name.toUpperCase()) { + case "RSA-PSS": + case "RSASSA-PKCS1-V1_5": + return this.signRsa(algorithm, key, data); + default: + throw new core.OperationError("algorithm: Is not recognized"); + } + } + static async verify(algorithm, key, signature, data) { + switch (algorithm.name.toUpperCase()) { + case "RSA-PSS": + case "RSASSA-PKCS1-V1_5": + return this.verifySSA(algorithm, key, data, signature); + default: + throw new core.OperationError("algorithm: Is not recognized"); + } + } + static async encrypt(algorithm, key, data) { + switch (algorithm.name.toUpperCase()) { + case "RSA-OAEP": + return this.encryptOAEP(algorithm, key, data); + default: + throw new core.OperationError("algorithm: Is not recognized"); + } + } + static async decrypt(algorithm, key, data) { + switch (algorithm.name.toUpperCase()) { + case "RSA-OAEP": + return this.decryptOAEP(algorithm, key, data); + default: + throw new core.OperationError("algorithm: Is not recognized"); + } + } + static importPrivateKey(asnKey, algorithm, extractable, keyUsages) { + const keyInfo = new core.asn1.PrivateKeyInfo(); + keyInfo.privateKeyAlgorithm.algorithm = "1.2.840.113549.1.1.1"; + keyInfo.privateKeyAlgorithm.parameters = null; + keyInfo.privateKey = AsnSerializer.serialize(asnKey); + const key = new RsaPrivateKey(); + key.data = Buffer$1.from(AsnSerializer.serialize(keyInfo)); + key.algorithm = Object.assign({}, algorithm); + key.algorithm.publicExponent = new Uint8Array(asnKey.publicExponent); + key.algorithm.modulusLength = asnKey.modulus.byteLength << 3; + key.extractable = extractable; + key.usages = keyUsages; + return key; + } + static importPublicKey(asnKey, algorithm, extractable, keyUsages) { + const keyInfo = new core.asn1.PublicKeyInfo(); + keyInfo.publicKeyAlgorithm.algorithm = "1.2.840.113549.1.1.1"; + keyInfo.publicKeyAlgorithm.parameters = null; + keyInfo.publicKey = AsnSerializer.serialize(asnKey); + const key = new RsaPublicKey(); + key.data = Buffer$1.from(AsnSerializer.serialize(keyInfo)); + key.algorithm = Object.assign({}, algorithm); + key.algorithm.publicExponent = new Uint8Array(asnKey.publicExponent); + key.algorithm.modulusLength = asnKey.modulus.byteLength << 3; + key.extractable = extractable; + key.usages = keyUsages; + return key; + } + static getCryptoAlgorithm(alg) { + switch (alg.hash.name.toUpperCase()) { + case "SHA-1": + return "RSA-SHA1"; + case "SHA-256": + return "RSA-SHA256"; + case "SHA-384": + return "RSA-SHA384"; + case "SHA-512": + return "RSA-SHA512"; + case "SHA3-256": + return "RSA-SHA3-256"; + case "SHA3-384": + return "RSA-SHA3-384"; + case "SHA3-512": + return "RSA-SHA3-512"; + default: + throw new core.OperationError("algorithm.hash: Is not recognized"); + } + } + static signRsa(algorithm, key, data) { + const cryptoAlg = this.getCryptoAlgorithm(key.algorithm); + const signer = crypto.createSign(cryptoAlg); + signer.update(Buffer$1.from(data)); + if (!key.pem) { + key.pem = `-----BEGIN PRIVATE KEY-----\n${key.data.toString("base64")}\n-----END PRIVATE KEY-----`; + } + const options = { + key: key.pem, + }; + if (algorithm.name.toUpperCase() === "RSA-PSS") { + options.padding = crypto.constants.RSA_PKCS1_PSS_PADDING; + options.saltLength = algorithm.saltLength; + } + const signature = signer.sign(options); + return new Uint8Array(signature).buffer; + } + static verifySSA(algorithm, key, data, signature) { + const cryptoAlg = this.getCryptoAlgorithm(key.algorithm); + const signer = crypto.createVerify(cryptoAlg); + signer.update(Buffer$1.from(data)); + if (!key.pem) { + key.pem = `-----BEGIN PUBLIC KEY-----\n${key.data.toString("base64")}\n-----END PUBLIC KEY-----`; + } + const options = { + key: key.pem, + }; + if (algorithm.name.toUpperCase() === "RSA-PSS") { + options.padding = crypto.constants.RSA_PKCS1_PSS_PADDING; + options.saltLength = algorithm.saltLength; + } + const ok = signer.verify(options, signature); + return ok; + } + static encryptOAEP(algorithm, key, data) { + const options = { + key: `-----BEGIN PUBLIC KEY-----\n${key.data.toString("base64")}\n-----END PUBLIC KEY-----`, + padding: crypto.constants.RSA_PKCS1_OAEP_PADDING, + }; + if (algorithm.label) ; + return new Uint8Array(crypto.publicEncrypt(options, data)).buffer; + } + static decryptOAEP(algorithm, key, data) { + const options = { + key: `-----BEGIN PRIVATE KEY-----\n${key.data.toString("base64")}\n-----END PRIVATE KEY-----`, + padding: crypto.constants.RSA_PKCS1_OAEP_PADDING, + }; + if (algorithm.label) ; + return new Uint8Array(crypto.privateDecrypt(options, data)).buffer; + } +} +RsaCrypto.publicKeyUsages = ["verify", "encrypt", "wrapKey"]; +RsaCrypto.privateKeyUsages = ["sign", "decrypt", "unwrapKey"]; + +class RsaSsaProvider extends core.RsaSsaProvider { + constructor() { + super(...arguments); + this.hashAlgorithms = [ + "SHA-1", "SHA-256", "SHA-384", "SHA-512", + "shake128", "shake256", + "SHA3-256", "SHA3-384", "SHA3-512" + ]; + } + async onGenerateKey(algorithm, extractable, keyUsages) { + const keys = await RsaCrypto.generateKey({ + ...algorithm, + name: this.name, + }, extractable, keyUsages); + return { + privateKey: setCryptoKey(keys.privateKey), + publicKey: setCryptoKey(keys.publicKey), + }; + } + async onSign(algorithm, key, data) { + return RsaCrypto.sign(algorithm, getCryptoKey(key), new Uint8Array(data)); + } + async onVerify(algorithm, key, signature, data) { + return RsaCrypto.verify(algorithm, getCryptoKey(key), new Uint8Array(signature), new Uint8Array(data)); + } + async onExportKey(format, key) { + return RsaCrypto.exportKey(format, getCryptoKey(key)); + } + async onImportKey(format, keyData, algorithm, extractable, keyUsages) { + const key = await RsaCrypto.importKey(format, keyData, { ...algorithm, name: this.name }, extractable, keyUsages); + return setCryptoKey(key); + } + checkCryptoKey(key, keyUsage) { + super.checkCryptoKey(key, keyUsage); + const internalKey = getCryptoKey(key); + if (!(internalKey instanceof RsaPrivateKey || internalKey instanceof RsaPublicKey)) { + throw new TypeError("key: Is not RSA CryptoKey"); + } + } +} + +class RsaPssProvider extends core.RsaPssProvider { + constructor() { + super(...arguments); + this.hashAlgorithms = [ + "SHA-1", "SHA-256", "SHA-384", "SHA-512", + "shake128", "shake256", + "SHA3-256", "SHA3-384", "SHA3-512" + ]; + } + async onGenerateKey(algorithm, extractable, keyUsages) { + const keys = await RsaCrypto.generateKey({ + ...algorithm, + name: this.name, + }, extractable, keyUsages); + return { + privateKey: setCryptoKey(keys.privateKey), + publicKey: setCryptoKey(keys.publicKey), + }; + } + async onSign(algorithm, key, data) { + return RsaCrypto.sign(algorithm, getCryptoKey(key), new Uint8Array(data)); + } + async onVerify(algorithm, key, signature, data) { + return RsaCrypto.verify(algorithm, getCryptoKey(key), new Uint8Array(signature), new Uint8Array(data)); + } + async onExportKey(format, key) { + return RsaCrypto.exportKey(format, getCryptoKey(key)); + } + async onImportKey(format, keyData, algorithm, extractable, keyUsages) { + const key = await RsaCrypto.importKey(format, keyData, { ...algorithm, name: this.name }, extractable, keyUsages); + return setCryptoKey(key); + } + checkCryptoKey(key, keyUsage) { + super.checkCryptoKey(key, keyUsage); + const internalKey = getCryptoKey(key); + if (!(internalKey instanceof RsaPrivateKey || internalKey instanceof RsaPublicKey)) { + throw new TypeError("key: Is not RSA CryptoKey"); + } + } +} + +class ShaCrypto { + static size(algorithm) { + switch (algorithm.name.toUpperCase()) { + case "SHA-1": + return 160; + case "SHA-256": + case "SHA3-256": + return 256; + case "SHA-384": + case "SHA3-384": + return 384; + case "SHA-512": + case "SHA3-512": + return 512; + default: + throw new Error("Unrecognized name"); + } + } + static getAlgorithmName(algorithm) { + switch (algorithm.name.toUpperCase()) { + case "SHA-1": + return "sha1"; + case "SHA-256": + return "sha256"; + case "SHA-384": + return "sha384"; + case "SHA-512": + return "sha512"; + case "SHA3-256": + return "sha3-256"; + case "SHA3-384": + return "sha3-384"; + case "SHA3-512": + return "sha3-512"; + default: + throw new Error("Unrecognized name"); + } + } + static digest(algorithm, data) { + const hashAlg = this.getAlgorithmName(algorithm); + const hash = crypto.createHash(hashAlg) + .update(Buffer$1.from(data)).digest(); + return new Uint8Array(hash).buffer; + } +} + +class RsaOaepProvider extends core.RsaOaepProvider { + async onGenerateKey(algorithm, extractable, keyUsages) { + const keys = await RsaCrypto.generateKey({ + ...algorithm, + name: this.name, + }, extractable, keyUsages); + return { + privateKey: setCryptoKey(keys.privateKey), + publicKey: setCryptoKey(keys.publicKey), + }; + } + async onEncrypt(algorithm, key, data) { + const internalKey = getCryptoKey(key); + const dataView = new Uint8Array(data); + const keySize = Math.ceil(internalKey.algorithm.modulusLength >> 3); + const hashSize = ShaCrypto.size(internalKey.algorithm.hash) >> 3; + const dataLength = dataView.byteLength; + const psLength = keySize - dataLength - 2 * hashSize - 2; + if (dataLength > keySize - 2 * hashSize - 2) { + throw new Error("Data too large"); + } + const message = new Uint8Array(keySize); + const seed = message.subarray(1, hashSize + 1); + const dataBlock = message.subarray(hashSize + 1); + dataBlock.set(dataView, hashSize + psLength + 1); + const labelHash = crypto.createHash(internalKey.algorithm.hash.name.replace("-", "")) + .update(core.BufferSourceConverter.toUint8Array(algorithm.label || new Uint8Array(0))) + .digest(); + dataBlock.set(labelHash, 0); + dataBlock[hashSize + psLength] = 1; + crypto.randomFillSync(seed); + const dataBlockMask = this.mgf1(internalKey.algorithm.hash, seed, dataBlock.length); + for (let i = 0; i < dataBlock.length; i++) { + dataBlock[i] ^= dataBlockMask[i]; + } + const seedMask = this.mgf1(internalKey.algorithm.hash, dataBlock, seed.length); + for (let i = 0; i < seed.length; i++) { + seed[i] ^= seedMask[i]; + } + if (!internalKey.pem) { + internalKey.pem = `-----BEGIN PUBLIC KEY-----\n${internalKey.data.toString("base64")}\n-----END PUBLIC KEY-----`; + } + const pkcs0 = crypto.publicEncrypt({ + key: internalKey.pem, + padding: crypto.constants.RSA_NO_PADDING, + }, Buffer$1.from(message)); + return new Uint8Array(pkcs0).buffer; + } + async onDecrypt(algorithm, key, data) { + const internalKey = getCryptoKey(key); + const keySize = Math.ceil(internalKey.algorithm.modulusLength >> 3); + const hashSize = ShaCrypto.size(internalKey.algorithm.hash) >> 3; + const dataLength = data.byteLength; + if (dataLength !== keySize) { + throw new Error("Bad data"); + } + if (!internalKey.pem) { + internalKey.pem = `-----BEGIN PRIVATE KEY-----\n${internalKey.data.toString("base64")}\n-----END PRIVATE KEY-----`; + } + let pkcs0 = crypto.privateDecrypt({ + key: internalKey.pem, + padding: crypto.constants.RSA_NO_PADDING, + }, Buffer$1.from(data)); + const z = pkcs0[0]; + const seed = pkcs0.subarray(1, hashSize + 1); + const dataBlock = pkcs0.subarray(hashSize + 1); + if (z !== 0) { + throw new Error("Decryption failed"); + } + const seedMask = this.mgf1(internalKey.algorithm.hash, dataBlock, seed.length); + for (let i = 0; i < seed.length; i++) { + seed[i] ^= seedMask[i]; + } + const dataBlockMask = this.mgf1(internalKey.algorithm.hash, seed, dataBlock.length); + for (let i = 0; i < dataBlock.length; i++) { + dataBlock[i] ^= dataBlockMask[i]; + } + const labelHash = crypto.createHash(internalKey.algorithm.hash.name.replace("-", "")) + .update(core.BufferSourceConverter.toUint8Array(algorithm.label || new Uint8Array(0))) + .digest(); + for (let i = 0; i < hashSize; i++) { + if (labelHash[i] !== dataBlock[i]) { + throw new Error("Decryption failed"); + } + } + let psEnd = hashSize; + for (; psEnd < dataBlock.length; psEnd++) { + const psz = dataBlock[psEnd]; + if (psz === 1) { + break; + } + if (psz !== 0) { + throw new Error("Decryption failed"); + } + } + if (psEnd === dataBlock.length) { + throw new Error("Decryption failed"); + } + pkcs0 = dataBlock.subarray(psEnd + 1); + return new Uint8Array(pkcs0).buffer; + } + async onExportKey(format, key) { + return RsaCrypto.exportKey(format, getCryptoKey(key)); + } + async onImportKey(format, keyData, algorithm, extractable, keyUsages) { + const key = await RsaCrypto.importKey(format, keyData, { ...algorithm, name: this.name }, extractable, keyUsages); + return setCryptoKey(key); + } + checkCryptoKey(key, keyUsage) { + super.checkCryptoKey(key, keyUsage); + const internalKey = getCryptoKey(key); + if (!(internalKey instanceof RsaPrivateKey || internalKey instanceof RsaPublicKey)) { + throw new TypeError("key: Is not RSA CryptoKey"); + } + } + mgf1(algorithm, seed, length = 0) { + const hashSize = ShaCrypto.size(algorithm) >> 3; + const mask = new Uint8Array(length); + const counter = new Uint8Array(4); + const chunks = Math.ceil(length / hashSize); + for (let i = 0; i < chunks; i++) { + counter[0] = i >>> 24; + counter[1] = (i >>> 16) & 255; + counter[2] = (i >>> 8) & 255; + counter[3] = i & 255; + const submask = mask.subarray(i * hashSize); + let chunk = crypto.createHash(algorithm.name.replace("-", "")) + .update(seed) + .update(counter) + .digest(); + if (chunk.length > submask.length) { + chunk = chunk.subarray(0, submask.length); + } + submask.set(chunk); + } + return mask; + } +} + +class RsaEsProvider extends core.ProviderCrypto { + constructor() { + super(...arguments); + this.name = "RSAES-PKCS1-v1_5"; + this.usages = { + publicKey: ["encrypt", "wrapKey"], + privateKey: ["decrypt", "unwrapKey"], + }; + } + async onGenerateKey(algorithm, extractable, keyUsages) { + const keys = await RsaCrypto.generateKey({ + ...algorithm, + name: this.name, + }, extractable, keyUsages); + return { + privateKey: setCryptoKey(keys.privateKey), + publicKey: setCryptoKey(keys.publicKey), + }; + } + checkGenerateKeyParams(algorithm) { + this.checkRequiredProperty(algorithm, "publicExponent"); + if (!(algorithm.publicExponent && algorithm.publicExponent instanceof Uint8Array)) { + throw new TypeError("publicExponent: Missing or not a Uint8Array"); + } + const publicExponent = Convert.ToBase64(algorithm.publicExponent); + if (!(publicExponent === "Aw==" || publicExponent === "AQAB")) { + throw new TypeError("publicExponent: Must be [3] or [1,0,1]"); + } + this.checkRequiredProperty(algorithm, "modulusLength"); + switch (algorithm.modulusLength) { + case 1024: + case 2048: + case 4096: + break; + default: + throw new TypeError("modulusLength: Must be 1024, 2048, or 4096"); + } + } + async onEncrypt(algorithm, key, data) { + const options = this.toCryptoOptions(key); + const enc = crypto.publicEncrypt(options, new Uint8Array(data)); + return new Uint8Array(enc).buffer; + } + async onDecrypt(algorithm, key, data) { + const options = this.toCryptoOptions(key); + const dec = crypto.privateDecrypt(options, new Uint8Array(data)); + return new Uint8Array(dec).buffer; + } + async onExportKey(format, key) { + return RsaCrypto.exportKey(format, getCryptoKey(key)); + } + async onImportKey(format, keyData, algorithm, extractable, keyUsages) { + const key = await RsaCrypto.importKey(format, keyData, { ...algorithm, name: this.name }, extractable, keyUsages); + return setCryptoKey(key); + } + checkCryptoKey(key, keyUsage) { + super.checkCryptoKey(key, keyUsage); + const internalKey = getCryptoKey(key); + if (!(internalKey instanceof RsaPrivateKey || internalKey instanceof RsaPublicKey)) { + throw new TypeError("key: Is not RSA CryptoKey"); + } + } + toCryptoOptions(key) { + const type = key.type.toUpperCase(); + return { + key: `-----BEGIN ${type} KEY-----\n${getCryptoKey(key).data.toString("base64")}\n-----END ${type} KEY-----`, + padding: crypto.constants.RSA_PKCS1_PADDING, + }; + } +} + +const namedOIDs = { + "1.2.840.10045.3.1.7": "P-256", + "P-256": "1.2.840.10045.3.1.7", + "1.3.132.0.34": "P-384", + "P-384": "1.3.132.0.34", + "1.3.132.0.35": "P-521", + "P-521": "1.3.132.0.35", + "1.3.132.0.10": "K-256", + "K-256": "1.3.132.0.10", + "brainpoolP160r1": "1.3.36.3.3.2.8.1.1.1", + "1.3.36.3.3.2.8.1.1.1": "brainpoolP160r1", + "brainpoolP160t1": "1.3.36.3.3.2.8.1.1.2", + "1.3.36.3.3.2.8.1.1.2": "brainpoolP160t1", + "brainpoolP192r1": "1.3.36.3.3.2.8.1.1.3", + "1.3.36.3.3.2.8.1.1.3": "brainpoolP192r1", + "brainpoolP192t1": "1.3.36.3.3.2.8.1.1.4", + "1.3.36.3.3.2.8.1.1.4": "brainpoolP192t1", + "brainpoolP224r1": "1.3.36.3.3.2.8.1.1.5", + "1.3.36.3.3.2.8.1.1.5": "brainpoolP224r1", + "brainpoolP224t1": "1.3.36.3.3.2.8.1.1.6", + "1.3.36.3.3.2.8.1.1.6": "brainpoolP224t1", + "brainpoolP256r1": "1.3.36.3.3.2.8.1.1.7", + "1.3.36.3.3.2.8.1.1.7": "brainpoolP256r1", + "brainpoolP256t1": "1.3.36.3.3.2.8.1.1.8", + "1.3.36.3.3.2.8.1.1.8": "brainpoolP256t1", + "brainpoolP320r1": "1.3.36.3.3.2.8.1.1.9", + "1.3.36.3.3.2.8.1.1.9": "brainpoolP320r1", + "brainpoolP320t1": "1.3.36.3.3.2.8.1.1.10", + "1.3.36.3.3.2.8.1.1.10": "brainpoolP320t1", + "brainpoolP384r1": "1.3.36.3.3.2.8.1.1.11", + "1.3.36.3.3.2.8.1.1.11": "brainpoolP384r1", + "brainpoolP384t1": "1.3.36.3.3.2.8.1.1.12", + "1.3.36.3.3.2.8.1.1.12": "brainpoolP384t1", + "brainpoolP512r1": "1.3.36.3.3.2.8.1.1.13", + "1.3.36.3.3.2.8.1.1.13": "brainpoolP512r1", + "brainpoolP512t1": "1.3.36.3.3.2.8.1.1.14", + "1.3.36.3.3.2.8.1.1.14": "brainpoolP512t1", +}; +function getOidByNamedCurve$1(namedCurve) { + const oid = namedOIDs[namedCurve]; + if (!oid) { + throw new core.OperationError(`Cannot convert WebCrypto named curve '${namedCurve}' to OID`); + } + return oid; +} + +class EcPrivateKey extends AsymmetricKey { + constructor() { + super(...arguments); + this.type = "private"; + } + getKey() { + const keyInfo = AsnParser.parse(this.data, core.asn1.PrivateKeyInfo); + return AsnParser.parse(keyInfo.privateKey, core.asn1.EcPrivateKey); + } + toJSON() { + const key = this.getKey(); + const json = { + kty: "EC", + crv: this.algorithm.namedCurve, + key_ops: this.usages, + ext: this.extractable, + }; + return Object.assign(json, JsonSerializer.toJSON(key)); + } + fromJSON(json) { + if (!json.crv) { + throw new core.OperationError(`Cannot get named curve from JWK. Property 'crv' is required`); + } + const keyInfo = new core.asn1.PrivateKeyInfo(); + keyInfo.privateKeyAlgorithm.algorithm = "1.2.840.10045.2.1"; + keyInfo.privateKeyAlgorithm.parameters = AsnSerializer.serialize(new core.asn1.ObjectIdentifier(getOidByNamedCurve$1(json.crv))); + const key = JsonParser.fromJSON(json, { targetSchema: core.asn1.EcPrivateKey }); + keyInfo.privateKey = AsnSerializer.serialize(key); + this.data = Buffer$1.from(AsnSerializer.serialize(keyInfo)); + return this; + } +} + +class EcPublicKey extends AsymmetricKey { + constructor() { + super(...arguments); + this.type = "public"; + } + getKey() { + const keyInfo = AsnParser.parse(this.data, core.asn1.PublicKeyInfo); + return new core.asn1.EcPublicKey(keyInfo.publicKey); + } + toJSON() { + const key = this.getKey(); + const json = { + kty: "EC", + crv: this.algorithm.namedCurve, + key_ops: this.usages, + ext: this.extractable, + }; + return Object.assign(json, JsonSerializer.toJSON(key)); + } + fromJSON(json) { + if (!json.crv) { + throw new core.OperationError(`Cannot get named curve from JWK. Property 'crv' is required`); + } + const key = JsonParser.fromJSON(json, { targetSchema: core.asn1.EcPublicKey }); + const keyInfo = new core.asn1.PublicKeyInfo(); + keyInfo.publicKeyAlgorithm.algorithm = "1.2.840.10045.2.1"; + keyInfo.publicKeyAlgorithm.parameters = AsnSerializer.serialize(new core.asn1.ObjectIdentifier(getOidByNamedCurve$1(json.crv))); + keyInfo.publicKey = AsnSerializer.toASN(key).valueHex; + this.data = Buffer$1.from(AsnSerializer.serialize(keyInfo)); + return this; + } +} + +class Sha1Provider extends core.ProviderCrypto { + constructor() { + super(...arguments); + this.name = "SHA-1"; + this.usages = []; + } + async onDigest(algorithm, data) { + return ShaCrypto.digest(algorithm, data); + } +} + +class Sha256Provider extends core.ProviderCrypto { + constructor() { + super(...arguments); + this.name = "SHA-256"; + this.usages = []; + } + async onDigest(algorithm, data) { + return ShaCrypto.digest(algorithm, data); + } +} + +class Sha384Provider extends core.ProviderCrypto { + constructor() { + super(...arguments); + this.name = "SHA-384"; + this.usages = []; + } + async onDigest(algorithm, data) { + return ShaCrypto.digest(algorithm, data); + } +} + +class Sha512Provider extends core.ProviderCrypto { + constructor() { + super(...arguments); + this.name = "SHA-512"; + this.usages = []; + } + async onDigest(algorithm, data) { + return ShaCrypto.digest(algorithm, data); + } +} + +class Sha3256Provider extends core.ProviderCrypto { + constructor() { + super(...arguments); + this.name = "SHA3-256"; + this.usages = []; + } + async onDigest(algorithm, data) { + return ShaCrypto.digest(algorithm, data); + } +} + +class Sha3384Provider extends core.ProviderCrypto { + constructor() { + super(...arguments); + this.name = "SHA3-384"; + this.usages = []; + } + async onDigest(algorithm, data) { + return ShaCrypto.digest(algorithm, data); + } +} + +class Sha3512Provider extends core.ProviderCrypto { + constructor() { + super(...arguments); + this.name = "SHA3-512"; + this.usages = []; + } + async onDigest(algorithm, data) { + return ShaCrypto.digest(algorithm, data); + } +} + +class EcCrypto { + static async generateKey(algorithm, extractable, keyUsages) { + const privateKey = new EcPrivateKey(); + privateKey.algorithm = algorithm; + privateKey.extractable = extractable; + privateKey.usages = keyUsages.filter((usage) => this.privateKeyUsages.indexOf(usage) !== -1); + const publicKey = new EcPublicKey(); + publicKey.algorithm = algorithm; + publicKey.extractable = true; + publicKey.usages = keyUsages.filter((usage) => this.publicKeyUsages.indexOf(usage) !== -1); + const keys = crypto.generateKeyPairSync("ec", { + namedCurve: this.getOpenSSLNamedCurve(algorithm.namedCurve), + publicKeyEncoding: { + format: "der", + type: "spki", + }, + privateKeyEncoding: { + format: "der", + type: "pkcs8", + }, + }); + privateKey.data = keys.privateKey; + publicKey.data = keys.publicKey; + const res = { + privateKey, + publicKey, + }; + return res; + } + static async sign(algorithm, key, data) { + const cryptoAlg = ShaCrypto.getAlgorithmName(algorithm.hash); + const signer = crypto.createSign(cryptoAlg); + signer.update(Buffer$1.from(data)); + if (!key.pem) { + key.pem = `-----BEGIN PRIVATE KEY-----\n${key.data.toString("base64")}\n-----END PRIVATE KEY-----`; + } + const options = { + key: key.pem, + }; + const signature = signer.sign(options); + const ecSignature = AsnParser.parse(signature, core.asn1.EcDsaSignature); + const signatureRaw = core.EcUtils.encodeSignature(ecSignature, core.EcCurves.get(key.algorithm.namedCurve).size); + return signatureRaw.buffer; + } + static async verify(algorithm, key, signature, data) { + const cryptoAlg = ShaCrypto.getAlgorithmName(algorithm.hash); + const signer = crypto.createVerify(cryptoAlg); + signer.update(Buffer$1.from(data)); + if (!key.pem) { + key.pem = `-----BEGIN PUBLIC KEY-----\n${key.data.toString("base64")}\n-----END PUBLIC KEY-----`; + } + const options = { + key: key.pem, + }; + const ecSignature = new core.asn1.EcDsaSignature(); + const namedCurve = core.EcCurves.get(key.algorithm.namedCurve); + const signaturePoint = core.EcUtils.decodeSignature(signature, namedCurve.size); + ecSignature.r = BufferSourceConverter.toArrayBuffer(signaturePoint.r); + ecSignature.s = BufferSourceConverter.toArrayBuffer(signaturePoint.s); + const ecSignatureRaw = Buffer$1.from(AsnSerializer.serialize(ecSignature)); + const ok = signer.verify(options, ecSignatureRaw); + return ok; + } + static async deriveBits(algorithm, baseKey, length) { + const cryptoAlg = this.getOpenSSLNamedCurve(baseKey.algorithm.namedCurve); + const ecdh = crypto.createECDH(cryptoAlg); + const asnPrivateKey = AsnParser.parse(baseKey.data, core.asn1.PrivateKeyInfo); + const asnEcPrivateKey = AsnParser.parse(asnPrivateKey.privateKey, core.asn1.EcPrivateKey); + ecdh.setPrivateKey(Buffer$1.from(asnEcPrivateKey.privateKey)); + const asnPublicKey = AsnParser.parse(algorithm.public.data, core.asn1.PublicKeyInfo); + const bits = ecdh.computeSecret(Buffer$1.from(asnPublicKey.publicKey)); + if (length === null) { + return bits; + } + return new Uint8Array(bits).buffer.slice(0, length >> 3); + } + static async exportKey(format, key) { + switch (format.toLowerCase()) { + case "jwk": + return JsonSerializer.toJSON(key); + case "pkcs8": + case "spki": + return new Uint8Array(key.data).buffer; + case "raw": { + const publicKeyInfo = AsnParser.parse(key.data, core.asn1.PublicKeyInfo); + return publicKeyInfo.publicKey; + } + default: + throw new core.OperationError("format: Must be 'jwk', 'raw', pkcs8' or 'spki'"); + } + } + static async importKey(format, keyData, algorithm, extractable, keyUsages) { + switch (format.toLowerCase()) { + case "jwk": { + const jwk = keyData; + if (jwk.d) { + const asnKey = JsonParser.fromJSON(keyData, { targetSchema: core.asn1.EcPrivateKey }); + return this.importPrivateKey(asnKey, algorithm, extractable, keyUsages); + } + else { + const asnKey = JsonParser.fromJSON(keyData, { targetSchema: core.asn1.EcPublicKey }); + return this.importPublicKey(asnKey, algorithm, extractable, keyUsages); + } + } + case "raw": { + const asnKey = new core.asn1.EcPublicKey(keyData); + return this.importPublicKey(asnKey, algorithm, extractable, keyUsages); + } + case "spki": { + const keyInfo = AsnParser.parse(new Uint8Array(keyData), core.asn1.PublicKeyInfo); + const asnKey = new core.asn1.EcPublicKey(keyInfo.publicKey); + this.assertKeyParameters(keyInfo.publicKeyAlgorithm.parameters, algorithm.namedCurve); + return this.importPublicKey(asnKey, algorithm, extractable, keyUsages); + } + case "pkcs8": { + const keyInfo = AsnParser.parse(new Uint8Array(keyData), core.asn1.PrivateKeyInfo); + const asnKey = AsnParser.parse(keyInfo.privateKey, core.asn1.EcPrivateKey); + this.assertKeyParameters(keyInfo.privateKeyAlgorithm.parameters, algorithm.namedCurve); + return this.importPrivateKey(asnKey, algorithm, extractable, keyUsages); + } + default: + throw new core.OperationError("format: Must be 'jwk', 'raw', 'pkcs8' or 'spki'"); + } + } + static assertKeyParameters(parameters, namedCurve) { + if (!parameters) { + throw new core.CryptoError("Key info doesn't have required parameters"); + } + let namedCurveIdentifier = ""; + try { + namedCurveIdentifier = AsnParser.parse(parameters, core.asn1.ObjectIdentifier).value; + } + catch (e) { + throw new core.CryptoError("Cannot read key info parameters"); + } + if (getOidByNamedCurve$1(namedCurve) !== namedCurveIdentifier) { + throw new core.CryptoError("Key info parameter doesn't match to named curve"); + } + } + static async importPrivateKey(asnKey, algorithm, extractable, keyUsages) { + const keyInfo = new core.asn1.PrivateKeyInfo(); + keyInfo.privateKeyAlgorithm.algorithm = "1.2.840.10045.2.1"; + keyInfo.privateKeyAlgorithm.parameters = AsnSerializer.serialize(new core.asn1.ObjectIdentifier(getOidByNamedCurve$1(algorithm.namedCurve))); + keyInfo.privateKey = AsnSerializer.serialize(asnKey); + const key = new EcPrivateKey(); + key.data = Buffer$1.from(AsnSerializer.serialize(keyInfo)); + key.algorithm = Object.assign({}, algorithm); + key.extractable = extractable; + key.usages = keyUsages; + return key; + } + static async importPublicKey(asnKey, algorithm, extractable, keyUsages) { + const keyInfo = new core.asn1.PublicKeyInfo(); + keyInfo.publicKeyAlgorithm.algorithm = "1.2.840.10045.2.1"; + const namedCurve = getOidByNamedCurve$1(algorithm.namedCurve); + keyInfo.publicKeyAlgorithm.parameters = AsnSerializer.serialize(new core.asn1.ObjectIdentifier(namedCurve)); + keyInfo.publicKey = asnKey.value; + const key = new EcPublicKey(); + key.data = Buffer$1.from(AsnSerializer.serialize(keyInfo)); + key.algorithm = Object.assign({}, algorithm); + key.extractable = extractable; + key.usages = keyUsages; + return key; + } + static getOpenSSLNamedCurve(curve) { + switch (curve.toUpperCase()) { + case "P-256": + return "prime256v1"; + case "K-256": + return "secp256k1"; + case "P-384": + return "secp384r1"; + case "P-521": + return "secp521r1"; + default: + return curve; + } + } +} +EcCrypto.publicKeyUsages = ["verify"]; +EcCrypto.privateKeyUsages = ["sign", "deriveKey", "deriveBits"]; + +class EcdsaProvider extends core.EcdsaProvider { + constructor() { + super(...arguments); + this.namedCurves = core.EcCurves.names; + this.hashAlgorithms = [ + "SHA-1", "SHA-256", "SHA-384", "SHA-512", + "shake128", "shake256", + "SHA3-256", "SHA3-384", "SHA3-512" + ]; + } + async onGenerateKey(algorithm, extractable, keyUsages) { + const keys = await EcCrypto.generateKey({ + ...algorithm, + name: this.name, + }, extractable, keyUsages); + return { + privateKey: setCryptoKey(keys.privateKey), + publicKey: setCryptoKey(keys.publicKey), + }; + } + async onSign(algorithm, key, data) { + return EcCrypto.sign(algorithm, getCryptoKey(key), new Uint8Array(data)); + } + async onVerify(algorithm, key, signature, data) { + return EcCrypto.verify(algorithm, getCryptoKey(key), new Uint8Array(signature), new Uint8Array(data)); + } + async onExportKey(format, key) { + return EcCrypto.exportKey(format, getCryptoKey(key)); + } + async onImportKey(format, keyData, algorithm, extractable, keyUsages) { + const key = await EcCrypto.importKey(format, keyData, { ...algorithm, name: this.name }, extractable, keyUsages); + return setCryptoKey(key); + } + checkCryptoKey(key, keyUsage) { + super.checkCryptoKey(key, keyUsage); + const internalKey = getCryptoKey(key); + if (!(internalKey instanceof EcPrivateKey || internalKey instanceof EcPublicKey)) { + throw new TypeError("key: Is not EC CryptoKey"); + } + } +} + +class EcdhProvider extends core.EcdhProvider { + constructor() { + super(...arguments); + this.namedCurves = core.EcCurves.names; + } + async onGenerateKey(algorithm, extractable, keyUsages) { + const keys = await EcCrypto.generateKey({ + ...algorithm, + name: this.name, + }, extractable, keyUsages); + return { + privateKey: setCryptoKey(keys.privateKey), + publicKey: setCryptoKey(keys.publicKey), + }; + } + async onExportKey(format, key) { + return EcCrypto.exportKey(format, getCryptoKey(key)); + } + async onImportKey(format, keyData, algorithm, extractable, keyUsages) { + const key = await EcCrypto.importKey(format, keyData, { ...algorithm, name: this.name }, extractable, keyUsages); + return setCryptoKey(key); + } + checkCryptoKey(key, keyUsage) { + super.checkCryptoKey(key, keyUsage); + const internalKey = getCryptoKey(key); + if (!(internalKey instanceof EcPrivateKey || internalKey instanceof EcPublicKey)) { + throw new TypeError("key: Is not EC CryptoKey"); + } + } + async onDeriveBits(algorithm, baseKey, length) { + const bits = await EcCrypto.deriveBits({ ...algorithm, public: getCryptoKey(algorithm.public) }, getCryptoKey(baseKey), length); + return bits; + } +} + +const edOIDs = { + [core.asn1.idEd448]: "Ed448", + "ed448": core.asn1.idEd448, + [core.asn1.idX448]: "X448", + "x448": core.asn1.idX448, + [core.asn1.idEd25519]: "Ed25519", + "ed25519": core.asn1.idEd25519, + [core.asn1.idX25519]: "X25519", + "x25519": core.asn1.idX25519, +}; +function getOidByNamedCurve(namedCurve) { + const oid = edOIDs[namedCurve.toLowerCase()]; + if (!oid) { + throw new core.OperationError(`Cannot convert WebCrypto named curve '${namedCurve}' to OID`); + } + return oid; +} + +class EdPrivateKey extends AsymmetricKey { + constructor() { + super(...arguments); + this.type = "private"; + } + getKey() { + const keyInfo = AsnParser.parse(this.data, core.asn1.PrivateKeyInfo); + return AsnParser.parse(keyInfo.privateKey, core.asn1.CurvePrivateKey); + } + toJSON() { + const key = this.getKey(); + const json = { + kty: "OKP", + crv: this.algorithm.namedCurve, + key_ops: this.usages, + ext: this.extractable, + }; + return Object.assign(json, JsonSerializer.toJSON(key)); + } + fromJSON(json) { + if (!json.crv) { + throw new core.OperationError(`Cannot get named curve from JWK. Property 'crv' is required`); + } + const keyInfo = new core.asn1.PrivateKeyInfo(); + keyInfo.privateKeyAlgorithm.algorithm = getOidByNamedCurve(json.crv); + const key = JsonParser.fromJSON(json, { targetSchema: core.asn1.CurvePrivateKey }); + keyInfo.privateKey = AsnSerializer.serialize(key); + this.data = Buffer$1.from(AsnSerializer.serialize(keyInfo)); + return this; + } +} + +class EdPublicKey extends AsymmetricKey { + constructor() { + super(...arguments); + this.type = "public"; + } + getKey() { + const keyInfo = AsnParser.parse(this.data, core.asn1.PublicKeyInfo); + return keyInfo.publicKey; + } + toJSON() { + const key = this.getKey(); + const json = { + kty: "OKP", + crv: this.algorithm.namedCurve, + key_ops: this.usages, + ext: this.extractable, + }; + return Object.assign(json, { + x: Convert.ToBase64Url(key) + }); + } + fromJSON(json) { + if (!json.crv) { + throw new core.OperationError(`Cannot get named curve from JWK. Property 'crv' is required`); + } + if (!json.x) { + throw new core.OperationError(`Cannot get property from JWK. Property 'x' is required`); + } + const keyInfo = new core.asn1.PublicKeyInfo(); + keyInfo.publicKeyAlgorithm.algorithm = getOidByNamedCurve(json.crv); + keyInfo.publicKey = Convert.FromBase64Url(json.x); + this.data = Buffer$1.from(AsnSerializer.serialize(keyInfo)); + return this; + } +} + +class EdCrypto { + static async generateKey(algorithm, extractable, keyUsages) { + const privateKey = new EdPrivateKey(); + privateKey.algorithm = algorithm; + privateKey.extractable = extractable; + privateKey.usages = keyUsages.filter((usage) => this.privateKeyUsages.indexOf(usage) !== -1); + const publicKey = new EdPublicKey(); + publicKey.algorithm = algorithm; + publicKey.extractable = true; + publicKey.usages = keyUsages.filter((usage) => this.publicKeyUsages.indexOf(usage) !== -1); + const type = algorithm.namedCurve.toLowerCase(); + const keys = crypto.generateKeyPairSync(type, { + publicKeyEncoding: { + format: "der", + type: "spki", + }, + privateKeyEncoding: { + format: "der", + type: "pkcs8", + }, + }); + privateKey.data = keys.privateKey; + publicKey.data = keys.publicKey; + const res = { + privateKey, + publicKey, + }; + return res; + } + static async sign(algorithm, key, data) { + if (!key.pem) { + key.pem = `-----BEGIN PRIVATE KEY-----\n${key.data.toString("base64")}\n-----END PRIVATE KEY-----`; + } + const options = { + key: key.pem, + }; + const signature = crypto.sign(null, Buffer$1.from(data), options); + return core.BufferSourceConverter.toArrayBuffer(signature); + } + static async verify(algorithm, key, signature, data) { + if (!key.pem) { + key.pem = `-----BEGIN PUBLIC KEY-----\n${key.data.toString("base64")}\n-----END PUBLIC KEY-----`; + } + const options = { + key: key.pem, + }; + const ok = crypto.verify(null, Buffer$1.from(data), options, Buffer$1.from(signature)); + return ok; + } + static async deriveBits(algorithm, baseKey, length) { + const publicKey = crypto.createPublicKey({ + key: algorithm.public.data, + format: "der", + type: "spki", + }); + const privateKey = crypto.createPrivateKey({ + key: baseKey.data, + format: "der", + type: "pkcs8", + }); + const bits = crypto.diffieHellman({ + publicKey, + privateKey, + }); + return new Uint8Array(bits).buffer.slice(0, length >> 3); + } + static async exportKey(format, key) { + switch (format.toLowerCase()) { + case "jwk": + return JsonSerializer.toJSON(key); + case "pkcs8": + case "spki": + return new Uint8Array(key.data).buffer; + case "raw": { + const publicKeyInfo = AsnParser.parse(key.data, core.asn1.PublicKeyInfo); + return publicKeyInfo.publicKey; + } + default: + throw new core.OperationError("format: Must be 'jwk', 'raw', pkcs8' or 'spki'"); + } + } + static async importKey(format, keyData, algorithm, extractable, keyUsages) { + switch (format.toLowerCase()) { + case "jwk": { + const jwk = keyData; + if (jwk.d) { + const asnKey = JsonParser.fromJSON(keyData, { targetSchema: core.asn1.CurvePrivateKey }); + return this.importPrivateKey(asnKey, algorithm, extractable, keyUsages); + } + else { + if (!jwk.x) { + throw new TypeError("keyData: Cannot get required 'x' filed"); + } + return this.importPublicKey(Convert.FromBase64Url(jwk.x), algorithm, extractable, keyUsages); + } + } + case "raw": { + return this.importPublicKey(keyData, algorithm, extractable, keyUsages); + } + case "spki": { + const keyInfo = AsnParser.parse(new Uint8Array(keyData), core.asn1.PublicKeyInfo); + return this.importPublicKey(keyInfo.publicKey, algorithm, extractable, keyUsages); + } + case "pkcs8": { + const keyInfo = AsnParser.parse(new Uint8Array(keyData), core.asn1.PrivateKeyInfo); + const asnKey = AsnParser.parse(keyInfo.privateKey, core.asn1.CurvePrivateKey); + return this.importPrivateKey(asnKey, algorithm, extractable, keyUsages); + } + default: + throw new core.OperationError("format: Must be 'jwk', 'raw', 'pkcs8' or 'spki'"); + } + } + static importPrivateKey(asnKey, algorithm, extractable, keyUsages) { + const key = new EdPrivateKey(); + key.fromJSON({ + crv: algorithm.namedCurve, + d: Convert.ToBase64Url(asnKey.d), + }); + key.algorithm = Object.assign({}, algorithm); + key.extractable = extractable; + key.usages = keyUsages; + return key; + } + static async importPublicKey(asnKey, algorithm, extractable, keyUsages) { + const key = new EdPublicKey(); + key.fromJSON({ + crv: algorithm.namedCurve, + x: Convert.ToBase64Url(asnKey), + }); + key.algorithm = Object.assign({}, algorithm); + key.extractable = extractable; + key.usages = keyUsages; + return key; + } +} +EdCrypto.publicKeyUsages = ["verify"]; +EdCrypto.privateKeyUsages = ["sign", "deriveKey", "deriveBits"]; + +class EdDsaProvider extends core.EdDsaProvider { + async onGenerateKey(algorithm, extractable, keyUsages) { + const keys = await EdCrypto.generateKey({ + name: this.name, + namedCurve: algorithm.namedCurve.replace(/^ed/i, "Ed"), + }, extractable, keyUsages); + return { + privateKey: setCryptoKey(keys.privateKey), + publicKey: setCryptoKey(keys.publicKey), + }; + } + async onSign(algorithm, key, data) { + return EdCrypto.sign(algorithm, getCryptoKey(key), new Uint8Array(data)); + } + async onVerify(algorithm, key, signature, data) { + return EdCrypto.verify(algorithm, getCryptoKey(key), new Uint8Array(signature), new Uint8Array(data)); + } + async onExportKey(format, key) { + return EdCrypto.exportKey(format, getCryptoKey(key)); + } + async onImportKey(format, keyData, algorithm, extractable, keyUsages) { + const key = await EdCrypto.importKey(format, keyData, { ...algorithm, name: this.name }, extractable, keyUsages); + return setCryptoKey(key); + } +} + +class EcdhEsProvider extends core.EcdhEsProvider { + async onGenerateKey(algorithm, extractable, keyUsages) { + const keys = await EdCrypto.generateKey({ + name: this.name, + namedCurve: algorithm.namedCurve.toUpperCase(), + }, extractable, keyUsages); + return { + privateKey: setCryptoKey(keys.privateKey), + publicKey: setCryptoKey(keys.publicKey), + }; + } + async onDeriveBits(algorithm, baseKey, length) { + const bits = await EdCrypto.deriveBits({ ...algorithm, public: getCryptoKey(algorithm.public) }, getCryptoKey(baseKey), length); + return bits; + } + async onExportKey(format, key) { + return EdCrypto.exportKey(format, getCryptoKey(key)); + } + async onImportKey(format, keyData, algorithm, extractable, keyUsages) { + const key = await EdCrypto.importKey(format, keyData, { ...algorithm, name: this.name }, extractable, keyUsages); + return setCryptoKey(key); + } +} + +class Ed25519CryptoKey extends CryptoKey { + constructor(algorithm, extractable, usages, data) { + super(); + this.algorithm = algorithm; + this.extractable = extractable; + this.usages = usages; + this.data = Buffer.from(data); + } + toJWK() { + return { + kty: "OKP", + crv: this.algorithm.name, + key_ops: this.usages, + ext: this.extractable, + }; + } +} + +class Ed25519PrivateKey extends Ed25519CryptoKey { + constructor() { + super(...arguments); + this.type = "private"; + } + toJWK() { + const pubJwk = crypto.createPublicKey({ + key: this.data, + format: "pem", + }).export({ format: "jwk" }); + const raw = core.PemConverter.toUint8Array(this.data.toString()); + const pkcs8 = AsnConvert.parse(raw, core.asn1.PrivateKeyInfo); + const d = AsnConvert.parse(pkcs8.privateKey, core.asn1.EdPrivateKey).value; + return { + ...super.toJWK(), + ...pubJwk, + d: Buffer.from(new Uint8Array(d)).toString("base64url"), + }; + } +} + +class Ed25519PublicKey extends Ed25519CryptoKey { + constructor() { + super(...arguments); + this.type = "public"; + } + toJWK() { + const jwk = crypto.createPublicKey({ + key: this.data, + format: "pem", + }).export({ format: "jwk" }); + return { + ...super.toJWK(), + ...jwk, + }; + } +} + +class Ed25519Crypto { + static async generateKey(algorithm, extractable, keyUsages) { + const type = algorithm.name.toLowerCase(); + const keys = crypto.generateKeyPairSync(type, { + publicKeyEncoding: { + format: "pem", + type: "spki", + }, + privateKeyEncoding: { + format: "pem", + type: "pkcs8", + }, + }); + const keyAlg = { + name: type === "ed25519" ? "Ed25519" : "X25519", + }; + const privateKeyUsages = keyUsages.filter((usage) => this.privateKeyUsages.includes(usage)); + const publicKeyUsages = keyUsages.filter((usage) => this.publicKeyUsages.includes(usage)); + return { + privateKey: new Ed25519PrivateKey(keyAlg, extractable, privateKeyUsages, keys.privateKey), + publicKey: new Ed25519PublicKey(keyAlg, true, publicKeyUsages, keys.publicKey), + }; + } + static async sign(algorithm, key, data) { + const signature = crypto.sign(null, Buffer.from(data), key.data); + return core.BufferSourceConverter.toArrayBuffer(signature); + } + static async verify(algorithm, key, signature, data) { + return crypto.verify(null, Buffer.from(data), key.data, signature); + } + static async exportKey(format, key) { + switch (format) { + case "jwk": + return key.toJWK(); + case "pkcs8": { + return core.PemConverter.toArrayBuffer(key.data.toString()); + } + case "spki": { + return core.PemConverter.toArrayBuffer(key.data.toString()); + } + case "raw": { + const jwk = key.toJWK(); + return Convert.FromBase64Url(jwk.x); + } + default: + return Promise.reject(new core.OperationError("format: Must be 'jwk', 'raw', pkcs8' or 'spki'")); + } + } + static async importKey(format, keyData, algorithm, extractable, keyUsages) { + switch (format) { + case "jwk": { + const jwk = keyData; + if (jwk.d) { + const privateData = new core.asn1.EdPrivateKey(); + privateData.value = core.BufferSourceConverter.toArrayBuffer(Buffer.from(jwk.d, "base64url")); + const pkcs8 = new core.asn1.PrivateKeyInfo(); + pkcs8.privateKeyAlgorithm.algorithm = algorithm.name.toLowerCase() === "ed25519" + ? core.asn1.idEd25519 + : core.asn1.idX25519; + pkcs8.privateKey = AsnConvert.serialize(privateData); + const raw = AsnConvert.serialize(pkcs8); + const pem = core.PemConverter.fromBufferSource(raw, "PRIVATE KEY"); + return new Ed25519PrivateKey(algorithm, extractable, keyUsages, pem); + } + else if (jwk.x) { + const pubKey = crypto.createPublicKey({ + format: "jwk", + key: jwk, + }); + const pem = pubKey.export({ format: "pem", type: "spki" }); + return new Ed25519PublicKey(algorithm, extractable, keyUsages, pem); + } + else { + throw new core.OperationError("keyData: Cannot import JWK. 'd' or 'x' must be presented"); + } + } + case "pkcs8": { + const pem = core.PemConverter.fromBufferSource(keyData, "PRIVATE KEY"); + return new Ed25519PrivateKey(algorithm, extractable, keyUsages, pem); + } + case "spki": { + const pem = core.PemConverter.fromBufferSource(keyData, "PUBLIC KEY"); + return new Ed25519PublicKey(algorithm, extractable, keyUsages, pem); + } + case "raw": { + const raw = keyData; + const key = crypto.createPublicKey({ + format: "jwk", + key: { + kty: "OKP", + crv: algorithm.name.toLowerCase() === "ed25519" ? "Ed25519" : "X25519", + x: Convert.ToBase64Url(raw), + }, + }); + const pem = key.export({ format: "pem", type: "spki" }); + return new Ed25519PublicKey(algorithm, extractable, keyUsages, pem); + } + default: + return Promise.reject(new core.OperationError("format: Must be 'jwk', 'raw', pkcs8' or 'spki'")); + } + } +} +Ed25519Crypto.privateKeyUsages = ["sign", "deriveBits", "deriveKey"]; +Ed25519Crypto.publicKeyUsages = ["verify"]; + +class Ed25519Provider extends core.Ed25519Provider { + async onGenerateKey(algorithm, extractable, keyUsages) { + const keys = await Ed25519Crypto.generateKey(algorithm, extractable, keyUsages); + return { + privateKey: setCryptoKey(keys.privateKey), + publicKey: setCryptoKey(keys.publicKey), + }; + } + async onSign(algorithm, key, data) { + const internalKey = getCryptoKey(key); + const signature = Ed25519Crypto.sign(algorithm, internalKey, new Uint8Array(data)); + return signature; + } + onVerify(algorithm, key, signature, data) { + const internalKey = getCryptoKey(key); + return Ed25519Crypto.verify(algorithm, internalKey, new Uint8Array(signature), new Uint8Array(data)); + } + async onExportKey(format, key) { + const internalKey = getCryptoKey(key); + return Ed25519Crypto.exportKey(format, internalKey); + } + async onImportKey(format, keyData, algorithm, extractable, keyUsages) { + const internalKey = await Ed25519Crypto.importKey(format, keyData, algorithm, extractable, keyUsages); + return setCryptoKey(internalKey); + } +} + +class X25519Provider extends core.X25519Provider { + async onGenerateKey(algorithm, extractable, keyUsages) { + const keys = await Ed25519Crypto.generateKey(algorithm, extractable, keyUsages); + return { + privateKey: setCryptoKey(keys.privateKey), + publicKey: setCryptoKey(keys.publicKey), + }; + } + async onDeriveBits(algorithm, baseKey, length) { + const internalBaseKey = getCryptoKey(baseKey); + const internalPublicKey = getCryptoKey(algorithm.public); + const publicKey = crypto.createPublicKey({ + key: internalPublicKey.data.toString(), + format: "pem", + type: "spki", + }); + const privateKey = crypto.createPrivateKey({ + key: internalBaseKey.data.toString(), + format: "pem", + type: "pkcs8", + }); + const bits = crypto.diffieHellman({ + publicKey, + privateKey, + }); + return new Uint8Array(bits).buffer.slice(0, length >> 3); + } + async onExportKey(format, key) { + const internalKey = getCryptoKey(key); + return Ed25519Crypto.exportKey(format, internalKey); + } + async onImportKey(format, keyData, algorithm, extractable, keyUsages) { + const key = await Ed25519Crypto.importKey(format, keyData, algorithm, extractable, keyUsages); + return setCryptoKey(key); + } + checkCryptoKey(key, keyUsage) { + super.checkCryptoKey(key, keyUsage); + if (!(getCryptoKey(key) instanceof Ed25519CryptoKey)) { + throw new TypeError("key: Is not a Ed25519CryptoKey"); + } + } +} + +class PbkdfCryptoKey extends CryptoKey { +} + +class Pbkdf2Provider extends core.Pbkdf2Provider { + async onDeriveBits(algorithm, baseKey, length) { + return new Promise((resolve, reject) => { + const salt = core.BufferSourceConverter.toArrayBuffer(algorithm.salt); + const hash = algorithm.hash.name.replace("-", ""); + crypto.pbkdf2(getCryptoKey(baseKey).data, Buffer$1.from(salt), algorithm.iterations, length >> 3, hash, (err, derivedBits) => { + if (err) { + reject(err); + } + else { + resolve(new Uint8Array(derivedBits).buffer); + } + }); + }); + } + async onImportKey(format, keyData, algorithm, extractable, keyUsages) { + if (format === "raw") { + const key = new PbkdfCryptoKey(); + key.data = Buffer$1.from(keyData); + key.algorithm = { name: this.name }; + key.extractable = false; + key.usages = keyUsages; + return setCryptoKey(key); + } + throw new core.OperationError("format: Must be 'raw'"); + } + checkCryptoKey(key, keyUsage) { + super.checkCryptoKey(key, keyUsage); + if (!(getCryptoKey(key) instanceof PbkdfCryptoKey)) { + throw new TypeError("key: Is not PBKDF CryptoKey"); + } + } +} + +class HmacCryptoKey extends CryptoKey { + get alg() { + const hash = this.algorithm.hash.name.toUpperCase(); + return `HS${hash.replace("SHA-", "")}`; + } + set alg(value) { + } +} +__decorate([ + JsonProp({ name: "k", converter: JsonBase64UrlConverter }) +], HmacCryptoKey.prototype, "data", void 0); + +class HmacProvider extends core.HmacProvider { + async onGenerateKey(algorithm, extractable, keyUsages) { + const length = (algorithm.length || this.getDefaultLength(algorithm.hash.name)) >> 3 << 3; + const key = new HmacCryptoKey(); + key.algorithm = { + ...algorithm, + length, + name: this.name, + }; + key.extractable = extractable; + key.usages = keyUsages; + key.data = crypto.randomBytes(length >> 3); + return setCryptoKey(key); + } + async onSign(algorithm, key, data) { + const cryptoAlg = ShaCrypto.getAlgorithmName(key.algorithm.hash); + const hmac = crypto.createHmac(cryptoAlg, getCryptoKey(key).data) + .update(Buffer$1.from(data)).digest(); + return new Uint8Array(hmac).buffer; + } + async onVerify(algorithm, key, signature, data) { + const cryptoAlg = ShaCrypto.getAlgorithmName(key.algorithm.hash); + const hmac = crypto.createHmac(cryptoAlg, getCryptoKey(key).data) + .update(Buffer$1.from(data)).digest(); + return hmac.compare(Buffer$1.from(signature)) === 0; + } + async onImportKey(format, keyData, algorithm, extractable, keyUsages) { + let key; + switch (format.toLowerCase()) { + case "jwk": + key = JsonParser.fromJSON(keyData, { targetSchema: HmacCryptoKey }); + break; + case "raw": + key = new HmacCryptoKey(); + key.data = Buffer$1.from(keyData); + break; + default: + throw new core.OperationError("format: Must be 'jwk' or 'raw'"); + } + key.algorithm = { + hash: { name: algorithm.hash.name }, + name: this.name, + length: key.data.length << 3, + }; + key.extractable = extractable; + key.usages = keyUsages; + return setCryptoKey(key); + } + async onExportKey(format, key) { + switch (format.toLowerCase()) { + case "jwk": + return JsonSerializer.toJSON(getCryptoKey(key)); + case "raw": + return new Uint8Array(getCryptoKey(key).data).buffer; + default: + throw new core.OperationError("format: Must be 'jwk' or 'raw'"); + } + } + checkCryptoKey(key, keyUsage) { + super.checkCryptoKey(key, keyUsage); + if (!(getCryptoKey(key) instanceof HmacCryptoKey)) { + throw new TypeError("key: Is not HMAC CryptoKey"); + } + } +} + +class HkdfCryptoKey extends CryptoKey { +} + +class HkdfProvider extends core.HkdfProvider { + async onImportKey(format, keyData, algorithm, extractable, keyUsages) { + if (format.toLowerCase() !== "raw") { + throw new core.OperationError("Operation not supported"); + } + const key = new HkdfCryptoKey(); + key.data = Buffer$1.from(keyData); + key.algorithm = { name: this.name }; + key.extractable = extractable; + key.usages = keyUsages; + return setCryptoKey(key); + } + async onDeriveBits(params, baseKey, length) { + const hash = params.hash.name.replace("-", ""); + const hashLength = crypto.createHash(hash).digest().length; + const byteLength = length / 8; + const info = BufferSourceConverter$1.toUint8Array(params.info); + const PRK = crypto.createHmac(hash, BufferSourceConverter$1.toUint8Array(params.salt)) + .update(BufferSourceConverter$1.toUint8Array(getCryptoKey(baseKey).data)) + .digest(); + const blocks = [Buffer$1.alloc(0)]; + const blockCount = Math.ceil(byteLength / hashLength) + 1; + for (let i = 1; i < blockCount; ++i) { + blocks.push(crypto.createHmac(hash, PRK) + .update(Buffer$1.concat([blocks[i - 1], info, Buffer$1.from([i])])) + .digest()); + } + return Buffer$1.concat(blocks).slice(0, byteLength); + } + checkCryptoKey(key, keyUsage) { + super.checkCryptoKey(key, keyUsage); + if (!(getCryptoKey(key) instanceof HkdfCryptoKey)) { + throw new TypeError("key: Is not HKDF CryptoKey"); + } + } +} + +class ShakeCrypto { + static digest(algorithm, data) { + const hash = crypto.createHash(algorithm.name.toLowerCase(), { outputLength: algorithm.length }) + .update(Buffer$1.from(data)).digest(); + return new Uint8Array(hash).buffer; + } +} + +class Shake128Provider extends core.Shake128Provider { + async onDigest(algorithm, data) { + return ShakeCrypto.digest(algorithm, data); + } +} + +class Shake256Provider extends core.Shake256Provider { + async onDigest(algorithm, data) { + return ShakeCrypto.digest(algorithm, data); + } +} + +class SubtleCrypto extends core.SubtleCrypto { + constructor() { + var _a; + super(); + this.providers.set(new AesCbcProvider()); + this.providers.set(new AesCtrProvider()); + this.providers.set(new AesGcmProvider()); + this.providers.set(new AesCmacProvider()); + this.providers.set(new AesKwProvider()); + this.providers.set(new AesEcbProvider()); + const ciphers = crypto.getCiphers(); + if (ciphers.includes("des-cbc")) { + this.providers.set(new DesCbcProvider()); + } + this.providers.set(new DesEde3CbcProvider()); + this.providers.set(new RsaSsaProvider()); + this.providers.set(new RsaPssProvider()); + this.providers.set(new RsaOaepProvider()); + this.providers.set(new RsaEsProvider()); + this.providers.set(new EcdsaProvider()); + this.providers.set(new EcdhProvider()); + this.providers.set(new Sha1Provider()); + this.providers.set(new Sha256Provider()); + this.providers.set(new Sha384Provider()); + this.providers.set(new Sha512Provider()); + this.providers.set(new Pbkdf2Provider()); + this.providers.set(new HmacProvider()); + this.providers.set(new HkdfProvider()); + const nodeMajorVersion = (_a = /^v(\d+)/.exec(process.version)) === null || _a === void 0 ? void 0 : _a[1]; + if (nodeMajorVersion && parseInt(nodeMajorVersion, 10) >= 12) { + this.providers.set(new Shake128Provider()); + this.providers.set(new Shake256Provider()); + } + const hashes = crypto.getHashes(); + if (hashes.includes("sha3-256")) { + this.providers.set(new Sha3256Provider()); + } + if (hashes.includes("sha3-384")) { + this.providers.set(new Sha3384Provider()); + } + if (hashes.includes("sha3-512")) { + this.providers.set(new Sha3512Provider()); + } + if (nodeMajorVersion && parseInt(nodeMajorVersion, 10) >= 14) { + this.providers.set(new EdDsaProvider()); + this.providers.set(new EcdhEsProvider()); + this.providers.set(new Ed25519Provider()); + this.providers.set(new X25519Provider()); + } + } +} + +class Crypto extends core.Crypto { + constructor() { + super(...arguments); + this.subtle = new SubtleCrypto(); + } + getRandomValues(array) { + if (!ArrayBuffer.isView(array)) { + throw new TypeError("Failed to execute 'getRandomValues' on 'Crypto': parameter 1 is not of type 'ArrayBufferView'"); + } + const buffer = Buffer$1.from(array.buffer, array.byteOffset, array.byteLength); + crypto.randomFillSync(buffer); + return array; + } +} + +export { Crypto }; diff --git a/gun-server/node_modules/@peculiar/webcrypto/build/webcrypto.js b/gun-server/node_modules/@peculiar/webcrypto/build/webcrypto.js new file mode 100644 index 0000000..24362ea --- /dev/null +++ b/gun-server/node_modules/@peculiar/webcrypto/build/webcrypto.js @@ -0,0 +1,2546 @@ +/*! + Copyright (c) Peculiar Ventures, LLC +*/ + +'use strict'; + +var core = require('webcrypto-core'); +var buffer = require('buffer'); +var crypto = require('crypto'); +var process = require('process'); +var tslib = require('tslib'); +var jsonSchema = require('@peculiar/json-schema'); +var pvtsutils = require('pvtsutils'); +var asn1Schema = require('@peculiar/asn1-schema'); + +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var core__namespace = /*#__PURE__*/_interopNamespaceDefault(core); +var process__namespace = /*#__PURE__*/_interopNamespaceDefault(process); + +const JsonBase64UrlConverter = { + fromJSON: (value) => buffer.Buffer.from(pvtsutils.Convert.FromBase64Url(value)), + toJSON: (value) => pvtsutils.Convert.ToBase64Url(value), +}; + +class CryptoKey extends core__namespace.CryptoKey { + constructor() { + super(...arguments); + this.data = buffer.Buffer.alloc(0); + this.algorithm = { name: "" }; + this.extractable = false; + this.type = "secret"; + this.usages = []; + this.kty = "oct"; + this.alg = ""; + } +} +tslib.__decorate([ + jsonSchema.JsonProp({ name: "ext", type: jsonSchema.JsonPropTypes.Boolean, optional: true }) +], CryptoKey.prototype, "extractable", void 0); +tslib.__decorate([ + jsonSchema.JsonProp({ name: "key_ops", type: jsonSchema.JsonPropTypes.String, repeated: true, optional: true }) +], CryptoKey.prototype, "usages", void 0); +tslib.__decorate([ + jsonSchema.JsonProp({ type: jsonSchema.JsonPropTypes.String }) +], CryptoKey.prototype, "kty", void 0); +tslib.__decorate([ + jsonSchema.JsonProp({ type: jsonSchema.JsonPropTypes.String, optional: true }) +], CryptoKey.prototype, "alg", void 0); + +class SymmetricKey extends CryptoKey { + constructor() { + super(...arguments); + this.kty = "oct"; + this.type = "secret"; + } +} + +class AsymmetricKey extends CryptoKey { +} + +class AesCryptoKey extends SymmetricKey { + get alg() { + switch (this.algorithm.name.toUpperCase()) { + case "AES-CBC": + return `A${this.algorithm.length}CBC`; + case "AES-CTR": + return `A${this.algorithm.length}CTR`; + case "AES-GCM": + return `A${this.algorithm.length}GCM`; + case "AES-KW": + return `A${this.algorithm.length}KW`; + case "AES-CMAC": + return `A${this.algorithm.length}CMAC`; + case "AES-ECB": + return `A${this.algorithm.length}ECB`; + default: + throw new core__namespace.AlgorithmError("Unsupported algorithm name"); + } + } + set alg(value) { + } +} +tslib.__decorate([ + jsonSchema.JsonProp({ name: "k", converter: JsonBase64UrlConverter }) +], AesCryptoKey.prototype, "data", void 0); + +class AesCrypto { + static async generateKey(algorithm, extractable, keyUsages) { + const key = new AesCryptoKey(); + key.algorithm = algorithm; + key.extractable = extractable; + key.usages = keyUsages; + key.data = crypto.randomBytes(algorithm.length >> 3); + return key; + } + static async exportKey(format, key) { + if (!(key instanceof AesCryptoKey)) { + throw new Error("key: Is not AesCryptoKey"); + } + switch (format.toLowerCase()) { + case "jwk": + return jsonSchema.JsonSerializer.toJSON(key); + case "raw": + return new Uint8Array(key.data).buffer; + default: + throw new core__namespace.OperationError("format: Must be 'jwk' or 'raw'"); + } + } + static async importKey(format, keyData, algorithm, extractable, keyUsages) { + let key; + switch (format.toLowerCase()) { + case "jwk": + key = jsonSchema.JsonParser.fromJSON(keyData, { targetSchema: AesCryptoKey }); + break; + case "raw": + key = new AesCryptoKey(); + key.data = buffer.Buffer.from(keyData); + break; + default: + throw new core__namespace.OperationError("format: Must be 'jwk' or 'raw'"); + } + key.algorithm = algorithm; + key.algorithm.length = key.data.length << 3; + key.extractable = extractable; + key.usages = keyUsages; + switch (key.algorithm.length) { + case 128: + case 192: + case 256: + break; + default: + throw new core__namespace.OperationError("keyData: Is wrong key length"); + } + return key; + } + static async encrypt(algorithm, key, data) { + switch (algorithm.name.toUpperCase()) { + case "AES-CBC": + return this.encryptAesCBC(algorithm, key, buffer.Buffer.from(data)); + case "AES-CTR": + return this.encryptAesCTR(algorithm, key, buffer.Buffer.from(data)); + case "AES-GCM": + return this.encryptAesGCM(algorithm, key, buffer.Buffer.from(data)); + case "AES-KW": + return this.encryptAesKW(algorithm, key, buffer.Buffer.from(data)); + case "AES-ECB": + return this.encryptAesECB(algorithm, key, buffer.Buffer.from(data)); + default: + throw new core__namespace.OperationError("algorithm: Is not recognized"); + } + } + static async decrypt(algorithm, key, data) { + if (!(key instanceof AesCryptoKey)) { + throw new Error("key: Is not AesCryptoKey"); + } + switch (algorithm.name.toUpperCase()) { + case "AES-CBC": + return this.decryptAesCBC(algorithm, key, buffer.Buffer.from(data)); + case "AES-CTR": + return this.decryptAesCTR(algorithm, key, buffer.Buffer.from(data)); + case "AES-GCM": + return this.decryptAesGCM(algorithm, key, buffer.Buffer.from(data)); + case "AES-KW": + return this.decryptAesKW(algorithm, key, buffer.Buffer.from(data)); + case "AES-ECB": + return this.decryptAesECB(algorithm, key, buffer.Buffer.from(data)); + default: + throw new core__namespace.OperationError("algorithm: Is not recognized"); + } + } + static async encryptAesCBC(algorithm, key, data) { + const cipher = crypto.createCipheriv(`aes-${key.algorithm.length}-cbc`, key.data, new Uint8Array(algorithm.iv)); + let enc = cipher.update(data); + enc = buffer.Buffer.concat([enc, cipher.final()]); + const res = new Uint8Array(enc).buffer; + return res; + } + static async decryptAesCBC(algorithm, key, data) { + const decipher = crypto.createDecipheriv(`aes-${key.algorithm.length}-cbc`, key.data, new Uint8Array(algorithm.iv)); + let dec = decipher.update(data); + dec = buffer.Buffer.concat([dec, decipher.final()]); + return new Uint8Array(dec).buffer; + } + static async encryptAesCTR(algorithm, key, data) { + const cipher = crypto.createCipheriv(`aes-${key.algorithm.length}-ctr`, key.data, buffer.Buffer.from(algorithm.counter)); + let enc = cipher.update(data); + enc = buffer.Buffer.concat([enc, cipher.final()]); + const res = new Uint8Array(enc).buffer; + return res; + } + static async decryptAesCTR(algorithm, key, data) { + const decipher = crypto.createDecipheriv(`aes-${key.algorithm.length}-ctr`, key.data, new Uint8Array(algorithm.counter)); + let dec = decipher.update(data); + dec = buffer.Buffer.concat([dec, decipher.final()]); + return new Uint8Array(dec).buffer; + } + static async encryptAesGCM(algorithm, key, data) { + const cipher = crypto.createCipheriv(`aes-${key.algorithm.length}-gcm`, key.data, buffer.Buffer.from(algorithm.iv), { + authTagLength: (algorithm.tagLength || 128) >> 3, + }); + if (algorithm.additionalData) { + cipher.setAAD(buffer.Buffer.from(algorithm.additionalData)); + } + let enc = cipher.update(data); + enc = buffer.Buffer.concat([enc, cipher.final(), cipher.getAuthTag()]); + const res = new Uint8Array(enc).buffer; + return res; + } + static async decryptAesGCM(algorithm, key, data) { + const tagLength = (algorithm.tagLength || 128) >> 3; + const decipher = crypto.createDecipheriv(`aes-${key.algorithm.length}-gcm`, key.data, new Uint8Array(algorithm.iv), { + authTagLength: tagLength, + }); + const enc = data.slice(0, data.length - tagLength); + const tag = data.slice(data.length - tagLength); + if (algorithm.additionalData) { + decipher.setAAD(buffer.Buffer.from(algorithm.additionalData)); + } + decipher.setAuthTag(tag); + let dec = decipher.update(enc); + dec = buffer.Buffer.concat([dec, decipher.final()]); + return new Uint8Array(dec).buffer; + } + static async encryptAesKW(algorithm, key, data) { + const cipher = crypto.createCipheriv(`id-aes${key.algorithm.length}-wrap`, key.data, this.AES_KW_IV); + let enc = cipher.update(data); + enc = buffer.Buffer.concat([enc, cipher.final()]); + return new Uint8Array(enc).buffer; + } + static async decryptAesKW(algorithm, key, data) { + const decipher = crypto.createDecipheriv(`id-aes${key.algorithm.length}-wrap`, key.data, this.AES_KW_IV); + let dec = decipher.update(data); + dec = buffer.Buffer.concat([dec, decipher.final()]); + return new Uint8Array(dec).buffer; + } + static async encryptAesECB(algorithm, key, data) { + const cipher = crypto.createCipheriv(`aes-${key.algorithm.length}-ecb`, key.data, new Uint8Array(0)); + let enc = cipher.update(data); + enc = buffer.Buffer.concat([enc, cipher.final()]); + const res = new Uint8Array(enc).buffer; + return res; + } + static async decryptAesECB(algorithm, key, data) { + const decipher = crypto.createDecipheriv(`aes-${key.algorithm.length}-ecb`, key.data, new Uint8Array(0)); + let dec = decipher.update(data); + dec = buffer.Buffer.concat([dec, decipher.final()]); + return new Uint8Array(dec).buffer; + } +} +AesCrypto.AES_KW_IV = buffer.Buffer.from("A6A6A6A6A6A6A6A6", "hex"); + +const keyStorage = new WeakMap(); +function getCryptoKey(key) { + const res = keyStorage.get(key); + if (!res) { + throw new core__namespace.OperationError("Cannot get CryptoKey from secure storage"); + } + return res; +} +function setCryptoKey(value) { + const key = core__namespace.CryptoKey.create(value.algorithm, value.type, value.extractable, value.usages); + Object.freeze(key); + keyStorage.set(key, value); + return key; +} + +class AesCbcProvider extends core__namespace.AesCbcProvider { + async onGenerateKey(algorithm, extractable, keyUsages) { + const key = await AesCrypto.generateKey({ + name: this.name, + length: algorithm.length, + }, extractable, keyUsages); + return setCryptoKey(key); + } + async onEncrypt(algorithm, key, data) { + return AesCrypto.encrypt(algorithm, getCryptoKey(key), new Uint8Array(data)); + } + async onDecrypt(algorithm, key, data) { + return AesCrypto.decrypt(algorithm, getCryptoKey(key), new Uint8Array(data)); + } + async onExportKey(format, key) { + return AesCrypto.exportKey(format, getCryptoKey(key)); + } + async onImportKey(format, keyData, algorithm, extractable, keyUsages) { + const key = await AesCrypto.importKey(format, keyData, { name: algorithm.name }, extractable, keyUsages); + return setCryptoKey(key); + } + checkCryptoKey(key, keyUsage) { + super.checkCryptoKey(key, keyUsage); + if (!(getCryptoKey(key) instanceof AesCryptoKey)) { + throw new TypeError("key: Is not a AesCryptoKey"); + } + } +} + +const zero = buffer.Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); +const rb = buffer.Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 135]); +const blockSize = 16; +function bitShiftLeft(buffer$1) { + const shifted = buffer.Buffer.alloc(buffer$1.length); + const last = buffer$1.length - 1; + for (let index = 0; index < last; index++) { + shifted[index] = buffer$1[index] << 1; + if (buffer$1[index + 1] & 0x80) { + shifted[index] += 0x01; + } + } + shifted[last] = buffer$1[last] << 1; + return shifted; +} +function xor(a, b) { + const length = Math.min(a.length, b.length); + const output = buffer.Buffer.alloc(length); + for (let index = 0; index < length; index++) { + output[index] = a[index] ^ b[index]; + } + return output; +} +function aes(key, message) { + const cipher = crypto.createCipheriv(`aes${key.length << 3}`, key, zero); + const result = cipher.update(message); + cipher.final(); + return result; +} +function getMessageBlock(message, blockIndex) { + const block = buffer.Buffer.alloc(blockSize); + const start = blockIndex * blockSize; + const end = start + blockSize; + message.copy(block, 0, start, end); + return block; +} +function getPaddedMessageBlock(message, blockIndex) { + const block = buffer.Buffer.alloc(blockSize); + const start = blockIndex * blockSize; + const end = message.length; + block.fill(0); + message.copy(block, 0, start, end); + block[end - start] = 0x80; + return block; +} +function generateSubkeys(key) { + const l = aes(key, zero); + let subkey1 = bitShiftLeft(l); + if (l[0] & 0x80) { + subkey1 = xor(subkey1, rb); + } + let subkey2 = bitShiftLeft(subkey1); + if (subkey1[0] & 0x80) { + subkey2 = xor(subkey2, rb); + } + return { subkey1, subkey2 }; +} +function aesCmac(key, message) { + const subkeys = generateSubkeys(key); + let blockCount = Math.ceil(message.length / blockSize); + let lastBlockCompleteFlag; + let lastBlock; + if (blockCount === 0) { + blockCount = 1; + lastBlockCompleteFlag = false; + } + else { + lastBlockCompleteFlag = (message.length % blockSize === 0); + } + const lastBlockIndex = blockCount - 1; + if (lastBlockCompleteFlag) { + lastBlock = xor(getMessageBlock(message, lastBlockIndex), subkeys.subkey1); + } + else { + lastBlock = xor(getPaddedMessageBlock(message, lastBlockIndex), subkeys.subkey2); + } + let x = zero; + let y; + for (let index = 0; index < lastBlockIndex; index++) { + y = xor(x, getMessageBlock(message, index)); + x = aes(key, y); + } + y = xor(lastBlock, x); + return aes(key, y); +} +class AesCmacProvider extends core__namespace.AesCmacProvider { + async onGenerateKey(algorithm, extractable, keyUsages) { + const key = await AesCrypto.generateKey({ + name: this.name, + length: algorithm.length, + }, extractable, keyUsages); + return setCryptoKey(key); + } + async onSign(algorithm, key, data) { + const result = aesCmac(getCryptoKey(key).data, buffer.Buffer.from(data)); + return new Uint8Array(result).buffer; + } + async onVerify(algorithm, key, signature, data) { + const signature2 = await this.sign(algorithm, key, data); + return buffer.Buffer.from(signature).compare(buffer.Buffer.from(signature2)) === 0; + } + async onExportKey(format, key) { + return AesCrypto.exportKey(format, getCryptoKey(key)); + } + async onImportKey(format, keyData, algorithm, extractable, keyUsages) { + const res = await AesCrypto.importKey(format, keyData, { name: algorithm.name }, extractable, keyUsages); + return setCryptoKey(res); + } + checkCryptoKey(key, keyUsage) { + super.checkCryptoKey(key, keyUsage); + if (!(getCryptoKey(key) instanceof AesCryptoKey)) { + throw new TypeError("key: Is not a AesCryptoKey"); + } + } +} + +class AesCtrProvider extends core__namespace.AesCtrProvider { + async onGenerateKey(algorithm, extractable, keyUsages) { + const key = await AesCrypto.generateKey({ + name: this.name, + length: algorithm.length, + }, extractable, keyUsages); + return setCryptoKey(key); + } + async onEncrypt(algorithm, key, data) { + return AesCrypto.encrypt(algorithm, getCryptoKey(key), new Uint8Array(data)); + } + async onDecrypt(algorithm, key, data) { + return AesCrypto.decrypt(algorithm, getCryptoKey(key), new Uint8Array(data)); + } + async onExportKey(format, key) { + return AesCrypto.exportKey(format, getCryptoKey(key)); + } + async onImportKey(format, keyData, algorithm, extractable, keyUsages) { + const res = await AesCrypto.importKey(format, keyData, { name: algorithm.name }, extractable, keyUsages); + return setCryptoKey(res); + } + checkCryptoKey(key, keyUsage) { + super.checkCryptoKey(key, keyUsage); + if (!(getCryptoKey(key) instanceof AesCryptoKey)) { + throw new TypeError("key: Is not a AesCryptoKey"); + } + } +} + +class AesGcmProvider extends core__namespace.AesGcmProvider { + async onGenerateKey(algorithm, extractable, keyUsages) { + const key = await AesCrypto.generateKey({ + name: this.name, + length: algorithm.length, + }, extractable, keyUsages); + return setCryptoKey(key); + } + async onEncrypt(algorithm, key, data) { + return AesCrypto.encrypt(algorithm, getCryptoKey(key), new Uint8Array(data)); + } + async onDecrypt(algorithm, key, data) { + return AesCrypto.decrypt(algorithm, getCryptoKey(key), new Uint8Array(data)); + } + async onExportKey(format, key) { + return AesCrypto.exportKey(format, getCryptoKey(key)); + } + async onImportKey(format, keyData, algorithm, extractable, keyUsages) { + const res = await AesCrypto.importKey(format, keyData, { name: algorithm.name }, extractable, keyUsages); + return setCryptoKey(res); + } + checkCryptoKey(key, keyUsage) { + super.checkCryptoKey(key, keyUsage); + if (!(getCryptoKey(key) instanceof AesCryptoKey)) { + throw new TypeError("key: Is not a AesCryptoKey"); + } + } +} + +class AesKwProvider extends core__namespace.AesKwProvider { + async onGenerateKey(algorithm, extractable, keyUsages) { + const res = await AesCrypto.generateKey({ + name: this.name, + length: algorithm.length, + }, extractable, keyUsages); + return setCryptoKey(res); + } + async onExportKey(format, key) { + return AesCrypto.exportKey(format, getCryptoKey(key)); + } + async onImportKey(format, keyData, algorithm, extractable, keyUsages) { + const res = await AesCrypto.importKey(format, keyData, { name: algorithm.name }, extractable, keyUsages); + return setCryptoKey(res); + } + async onEncrypt(algorithm, key, data) { + return AesCrypto.encrypt(algorithm, getCryptoKey(key), new Uint8Array(data)); + } + async onDecrypt(algorithm, key, data) { + return AesCrypto.decrypt(algorithm, getCryptoKey(key), new Uint8Array(data)); + } + checkCryptoKey(key, keyUsage) { + super.checkCryptoKey(key, keyUsage); + if (!(getCryptoKey(key) instanceof AesCryptoKey)) { + throw new TypeError("key: Is not a AesCryptoKey"); + } + } +} + +class AesEcbProvider extends core__namespace.AesEcbProvider { + async onGenerateKey(algorithm, extractable, keyUsages) { + const key = await AesCrypto.generateKey({ + name: this.name, + length: algorithm.length, + }, extractable, keyUsages); + return setCryptoKey(key); + } + async onEncrypt(algorithm, key, data) { + return AesCrypto.encrypt(algorithm, getCryptoKey(key), new Uint8Array(data)); + } + async onDecrypt(algorithm, key, data) { + return AesCrypto.decrypt(algorithm, getCryptoKey(key), new Uint8Array(data)); + } + async onExportKey(format, key) { + return AesCrypto.exportKey(format, getCryptoKey(key)); + } + async onImportKey(format, keyData, algorithm, extractable, keyUsages) { + const res = await AesCrypto.importKey(format, keyData, { name: algorithm.name }, extractable, keyUsages); + return setCryptoKey(res); + } + checkCryptoKey(key, keyUsage) { + super.checkCryptoKey(key, keyUsage); + if (!(getCryptoKey(key) instanceof AesCryptoKey)) { + throw new TypeError("key: Is not a AesCryptoKey"); + } + } +} + +class DesCryptoKey extends SymmetricKey { + get alg() { + switch (this.algorithm.name.toUpperCase()) { + case "DES-CBC": + return `DES-CBC`; + case "DES-EDE3-CBC": + return `3DES-CBC`; + default: + throw new core__namespace.AlgorithmError("Unsupported algorithm name"); + } + } + set alg(value) { + } +} +tslib.__decorate([ + jsonSchema.JsonProp({ name: "k", converter: JsonBase64UrlConverter }) +], DesCryptoKey.prototype, "data", void 0); + +class DesCrypto { + static async generateKey(algorithm, extractable, keyUsages) { + const key = new DesCryptoKey(); + key.algorithm = algorithm; + key.extractable = extractable; + key.usages = keyUsages; + key.data = crypto.randomBytes(algorithm.length >> 3); + return key; + } + static async exportKey(format, key) { + switch (format.toLowerCase()) { + case "jwk": + return jsonSchema.JsonSerializer.toJSON(key); + case "raw": + return new Uint8Array(key.data).buffer; + default: + throw new core__namespace.OperationError("format: Must be 'jwk' or 'raw'"); + } + } + static async importKey(format, keyData, algorithm, extractable, keyUsages) { + let key; + switch (format.toLowerCase()) { + case "jwk": + key = jsonSchema.JsonParser.fromJSON(keyData, { targetSchema: DesCryptoKey }); + break; + case "raw": + key = new DesCryptoKey(); + key.data = buffer.Buffer.from(keyData); + break; + default: + throw new core__namespace.OperationError("format: Must be 'jwk' or 'raw'"); + } + key.algorithm = algorithm; + key.extractable = extractable; + key.usages = keyUsages; + return key; + } + static async encrypt(algorithm, key, data) { + switch (algorithm.name.toUpperCase()) { + case "DES-CBC": + return this.encryptDesCBC(algorithm, key, buffer.Buffer.from(data)); + case "DES-EDE3-CBC": + return this.encryptDesEDE3CBC(algorithm, key, buffer.Buffer.from(data)); + default: + throw new core__namespace.OperationError("algorithm: Is not recognized"); + } + } + static async decrypt(algorithm, key, data) { + if (!(key instanceof DesCryptoKey)) { + throw new Error("key: Is not DesCryptoKey"); + } + switch (algorithm.name.toUpperCase()) { + case "DES-CBC": + return this.decryptDesCBC(algorithm, key, buffer.Buffer.from(data)); + case "DES-EDE3-CBC": + return this.decryptDesEDE3CBC(algorithm, key, buffer.Buffer.from(data)); + default: + throw new core__namespace.OperationError("algorithm: Is not recognized"); + } + } + static async encryptDesCBC(algorithm, key, data) { + const cipher = crypto.createCipheriv(`des-cbc`, key.data, new Uint8Array(algorithm.iv)); + let enc = cipher.update(data); + enc = buffer.Buffer.concat([enc, cipher.final()]); + const res = new Uint8Array(enc).buffer; + return res; + } + static async decryptDesCBC(algorithm, key, data) { + const decipher = crypto.createDecipheriv(`des-cbc`, key.data, new Uint8Array(algorithm.iv)); + let dec = decipher.update(data); + dec = buffer.Buffer.concat([dec, decipher.final()]); + return new Uint8Array(dec).buffer; + } + static async encryptDesEDE3CBC(algorithm, key, data) { + const cipher = crypto.createCipheriv(`des-ede3-cbc`, key.data, buffer.Buffer.from(algorithm.iv)); + let enc = cipher.update(data); + enc = buffer.Buffer.concat([enc, cipher.final()]); + const res = new Uint8Array(enc).buffer; + return res; + } + static async decryptDesEDE3CBC(algorithm, key, data) { + const decipher = crypto.createDecipheriv(`des-ede3-cbc`, key.data, new Uint8Array(algorithm.iv)); + let dec = decipher.update(data); + dec = buffer.Buffer.concat([dec, decipher.final()]); + return new Uint8Array(dec).buffer; + } +} + +class DesCbcProvider extends core__namespace.DesProvider { + constructor() { + super(...arguments); + this.keySizeBits = 64; + this.ivSize = 8; + this.name = "DES-CBC"; + } + async onGenerateKey(algorithm, extractable, keyUsages) { + const key = await DesCrypto.generateKey({ + name: this.name, + length: this.keySizeBits, + }, extractable, keyUsages); + return setCryptoKey(key); + } + async onEncrypt(algorithm, key, data) { + return DesCrypto.encrypt(algorithm, getCryptoKey(key), new Uint8Array(data)); + } + async onDecrypt(algorithm, key, data) { + return DesCrypto.decrypt(algorithm, getCryptoKey(key), new Uint8Array(data)); + } + async onExportKey(format, key) { + return DesCrypto.exportKey(format, getCryptoKey(key)); + } + async onImportKey(format, keyData, algorithm, extractable, keyUsages) { + const key = await DesCrypto.importKey(format, keyData, { name: this.name, length: this.keySizeBits }, extractable, keyUsages); + if (key.data.length !== (this.keySizeBits >> 3)) { + throw new core__namespace.OperationError("keyData: Wrong key size"); + } + return setCryptoKey(key); + } + checkCryptoKey(key, keyUsage) { + super.checkCryptoKey(key, keyUsage); + if (!(getCryptoKey(key) instanceof DesCryptoKey)) { + throw new TypeError("key: Is not a DesCryptoKey"); + } + } +} + +class DesEde3CbcProvider extends core__namespace.DesProvider { + constructor() { + super(...arguments); + this.keySizeBits = 192; + this.ivSize = 8; + this.name = "DES-EDE3-CBC"; + } + async onGenerateKey(algorithm, extractable, keyUsages) { + const key = await DesCrypto.generateKey({ + name: this.name, + length: this.keySizeBits, + }, extractable, keyUsages); + return setCryptoKey(key); + } + async onEncrypt(algorithm, key, data) { + return DesCrypto.encrypt(algorithm, getCryptoKey(key), new Uint8Array(data)); + } + async onDecrypt(algorithm, key, data) { + return DesCrypto.decrypt(algorithm, getCryptoKey(key), new Uint8Array(data)); + } + async onExportKey(format, key) { + return DesCrypto.exportKey(format, getCryptoKey(key)); + } + async onImportKey(format, keyData, algorithm, extractable, keyUsages) { + const key = await DesCrypto.importKey(format, keyData, { name: this.name, length: this.keySizeBits }, extractable, keyUsages); + if (key.data.length !== (this.keySizeBits >> 3)) { + throw new core__namespace.OperationError("keyData: Wrong key size"); + } + return setCryptoKey(key); + } + checkCryptoKey(key, keyUsage) { + super.checkCryptoKey(key, keyUsage); + if (!(getCryptoKey(key) instanceof DesCryptoKey)) { + throw new TypeError("key: Is not a DesCryptoKey"); + } + } +} + +function getJwkAlgorithm(algorithm) { + switch (algorithm.name.toUpperCase()) { + case "RSA-OAEP": { + const mdSize = /(\d+)$/.exec(algorithm.hash.name)[1]; + return `RSA-OAEP${mdSize !== "1" ? `-${mdSize}` : ""}`; + } + case "RSASSA-PKCS1-V1_5": + return `RS${/(\d+)$/.exec(algorithm.hash.name)[1]}`; + case "RSA-PSS": + return `PS${/(\d+)$/.exec(algorithm.hash.name)[1]}`; + case "RSA-PKCS1": + return `RS1`; + default: + throw new core__namespace.OperationError("algorithm: Is not recognized"); + } +} + +class RsaPrivateKey extends AsymmetricKey { + constructor() { + super(...arguments); + this.type = "private"; + } + getKey() { + const keyInfo = asn1Schema.AsnParser.parse(this.data, core__namespace.asn1.PrivateKeyInfo); + return asn1Schema.AsnParser.parse(keyInfo.privateKey, core__namespace.asn1.RsaPrivateKey); + } + toJSON() { + const key = this.getKey(); + const json = { + kty: "RSA", + alg: getJwkAlgorithm(this.algorithm), + key_ops: this.usages, + ext: this.extractable, + }; + return Object.assign(json, jsonSchema.JsonSerializer.toJSON(key)); + } + fromJSON(json) { + const key = jsonSchema.JsonParser.fromJSON(json, { targetSchema: core__namespace.asn1.RsaPrivateKey }); + const keyInfo = new core__namespace.asn1.PrivateKeyInfo(); + keyInfo.privateKeyAlgorithm.algorithm = "1.2.840.113549.1.1.1"; + keyInfo.privateKeyAlgorithm.parameters = null; + keyInfo.privateKey = asn1Schema.AsnSerializer.serialize(key); + this.data = buffer.Buffer.from(asn1Schema.AsnSerializer.serialize(keyInfo)); + } +} + +class RsaPublicKey extends AsymmetricKey { + constructor() { + super(...arguments); + this.type = "public"; + } + getKey() { + const keyInfo = asn1Schema.AsnParser.parse(this.data, core__namespace.asn1.PublicKeyInfo); + return asn1Schema.AsnParser.parse(keyInfo.publicKey, core__namespace.asn1.RsaPublicKey); + } + toJSON() { + const key = this.getKey(); + const json = { + kty: "RSA", + alg: getJwkAlgorithm(this.algorithm), + key_ops: this.usages, + ext: this.extractable, + }; + return Object.assign(json, jsonSchema.JsonSerializer.toJSON(key)); + } + fromJSON(json) { + const key = jsonSchema.JsonParser.fromJSON(json, { targetSchema: core__namespace.asn1.RsaPublicKey }); + const keyInfo = new core__namespace.asn1.PublicKeyInfo(); + keyInfo.publicKeyAlgorithm.algorithm = "1.2.840.113549.1.1.1"; + keyInfo.publicKeyAlgorithm.parameters = null; + keyInfo.publicKey = asn1Schema.AsnSerializer.serialize(key); + this.data = buffer.Buffer.from(asn1Schema.AsnSerializer.serialize(keyInfo)); + } +} + +class RsaCrypto { + static async generateKey(algorithm, extractable, keyUsages) { + const privateKey = new RsaPrivateKey(); + privateKey.algorithm = algorithm; + privateKey.extractable = extractable; + privateKey.usages = keyUsages.filter((usage) => this.privateKeyUsages.indexOf(usage) !== -1); + const publicKey = new RsaPublicKey(); + publicKey.algorithm = algorithm; + publicKey.extractable = true; + publicKey.usages = keyUsages.filter((usage) => this.publicKeyUsages.indexOf(usage) !== -1); + const publicExponent = buffer.Buffer.concat([ + buffer.Buffer.alloc(4 - algorithm.publicExponent.byteLength, 0), + buffer.Buffer.from(algorithm.publicExponent), + ]).readInt32BE(0); + const keys = crypto.generateKeyPairSync("rsa", { + modulusLength: algorithm.modulusLength, + publicExponent, + publicKeyEncoding: { + format: "der", + type: "spki", + }, + privateKeyEncoding: { + format: "der", + type: "pkcs8", + }, + }); + privateKey.data = keys.privateKey; + publicKey.data = keys.publicKey; + const res = { + privateKey, + publicKey, + }; + return res; + } + static async exportKey(format, key) { + switch (format.toLowerCase()) { + case "jwk": + return jsonSchema.JsonSerializer.toJSON(key); + case "pkcs8": + case "spki": + return new Uint8Array(key.data).buffer; + default: + throw new core__namespace.OperationError("format: Must be 'jwk', 'pkcs8' or 'spki'"); + } + } + static async importKey(format, keyData, algorithm, extractable, keyUsages) { + switch (format.toLowerCase()) { + case "jwk": { + const jwk = keyData; + if (jwk.d) { + const asnKey = jsonSchema.JsonParser.fromJSON(keyData, { targetSchema: core__namespace.asn1.RsaPrivateKey }); + return this.importPrivateKey(asnKey, algorithm, extractable, keyUsages); + } + else { + const asnKey = jsonSchema.JsonParser.fromJSON(keyData, { targetSchema: core__namespace.asn1.RsaPublicKey }); + return this.importPublicKey(asnKey, algorithm, extractable, keyUsages); + } + } + case "spki": { + const keyInfo = asn1Schema.AsnParser.parse(new Uint8Array(keyData), core__namespace.asn1.PublicKeyInfo); + const asnKey = asn1Schema.AsnParser.parse(keyInfo.publicKey, core__namespace.asn1.RsaPublicKey); + return this.importPublicKey(asnKey, algorithm, extractable, keyUsages); + } + case "pkcs8": { + const keyInfo = asn1Schema.AsnParser.parse(new Uint8Array(keyData), core__namespace.asn1.PrivateKeyInfo); + const asnKey = asn1Schema.AsnParser.parse(keyInfo.privateKey, core__namespace.asn1.RsaPrivateKey); + return this.importPrivateKey(asnKey, algorithm, extractable, keyUsages); + } + default: + throw new core__namespace.OperationError("format: Must be 'jwk', 'pkcs8' or 'spki'"); + } + } + static async sign(algorithm, key, data) { + switch (algorithm.name.toUpperCase()) { + case "RSA-PSS": + case "RSASSA-PKCS1-V1_5": + return this.signRsa(algorithm, key, data); + default: + throw new core__namespace.OperationError("algorithm: Is not recognized"); + } + } + static async verify(algorithm, key, signature, data) { + switch (algorithm.name.toUpperCase()) { + case "RSA-PSS": + case "RSASSA-PKCS1-V1_5": + return this.verifySSA(algorithm, key, data, signature); + default: + throw new core__namespace.OperationError("algorithm: Is not recognized"); + } + } + static async encrypt(algorithm, key, data) { + switch (algorithm.name.toUpperCase()) { + case "RSA-OAEP": + return this.encryptOAEP(algorithm, key, data); + default: + throw new core__namespace.OperationError("algorithm: Is not recognized"); + } + } + static async decrypt(algorithm, key, data) { + switch (algorithm.name.toUpperCase()) { + case "RSA-OAEP": + return this.decryptOAEP(algorithm, key, data); + default: + throw new core__namespace.OperationError("algorithm: Is not recognized"); + } + } + static importPrivateKey(asnKey, algorithm, extractable, keyUsages) { + const keyInfo = new core__namespace.asn1.PrivateKeyInfo(); + keyInfo.privateKeyAlgorithm.algorithm = "1.2.840.113549.1.1.1"; + keyInfo.privateKeyAlgorithm.parameters = null; + keyInfo.privateKey = asn1Schema.AsnSerializer.serialize(asnKey); + const key = new RsaPrivateKey(); + key.data = buffer.Buffer.from(asn1Schema.AsnSerializer.serialize(keyInfo)); + key.algorithm = Object.assign({}, algorithm); + key.algorithm.publicExponent = new Uint8Array(asnKey.publicExponent); + key.algorithm.modulusLength = asnKey.modulus.byteLength << 3; + key.extractable = extractable; + key.usages = keyUsages; + return key; + } + static importPublicKey(asnKey, algorithm, extractable, keyUsages) { + const keyInfo = new core__namespace.asn1.PublicKeyInfo(); + keyInfo.publicKeyAlgorithm.algorithm = "1.2.840.113549.1.1.1"; + keyInfo.publicKeyAlgorithm.parameters = null; + keyInfo.publicKey = asn1Schema.AsnSerializer.serialize(asnKey); + const key = new RsaPublicKey(); + key.data = buffer.Buffer.from(asn1Schema.AsnSerializer.serialize(keyInfo)); + key.algorithm = Object.assign({}, algorithm); + key.algorithm.publicExponent = new Uint8Array(asnKey.publicExponent); + key.algorithm.modulusLength = asnKey.modulus.byteLength << 3; + key.extractable = extractable; + key.usages = keyUsages; + return key; + } + static getCryptoAlgorithm(alg) { + switch (alg.hash.name.toUpperCase()) { + case "SHA-1": + return "RSA-SHA1"; + case "SHA-256": + return "RSA-SHA256"; + case "SHA-384": + return "RSA-SHA384"; + case "SHA-512": + return "RSA-SHA512"; + case "SHA3-256": + return "RSA-SHA3-256"; + case "SHA3-384": + return "RSA-SHA3-384"; + case "SHA3-512": + return "RSA-SHA3-512"; + default: + throw new core__namespace.OperationError("algorithm.hash: Is not recognized"); + } + } + static signRsa(algorithm, key, data) { + const cryptoAlg = this.getCryptoAlgorithm(key.algorithm); + const signer = crypto.createSign(cryptoAlg); + signer.update(buffer.Buffer.from(data)); + if (!key.pem) { + key.pem = `-----BEGIN PRIVATE KEY-----\n${key.data.toString("base64")}\n-----END PRIVATE KEY-----`; + } + const options = { + key: key.pem, + }; + if (algorithm.name.toUpperCase() === "RSA-PSS") { + options.padding = crypto.constants.RSA_PKCS1_PSS_PADDING; + options.saltLength = algorithm.saltLength; + } + const signature = signer.sign(options); + return new Uint8Array(signature).buffer; + } + static verifySSA(algorithm, key, data, signature) { + const cryptoAlg = this.getCryptoAlgorithm(key.algorithm); + const signer = crypto.createVerify(cryptoAlg); + signer.update(buffer.Buffer.from(data)); + if (!key.pem) { + key.pem = `-----BEGIN PUBLIC KEY-----\n${key.data.toString("base64")}\n-----END PUBLIC KEY-----`; + } + const options = { + key: key.pem, + }; + if (algorithm.name.toUpperCase() === "RSA-PSS") { + options.padding = crypto.constants.RSA_PKCS1_PSS_PADDING; + options.saltLength = algorithm.saltLength; + } + const ok = signer.verify(options, signature); + return ok; + } + static encryptOAEP(algorithm, key, data) { + const options = { + key: `-----BEGIN PUBLIC KEY-----\n${key.data.toString("base64")}\n-----END PUBLIC KEY-----`, + padding: crypto.constants.RSA_PKCS1_OAEP_PADDING, + }; + if (algorithm.label) ; + return new Uint8Array(crypto.publicEncrypt(options, data)).buffer; + } + static decryptOAEP(algorithm, key, data) { + const options = { + key: `-----BEGIN PRIVATE KEY-----\n${key.data.toString("base64")}\n-----END PRIVATE KEY-----`, + padding: crypto.constants.RSA_PKCS1_OAEP_PADDING, + }; + if (algorithm.label) ; + return new Uint8Array(crypto.privateDecrypt(options, data)).buffer; + } +} +RsaCrypto.publicKeyUsages = ["verify", "encrypt", "wrapKey"]; +RsaCrypto.privateKeyUsages = ["sign", "decrypt", "unwrapKey"]; + +class RsaSsaProvider extends core__namespace.RsaSsaProvider { + constructor() { + super(...arguments); + this.hashAlgorithms = [ + "SHA-1", "SHA-256", "SHA-384", "SHA-512", + "shake128", "shake256", + "SHA3-256", "SHA3-384", "SHA3-512" + ]; + } + async onGenerateKey(algorithm, extractable, keyUsages) { + const keys = await RsaCrypto.generateKey({ + ...algorithm, + name: this.name, + }, extractable, keyUsages); + return { + privateKey: setCryptoKey(keys.privateKey), + publicKey: setCryptoKey(keys.publicKey), + }; + } + async onSign(algorithm, key, data) { + return RsaCrypto.sign(algorithm, getCryptoKey(key), new Uint8Array(data)); + } + async onVerify(algorithm, key, signature, data) { + return RsaCrypto.verify(algorithm, getCryptoKey(key), new Uint8Array(signature), new Uint8Array(data)); + } + async onExportKey(format, key) { + return RsaCrypto.exportKey(format, getCryptoKey(key)); + } + async onImportKey(format, keyData, algorithm, extractable, keyUsages) { + const key = await RsaCrypto.importKey(format, keyData, { ...algorithm, name: this.name }, extractable, keyUsages); + return setCryptoKey(key); + } + checkCryptoKey(key, keyUsage) { + super.checkCryptoKey(key, keyUsage); + const internalKey = getCryptoKey(key); + if (!(internalKey instanceof RsaPrivateKey || internalKey instanceof RsaPublicKey)) { + throw new TypeError("key: Is not RSA CryptoKey"); + } + } +} + +class RsaPssProvider extends core__namespace.RsaPssProvider { + constructor() { + super(...arguments); + this.hashAlgorithms = [ + "SHA-1", "SHA-256", "SHA-384", "SHA-512", + "shake128", "shake256", + "SHA3-256", "SHA3-384", "SHA3-512" + ]; + } + async onGenerateKey(algorithm, extractable, keyUsages) { + const keys = await RsaCrypto.generateKey({ + ...algorithm, + name: this.name, + }, extractable, keyUsages); + return { + privateKey: setCryptoKey(keys.privateKey), + publicKey: setCryptoKey(keys.publicKey), + }; + } + async onSign(algorithm, key, data) { + return RsaCrypto.sign(algorithm, getCryptoKey(key), new Uint8Array(data)); + } + async onVerify(algorithm, key, signature, data) { + return RsaCrypto.verify(algorithm, getCryptoKey(key), new Uint8Array(signature), new Uint8Array(data)); + } + async onExportKey(format, key) { + return RsaCrypto.exportKey(format, getCryptoKey(key)); + } + async onImportKey(format, keyData, algorithm, extractable, keyUsages) { + const key = await RsaCrypto.importKey(format, keyData, { ...algorithm, name: this.name }, extractable, keyUsages); + return setCryptoKey(key); + } + checkCryptoKey(key, keyUsage) { + super.checkCryptoKey(key, keyUsage); + const internalKey = getCryptoKey(key); + if (!(internalKey instanceof RsaPrivateKey || internalKey instanceof RsaPublicKey)) { + throw new TypeError("key: Is not RSA CryptoKey"); + } + } +} + +class ShaCrypto { + static size(algorithm) { + switch (algorithm.name.toUpperCase()) { + case "SHA-1": + return 160; + case "SHA-256": + case "SHA3-256": + return 256; + case "SHA-384": + case "SHA3-384": + return 384; + case "SHA-512": + case "SHA3-512": + return 512; + default: + throw new Error("Unrecognized name"); + } + } + static getAlgorithmName(algorithm) { + switch (algorithm.name.toUpperCase()) { + case "SHA-1": + return "sha1"; + case "SHA-256": + return "sha256"; + case "SHA-384": + return "sha384"; + case "SHA-512": + return "sha512"; + case "SHA3-256": + return "sha3-256"; + case "SHA3-384": + return "sha3-384"; + case "SHA3-512": + return "sha3-512"; + default: + throw new Error("Unrecognized name"); + } + } + static digest(algorithm, data) { + const hashAlg = this.getAlgorithmName(algorithm); + const hash = crypto.createHash(hashAlg) + .update(buffer.Buffer.from(data)).digest(); + return new Uint8Array(hash).buffer; + } +} + +class RsaOaepProvider extends core__namespace.RsaOaepProvider { + async onGenerateKey(algorithm, extractable, keyUsages) { + const keys = await RsaCrypto.generateKey({ + ...algorithm, + name: this.name, + }, extractable, keyUsages); + return { + privateKey: setCryptoKey(keys.privateKey), + publicKey: setCryptoKey(keys.publicKey), + }; + } + async onEncrypt(algorithm, key, data) { + const internalKey = getCryptoKey(key); + const dataView = new Uint8Array(data); + const keySize = Math.ceil(internalKey.algorithm.modulusLength >> 3); + const hashSize = ShaCrypto.size(internalKey.algorithm.hash) >> 3; + const dataLength = dataView.byteLength; + const psLength = keySize - dataLength - 2 * hashSize - 2; + if (dataLength > keySize - 2 * hashSize - 2) { + throw new Error("Data too large"); + } + const message = new Uint8Array(keySize); + const seed = message.subarray(1, hashSize + 1); + const dataBlock = message.subarray(hashSize + 1); + dataBlock.set(dataView, hashSize + psLength + 1); + const labelHash = crypto.createHash(internalKey.algorithm.hash.name.replace("-", "")) + .update(core__namespace.BufferSourceConverter.toUint8Array(algorithm.label || new Uint8Array(0))) + .digest(); + dataBlock.set(labelHash, 0); + dataBlock[hashSize + psLength] = 1; + crypto.randomFillSync(seed); + const dataBlockMask = this.mgf1(internalKey.algorithm.hash, seed, dataBlock.length); + for (let i = 0; i < dataBlock.length; i++) { + dataBlock[i] ^= dataBlockMask[i]; + } + const seedMask = this.mgf1(internalKey.algorithm.hash, dataBlock, seed.length); + for (let i = 0; i < seed.length; i++) { + seed[i] ^= seedMask[i]; + } + if (!internalKey.pem) { + internalKey.pem = `-----BEGIN PUBLIC KEY-----\n${internalKey.data.toString("base64")}\n-----END PUBLIC KEY-----`; + } + const pkcs0 = crypto.publicEncrypt({ + key: internalKey.pem, + padding: crypto.constants.RSA_NO_PADDING, + }, buffer.Buffer.from(message)); + return new Uint8Array(pkcs0).buffer; + } + async onDecrypt(algorithm, key, data) { + const internalKey = getCryptoKey(key); + const keySize = Math.ceil(internalKey.algorithm.modulusLength >> 3); + const hashSize = ShaCrypto.size(internalKey.algorithm.hash) >> 3; + const dataLength = data.byteLength; + if (dataLength !== keySize) { + throw new Error("Bad data"); + } + if (!internalKey.pem) { + internalKey.pem = `-----BEGIN PRIVATE KEY-----\n${internalKey.data.toString("base64")}\n-----END PRIVATE KEY-----`; + } + let pkcs0 = crypto.privateDecrypt({ + key: internalKey.pem, + padding: crypto.constants.RSA_NO_PADDING, + }, buffer.Buffer.from(data)); + const z = pkcs0[0]; + const seed = pkcs0.subarray(1, hashSize + 1); + const dataBlock = pkcs0.subarray(hashSize + 1); + if (z !== 0) { + throw new Error("Decryption failed"); + } + const seedMask = this.mgf1(internalKey.algorithm.hash, dataBlock, seed.length); + for (let i = 0; i < seed.length; i++) { + seed[i] ^= seedMask[i]; + } + const dataBlockMask = this.mgf1(internalKey.algorithm.hash, seed, dataBlock.length); + for (let i = 0; i < dataBlock.length; i++) { + dataBlock[i] ^= dataBlockMask[i]; + } + const labelHash = crypto.createHash(internalKey.algorithm.hash.name.replace("-", "")) + .update(core__namespace.BufferSourceConverter.toUint8Array(algorithm.label || new Uint8Array(0))) + .digest(); + for (let i = 0; i < hashSize; i++) { + if (labelHash[i] !== dataBlock[i]) { + throw new Error("Decryption failed"); + } + } + let psEnd = hashSize; + for (; psEnd < dataBlock.length; psEnd++) { + const psz = dataBlock[psEnd]; + if (psz === 1) { + break; + } + if (psz !== 0) { + throw new Error("Decryption failed"); + } + } + if (psEnd === dataBlock.length) { + throw new Error("Decryption failed"); + } + pkcs0 = dataBlock.subarray(psEnd + 1); + return new Uint8Array(pkcs0).buffer; + } + async onExportKey(format, key) { + return RsaCrypto.exportKey(format, getCryptoKey(key)); + } + async onImportKey(format, keyData, algorithm, extractable, keyUsages) { + const key = await RsaCrypto.importKey(format, keyData, { ...algorithm, name: this.name }, extractable, keyUsages); + return setCryptoKey(key); + } + checkCryptoKey(key, keyUsage) { + super.checkCryptoKey(key, keyUsage); + const internalKey = getCryptoKey(key); + if (!(internalKey instanceof RsaPrivateKey || internalKey instanceof RsaPublicKey)) { + throw new TypeError("key: Is not RSA CryptoKey"); + } + } + mgf1(algorithm, seed, length = 0) { + const hashSize = ShaCrypto.size(algorithm) >> 3; + const mask = new Uint8Array(length); + const counter = new Uint8Array(4); + const chunks = Math.ceil(length / hashSize); + for (let i = 0; i < chunks; i++) { + counter[0] = i >>> 24; + counter[1] = (i >>> 16) & 255; + counter[2] = (i >>> 8) & 255; + counter[3] = i & 255; + const submask = mask.subarray(i * hashSize); + let chunk = crypto.createHash(algorithm.name.replace("-", "")) + .update(seed) + .update(counter) + .digest(); + if (chunk.length > submask.length) { + chunk = chunk.subarray(0, submask.length); + } + submask.set(chunk); + } + return mask; + } +} + +class RsaEsProvider extends core__namespace.ProviderCrypto { + constructor() { + super(...arguments); + this.name = "RSAES-PKCS1-v1_5"; + this.usages = { + publicKey: ["encrypt", "wrapKey"], + privateKey: ["decrypt", "unwrapKey"], + }; + } + async onGenerateKey(algorithm, extractable, keyUsages) { + const keys = await RsaCrypto.generateKey({ + ...algorithm, + name: this.name, + }, extractable, keyUsages); + return { + privateKey: setCryptoKey(keys.privateKey), + publicKey: setCryptoKey(keys.publicKey), + }; + } + checkGenerateKeyParams(algorithm) { + this.checkRequiredProperty(algorithm, "publicExponent"); + if (!(algorithm.publicExponent && algorithm.publicExponent instanceof Uint8Array)) { + throw new TypeError("publicExponent: Missing or not a Uint8Array"); + } + const publicExponent = pvtsutils.Convert.ToBase64(algorithm.publicExponent); + if (!(publicExponent === "Aw==" || publicExponent === "AQAB")) { + throw new TypeError("publicExponent: Must be [3] or [1,0,1]"); + } + this.checkRequiredProperty(algorithm, "modulusLength"); + switch (algorithm.modulusLength) { + case 1024: + case 2048: + case 4096: + break; + default: + throw new TypeError("modulusLength: Must be 1024, 2048, or 4096"); + } + } + async onEncrypt(algorithm, key, data) { + const options = this.toCryptoOptions(key); + const enc = crypto.publicEncrypt(options, new Uint8Array(data)); + return new Uint8Array(enc).buffer; + } + async onDecrypt(algorithm, key, data) { + const options = this.toCryptoOptions(key); + const dec = crypto.privateDecrypt(options, new Uint8Array(data)); + return new Uint8Array(dec).buffer; + } + async onExportKey(format, key) { + return RsaCrypto.exportKey(format, getCryptoKey(key)); + } + async onImportKey(format, keyData, algorithm, extractable, keyUsages) { + const key = await RsaCrypto.importKey(format, keyData, { ...algorithm, name: this.name }, extractable, keyUsages); + return setCryptoKey(key); + } + checkCryptoKey(key, keyUsage) { + super.checkCryptoKey(key, keyUsage); + const internalKey = getCryptoKey(key); + if (!(internalKey instanceof RsaPrivateKey || internalKey instanceof RsaPublicKey)) { + throw new TypeError("key: Is not RSA CryptoKey"); + } + } + toCryptoOptions(key) { + const type = key.type.toUpperCase(); + return { + key: `-----BEGIN ${type} KEY-----\n${getCryptoKey(key).data.toString("base64")}\n-----END ${type} KEY-----`, + padding: crypto.constants.RSA_PKCS1_PADDING, + }; + } +} + +const namedOIDs = { + "1.2.840.10045.3.1.7": "P-256", + "P-256": "1.2.840.10045.3.1.7", + "1.3.132.0.34": "P-384", + "P-384": "1.3.132.0.34", + "1.3.132.0.35": "P-521", + "P-521": "1.3.132.0.35", + "1.3.132.0.10": "K-256", + "K-256": "1.3.132.0.10", + "brainpoolP160r1": "1.3.36.3.3.2.8.1.1.1", + "1.3.36.3.3.2.8.1.1.1": "brainpoolP160r1", + "brainpoolP160t1": "1.3.36.3.3.2.8.1.1.2", + "1.3.36.3.3.2.8.1.1.2": "brainpoolP160t1", + "brainpoolP192r1": "1.3.36.3.3.2.8.1.1.3", + "1.3.36.3.3.2.8.1.1.3": "brainpoolP192r1", + "brainpoolP192t1": "1.3.36.3.3.2.8.1.1.4", + "1.3.36.3.3.2.8.1.1.4": "brainpoolP192t1", + "brainpoolP224r1": "1.3.36.3.3.2.8.1.1.5", + "1.3.36.3.3.2.8.1.1.5": "brainpoolP224r1", + "brainpoolP224t1": "1.3.36.3.3.2.8.1.1.6", + "1.3.36.3.3.2.8.1.1.6": "brainpoolP224t1", + "brainpoolP256r1": "1.3.36.3.3.2.8.1.1.7", + "1.3.36.3.3.2.8.1.1.7": "brainpoolP256r1", + "brainpoolP256t1": "1.3.36.3.3.2.8.1.1.8", + "1.3.36.3.3.2.8.1.1.8": "brainpoolP256t1", + "brainpoolP320r1": "1.3.36.3.3.2.8.1.1.9", + "1.3.36.3.3.2.8.1.1.9": "brainpoolP320r1", + "brainpoolP320t1": "1.3.36.3.3.2.8.1.1.10", + "1.3.36.3.3.2.8.1.1.10": "brainpoolP320t1", + "brainpoolP384r1": "1.3.36.3.3.2.8.1.1.11", + "1.3.36.3.3.2.8.1.1.11": "brainpoolP384r1", + "brainpoolP384t1": "1.3.36.3.3.2.8.1.1.12", + "1.3.36.3.3.2.8.1.1.12": "brainpoolP384t1", + "brainpoolP512r1": "1.3.36.3.3.2.8.1.1.13", + "1.3.36.3.3.2.8.1.1.13": "brainpoolP512r1", + "brainpoolP512t1": "1.3.36.3.3.2.8.1.1.14", + "1.3.36.3.3.2.8.1.1.14": "brainpoolP512t1", +}; +function getOidByNamedCurve$1(namedCurve) { + const oid = namedOIDs[namedCurve]; + if (!oid) { + throw new core__namespace.OperationError(`Cannot convert WebCrypto named curve '${namedCurve}' to OID`); + } + return oid; +} + +class EcPrivateKey extends AsymmetricKey { + constructor() { + super(...arguments); + this.type = "private"; + } + getKey() { + const keyInfo = asn1Schema.AsnParser.parse(this.data, core__namespace.asn1.PrivateKeyInfo); + return asn1Schema.AsnParser.parse(keyInfo.privateKey, core__namespace.asn1.EcPrivateKey); + } + toJSON() { + const key = this.getKey(); + const json = { + kty: "EC", + crv: this.algorithm.namedCurve, + key_ops: this.usages, + ext: this.extractable, + }; + return Object.assign(json, jsonSchema.JsonSerializer.toJSON(key)); + } + fromJSON(json) { + if (!json.crv) { + throw new core__namespace.OperationError(`Cannot get named curve from JWK. Property 'crv' is required`); + } + const keyInfo = new core__namespace.asn1.PrivateKeyInfo(); + keyInfo.privateKeyAlgorithm.algorithm = "1.2.840.10045.2.1"; + keyInfo.privateKeyAlgorithm.parameters = asn1Schema.AsnSerializer.serialize(new core__namespace.asn1.ObjectIdentifier(getOidByNamedCurve$1(json.crv))); + const key = jsonSchema.JsonParser.fromJSON(json, { targetSchema: core__namespace.asn1.EcPrivateKey }); + keyInfo.privateKey = asn1Schema.AsnSerializer.serialize(key); + this.data = buffer.Buffer.from(asn1Schema.AsnSerializer.serialize(keyInfo)); + return this; + } +} + +class EcPublicKey extends AsymmetricKey { + constructor() { + super(...arguments); + this.type = "public"; + } + getKey() { + const keyInfo = asn1Schema.AsnParser.parse(this.data, core__namespace.asn1.PublicKeyInfo); + return new core__namespace.asn1.EcPublicKey(keyInfo.publicKey); + } + toJSON() { + const key = this.getKey(); + const json = { + kty: "EC", + crv: this.algorithm.namedCurve, + key_ops: this.usages, + ext: this.extractable, + }; + return Object.assign(json, jsonSchema.JsonSerializer.toJSON(key)); + } + fromJSON(json) { + if (!json.crv) { + throw new core__namespace.OperationError(`Cannot get named curve from JWK. Property 'crv' is required`); + } + const key = jsonSchema.JsonParser.fromJSON(json, { targetSchema: core__namespace.asn1.EcPublicKey }); + const keyInfo = new core__namespace.asn1.PublicKeyInfo(); + keyInfo.publicKeyAlgorithm.algorithm = "1.2.840.10045.2.1"; + keyInfo.publicKeyAlgorithm.parameters = asn1Schema.AsnSerializer.serialize(new core__namespace.asn1.ObjectIdentifier(getOidByNamedCurve$1(json.crv))); + keyInfo.publicKey = asn1Schema.AsnSerializer.toASN(key).valueHex; + this.data = buffer.Buffer.from(asn1Schema.AsnSerializer.serialize(keyInfo)); + return this; + } +} + +class Sha1Provider extends core__namespace.ProviderCrypto { + constructor() { + super(...arguments); + this.name = "SHA-1"; + this.usages = []; + } + async onDigest(algorithm, data) { + return ShaCrypto.digest(algorithm, data); + } +} + +class Sha256Provider extends core__namespace.ProviderCrypto { + constructor() { + super(...arguments); + this.name = "SHA-256"; + this.usages = []; + } + async onDigest(algorithm, data) { + return ShaCrypto.digest(algorithm, data); + } +} + +class Sha384Provider extends core__namespace.ProviderCrypto { + constructor() { + super(...arguments); + this.name = "SHA-384"; + this.usages = []; + } + async onDigest(algorithm, data) { + return ShaCrypto.digest(algorithm, data); + } +} + +class Sha512Provider extends core__namespace.ProviderCrypto { + constructor() { + super(...arguments); + this.name = "SHA-512"; + this.usages = []; + } + async onDigest(algorithm, data) { + return ShaCrypto.digest(algorithm, data); + } +} + +class Sha3256Provider extends core__namespace.ProviderCrypto { + constructor() { + super(...arguments); + this.name = "SHA3-256"; + this.usages = []; + } + async onDigest(algorithm, data) { + return ShaCrypto.digest(algorithm, data); + } +} + +class Sha3384Provider extends core__namespace.ProviderCrypto { + constructor() { + super(...arguments); + this.name = "SHA3-384"; + this.usages = []; + } + async onDigest(algorithm, data) { + return ShaCrypto.digest(algorithm, data); + } +} + +class Sha3512Provider extends core__namespace.ProviderCrypto { + constructor() { + super(...arguments); + this.name = "SHA3-512"; + this.usages = []; + } + async onDigest(algorithm, data) { + return ShaCrypto.digest(algorithm, data); + } +} + +class EcCrypto { + static async generateKey(algorithm, extractable, keyUsages) { + const privateKey = new EcPrivateKey(); + privateKey.algorithm = algorithm; + privateKey.extractable = extractable; + privateKey.usages = keyUsages.filter((usage) => this.privateKeyUsages.indexOf(usage) !== -1); + const publicKey = new EcPublicKey(); + publicKey.algorithm = algorithm; + publicKey.extractable = true; + publicKey.usages = keyUsages.filter((usage) => this.publicKeyUsages.indexOf(usage) !== -1); + const keys = crypto.generateKeyPairSync("ec", { + namedCurve: this.getOpenSSLNamedCurve(algorithm.namedCurve), + publicKeyEncoding: { + format: "der", + type: "spki", + }, + privateKeyEncoding: { + format: "der", + type: "pkcs8", + }, + }); + privateKey.data = keys.privateKey; + publicKey.data = keys.publicKey; + const res = { + privateKey, + publicKey, + }; + return res; + } + static async sign(algorithm, key, data) { + const cryptoAlg = ShaCrypto.getAlgorithmName(algorithm.hash); + const signer = crypto.createSign(cryptoAlg); + signer.update(buffer.Buffer.from(data)); + if (!key.pem) { + key.pem = `-----BEGIN PRIVATE KEY-----\n${key.data.toString("base64")}\n-----END PRIVATE KEY-----`; + } + const options = { + key: key.pem, + }; + const signature = signer.sign(options); + const ecSignature = asn1Schema.AsnParser.parse(signature, core__namespace.asn1.EcDsaSignature); + const signatureRaw = core__namespace.EcUtils.encodeSignature(ecSignature, core__namespace.EcCurves.get(key.algorithm.namedCurve).size); + return signatureRaw.buffer; + } + static async verify(algorithm, key, signature, data) { + const cryptoAlg = ShaCrypto.getAlgorithmName(algorithm.hash); + const signer = crypto.createVerify(cryptoAlg); + signer.update(buffer.Buffer.from(data)); + if (!key.pem) { + key.pem = `-----BEGIN PUBLIC KEY-----\n${key.data.toString("base64")}\n-----END PUBLIC KEY-----`; + } + const options = { + key: key.pem, + }; + const ecSignature = new core__namespace.asn1.EcDsaSignature(); + const namedCurve = core__namespace.EcCurves.get(key.algorithm.namedCurve); + const signaturePoint = core__namespace.EcUtils.decodeSignature(signature, namedCurve.size); + ecSignature.r = pvtsutils.BufferSourceConverter.toArrayBuffer(signaturePoint.r); + ecSignature.s = pvtsutils.BufferSourceConverter.toArrayBuffer(signaturePoint.s); + const ecSignatureRaw = buffer.Buffer.from(asn1Schema.AsnSerializer.serialize(ecSignature)); + const ok = signer.verify(options, ecSignatureRaw); + return ok; + } + static async deriveBits(algorithm, baseKey, length) { + const cryptoAlg = this.getOpenSSLNamedCurve(baseKey.algorithm.namedCurve); + const ecdh = crypto.createECDH(cryptoAlg); + const asnPrivateKey = asn1Schema.AsnParser.parse(baseKey.data, core__namespace.asn1.PrivateKeyInfo); + const asnEcPrivateKey = asn1Schema.AsnParser.parse(asnPrivateKey.privateKey, core__namespace.asn1.EcPrivateKey); + ecdh.setPrivateKey(buffer.Buffer.from(asnEcPrivateKey.privateKey)); + const asnPublicKey = asn1Schema.AsnParser.parse(algorithm.public.data, core__namespace.asn1.PublicKeyInfo); + const bits = ecdh.computeSecret(buffer.Buffer.from(asnPublicKey.publicKey)); + if (length === null) { + return bits; + } + return new Uint8Array(bits).buffer.slice(0, length >> 3); + } + static async exportKey(format, key) { + switch (format.toLowerCase()) { + case "jwk": + return jsonSchema.JsonSerializer.toJSON(key); + case "pkcs8": + case "spki": + return new Uint8Array(key.data).buffer; + case "raw": { + const publicKeyInfo = asn1Schema.AsnParser.parse(key.data, core__namespace.asn1.PublicKeyInfo); + return publicKeyInfo.publicKey; + } + default: + throw new core__namespace.OperationError("format: Must be 'jwk', 'raw', pkcs8' or 'spki'"); + } + } + static async importKey(format, keyData, algorithm, extractable, keyUsages) { + switch (format.toLowerCase()) { + case "jwk": { + const jwk = keyData; + if (jwk.d) { + const asnKey = jsonSchema.JsonParser.fromJSON(keyData, { targetSchema: core__namespace.asn1.EcPrivateKey }); + return this.importPrivateKey(asnKey, algorithm, extractable, keyUsages); + } + else { + const asnKey = jsonSchema.JsonParser.fromJSON(keyData, { targetSchema: core__namespace.asn1.EcPublicKey }); + return this.importPublicKey(asnKey, algorithm, extractable, keyUsages); + } + } + case "raw": { + const asnKey = new core__namespace.asn1.EcPublicKey(keyData); + return this.importPublicKey(asnKey, algorithm, extractable, keyUsages); + } + case "spki": { + const keyInfo = asn1Schema.AsnParser.parse(new Uint8Array(keyData), core__namespace.asn1.PublicKeyInfo); + const asnKey = new core__namespace.asn1.EcPublicKey(keyInfo.publicKey); + this.assertKeyParameters(keyInfo.publicKeyAlgorithm.parameters, algorithm.namedCurve); + return this.importPublicKey(asnKey, algorithm, extractable, keyUsages); + } + case "pkcs8": { + const keyInfo = asn1Schema.AsnParser.parse(new Uint8Array(keyData), core__namespace.asn1.PrivateKeyInfo); + const asnKey = asn1Schema.AsnParser.parse(keyInfo.privateKey, core__namespace.asn1.EcPrivateKey); + this.assertKeyParameters(keyInfo.privateKeyAlgorithm.parameters, algorithm.namedCurve); + return this.importPrivateKey(asnKey, algorithm, extractable, keyUsages); + } + default: + throw new core__namespace.OperationError("format: Must be 'jwk', 'raw', 'pkcs8' or 'spki'"); + } + } + static assertKeyParameters(parameters, namedCurve) { + if (!parameters) { + throw new core__namespace.CryptoError("Key info doesn't have required parameters"); + } + let namedCurveIdentifier = ""; + try { + namedCurveIdentifier = asn1Schema.AsnParser.parse(parameters, core__namespace.asn1.ObjectIdentifier).value; + } + catch (e) { + throw new core__namespace.CryptoError("Cannot read key info parameters"); + } + if (getOidByNamedCurve$1(namedCurve) !== namedCurveIdentifier) { + throw new core__namespace.CryptoError("Key info parameter doesn't match to named curve"); + } + } + static async importPrivateKey(asnKey, algorithm, extractable, keyUsages) { + const keyInfo = new core__namespace.asn1.PrivateKeyInfo(); + keyInfo.privateKeyAlgorithm.algorithm = "1.2.840.10045.2.1"; + keyInfo.privateKeyAlgorithm.parameters = asn1Schema.AsnSerializer.serialize(new core__namespace.asn1.ObjectIdentifier(getOidByNamedCurve$1(algorithm.namedCurve))); + keyInfo.privateKey = asn1Schema.AsnSerializer.serialize(asnKey); + const key = new EcPrivateKey(); + key.data = buffer.Buffer.from(asn1Schema.AsnSerializer.serialize(keyInfo)); + key.algorithm = Object.assign({}, algorithm); + key.extractable = extractable; + key.usages = keyUsages; + return key; + } + static async importPublicKey(asnKey, algorithm, extractable, keyUsages) { + const keyInfo = new core__namespace.asn1.PublicKeyInfo(); + keyInfo.publicKeyAlgorithm.algorithm = "1.2.840.10045.2.1"; + const namedCurve = getOidByNamedCurve$1(algorithm.namedCurve); + keyInfo.publicKeyAlgorithm.parameters = asn1Schema.AsnSerializer.serialize(new core__namespace.asn1.ObjectIdentifier(namedCurve)); + keyInfo.publicKey = asnKey.value; + const key = new EcPublicKey(); + key.data = buffer.Buffer.from(asn1Schema.AsnSerializer.serialize(keyInfo)); + key.algorithm = Object.assign({}, algorithm); + key.extractable = extractable; + key.usages = keyUsages; + return key; + } + static getOpenSSLNamedCurve(curve) { + switch (curve.toUpperCase()) { + case "P-256": + return "prime256v1"; + case "K-256": + return "secp256k1"; + case "P-384": + return "secp384r1"; + case "P-521": + return "secp521r1"; + default: + return curve; + } + } +} +EcCrypto.publicKeyUsages = ["verify"]; +EcCrypto.privateKeyUsages = ["sign", "deriveKey", "deriveBits"]; + +class EcdsaProvider extends core__namespace.EcdsaProvider { + constructor() { + super(...arguments); + this.namedCurves = core__namespace.EcCurves.names; + this.hashAlgorithms = [ + "SHA-1", "SHA-256", "SHA-384", "SHA-512", + "shake128", "shake256", + "SHA3-256", "SHA3-384", "SHA3-512" + ]; + } + async onGenerateKey(algorithm, extractable, keyUsages) { + const keys = await EcCrypto.generateKey({ + ...algorithm, + name: this.name, + }, extractable, keyUsages); + return { + privateKey: setCryptoKey(keys.privateKey), + publicKey: setCryptoKey(keys.publicKey), + }; + } + async onSign(algorithm, key, data) { + return EcCrypto.sign(algorithm, getCryptoKey(key), new Uint8Array(data)); + } + async onVerify(algorithm, key, signature, data) { + return EcCrypto.verify(algorithm, getCryptoKey(key), new Uint8Array(signature), new Uint8Array(data)); + } + async onExportKey(format, key) { + return EcCrypto.exportKey(format, getCryptoKey(key)); + } + async onImportKey(format, keyData, algorithm, extractable, keyUsages) { + const key = await EcCrypto.importKey(format, keyData, { ...algorithm, name: this.name }, extractable, keyUsages); + return setCryptoKey(key); + } + checkCryptoKey(key, keyUsage) { + super.checkCryptoKey(key, keyUsage); + const internalKey = getCryptoKey(key); + if (!(internalKey instanceof EcPrivateKey || internalKey instanceof EcPublicKey)) { + throw new TypeError("key: Is not EC CryptoKey"); + } + } +} + +class EcdhProvider extends core__namespace.EcdhProvider { + constructor() { + super(...arguments); + this.namedCurves = core__namespace.EcCurves.names; + } + async onGenerateKey(algorithm, extractable, keyUsages) { + const keys = await EcCrypto.generateKey({ + ...algorithm, + name: this.name, + }, extractable, keyUsages); + return { + privateKey: setCryptoKey(keys.privateKey), + publicKey: setCryptoKey(keys.publicKey), + }; + } + async onExportKey(format, key) { + return EcCrypto.exportKey(format, getCryptoKey(key)); + } + async onImportKey(format, keyData, algorithm, extractable, keyUsages) { + const key = await EcCrypto.importKey(format, keyData, { ...algorithm, name: this.name }, extractable, keyUsages); + return setCryptoKey(key); + } + checkCryptoKey(key, keyUsage) { + super.checkCryptoKey(key, keyUsage); + const internalKey = getCryptoKey(key); + if (!(internalKey instanceof EcPrivateKey || internalKey instanceof EcPublicKey)) { + throw new TypeError("key: Is not EC CryptoKey"); + } + } + async onDeriveBits(algorithm, baseKey, length) { + const bits = await EcCrypto.deriveBits({ ...algorithm, public: getCryptoKey(algorithm.public) }, getCryptoKey(baseKey), length); + return bits; + } +} + +const edOIDs = { + [core__namespace.asn1.idEd448]: "Ed448", + "ed448": core__namespace.asn1.idEd448, + [core__namespace.asn1.idX448]: "X448", + "x448": core__namespace.asn1.idX448, + [core__namespace.asn1.idEd25519]: "Ed25519", + "ed25519": core__namespace.asn1.idEd25519, + [core__namespace.asn1.idX25519]: "X25519", + "x25519": core__namespace.asn1.idX25519, +}; +function getOidByNamedCurve(namedCurve) { + const oid = edOIDs[namedCurve.toLowerCase()]; + if (!oid) { + throw new core__namespace.OperationError(`Cannot convert WebCrypto named curve '${namedCurve}' to OID`); + } + return oid; +} + +class EdPrivateKey extends AsymmetricKey { + constructor() { + super(...arguments); + this.type = "private"; + } + getKey() { + const keyInfo = asn1Schema.AsnParser.parse(this.data, core__namespace.asn1.PrivateKeyInfo); + return asn1Schema.AsnParser.parse(keyInfo.privateKey, core__namespace.asn1.CurvePrivateKey); + } + toJSON() { + const key = this.getKey(); + const json = { + kty: "OKP", + crv: this.algorithm.namedCurve, + key_ops: this.usages, + ext: this.extractable, + }; + return Object.assign(json, jsonSchema.JsonSerializer.toJSON(key)); + } + fromJSON(json) { + if (!json.crv) { + throw new core__namespace.OperationError(`Cannot get named curve from JWK. Property 'crv' is required`); + } + const keyInfo = new core__namespace.asn1.PrivateKeyInfo(); + keyInfo.privateKeyAlgorithm.algorithm = getOidByNamedCurve(json.crv); + const key = jsonSchema.JsonParser.fromJSON(json, { targetSchema: core__namespace.asn1.CurvePrivateKey }); + keyInfo.privateKey = asn1Schema.AsnSerializer.serialize(key); + this.data = buffer.Buffer.from(asn1Schema.AsnSerializer.serialize(keyInfo)); + return this; + } +} + +class EdPublicKey extends AsymmetricKey { + constructor() { + super(...arguments); + this.type = "public"; + } + getKey() { + const keyInfo = asn1Schema.AsnParser.parse(this.data, core__namespace.asn1.PublicKeyInfo); + return keyInfo.publicKey; + } + toJSON() { + const key = this.getKey(); + const json = { + kty: "OKP", + crv: this.algorithm.namedCurve, + key_ops: this.usages, + ext: this.extractable, + }; + return Object.assign(json, { + x: pvtsutils.Convert.ToBase64Url(key) + }); + } + fromJSON(json) { + if (!json.crv) { + throw new core__namespace.OperationError(`Cannot get named curve from JWK. Property 'crv' is required`); + } + if (!json.x) { + throw new core__namespace.OperationError(`Cannot get property from JWK. Property 'x' is required`); + } + const keyInfo = new core__namespace.asn1.PublicKeyInfo(); + keyInfo.publicKeyAlgorithm.algorithm = getOidByNamedCurve(json.crv); + keyInfo.publicKey = pvtsutils.Convert.FromBase64Url(json.x); + this.data = buffer.Buffer.from(asn1Schema.AsnSerializer.serialize(keyInfo)); + return this; + } +} + +class EdCrypto { + static async generateKey(algorithm, extractable, keyUsages) { + const privateKey = new EdPrivateKey(); + privateKey.algorithm = algorithm; + privateKey.extractable = extractable; + privateKey.usages = keyUsages.filter((usage) => this.privateKeyUsages.indexOf(usage) !== -1); + const publicKey = new EdPublicKey(); + publicKey.algorithm = algorithm; + publicKey.extractable = true; + publicKey.usages = keyUsages.filter((usage) => this.publicKeyUsages.indexOf(usage) !== -1); + const type = algorithm.namedCurve.toLowerCase(); + const keys = crypto.generateKeyPairSync(type, { + publicKeyEncoding: { + format: "der", + type: "spki", + }, + privateKeyEncoding: { + format: "der", + type: "pkcs8", + }, + }); + privateKey.data = keys.privateKey; + publicKey.data = keys.publicKey; + const res = { + privateKey, + publicKey, + }; + return res; + } + static async sign(algorithm, key, data) { + if (!key.pem) { + key.pem = `-----BEGIN PRIVATE KEY-----\n${key.data.toString("base64")}\n-----END PRIVATE KEY-----`; + } + const options = { + key: key.pem, + }; + const signature = crypto.sign(null, buffer.Buffer.from(data), options); + return core__namespace.BufferSourceConverter.toArrayBuffer(signature); + } + static async verify(algorithm, key, signature, data) { + if (!key.pem) { + key.pem = `-----BEGIN PUBLIC KEY-----\n${key.data.toString("base64")}\n-----END PUBLIC KEY-----`; + } + const options = { + key: key.pem, + }; + const ok = crypto.verify(null, buffer.Buffer.from(data), options, buffer.Buffer.from(signature)); + return ok; + } + static async deriveBits(algorithm, baseKey, length) { + const publicKey = crypto.createPublicKey({ + key: algorithm.public.data, + format: "der", + type: "spki", + }); + const privateKey = crypto.createPrivateKey({ + key: baseKey.data, + format: "der", + type: "pkcs8", + }); + const bits = crypto.diffieHellman({ + publicKey, + privateKey, + }); + return new Uint8Array(bits).buffer.slice(0, length >> 3); + } + static async exportKey(format, key) { + switch (format.toLowerCase()) { + case "jwk": + return jsonSchema.JsonSerializer.toJSON(key); + case "pkcs8": + case "spki": + return new Uint8Array(key.data).buffer; + case "raw": { + const publicKeyInfo = asn1Schema.AsnParser.parse(key.data, core__namespace.asn1.PublicKeyInfo); + return publicKeyInfo.publicKey; + } + default: + throw new core__namespace.OperationError("format: Must be 'jwk', 'raw', pkcs8' or 'spki'"); + } + } + static async importKey(format, keyData, algorithm, extractable, keyUsages) { + switch (format.toLowerCase()) { + case "jwk": { + const jwk = keyData; + if (jwk.d) { + const asnKey = jsonSchema.JsonParser.fromJSON(keyData, { targetSchema: core__namespace.asn1.CurvePrivateKey }); + return this.importPrivateKey(asnKey, algorithm, extractable, keyUsages); + } + else { + if (!jwk.x) { + throw new TypeError("keyData: Cannot get required 'x' filed"); + } + return this.importPublicKey(pvtsutils.Convert.FromBase64Url(jwk.x), algorithm, extractable, keyUsages); + } + } + case "raw": { + return this.importPublicKey(keyData, algorithm, extractable, keyUsages); + } + case "spki": { + const keyInfo = asn1Schema.AsnParser.parse(new Uint8Array(keyData), core__namespace.asn1.PublicKeyInfo); + return this.importPublicKey(keyInfo.publicKey, algorithm, extractable, keyUsages); + } + case "pkcs8": { + const keyInfo = asn1Schema.AsnParser.parse(new Uint8Array(keyData), core__namespace.asn1.PrivateKeyInfo); + const asnKey = asn1Schema.AsnParser.parse(keyInfo.privateKey, core__namespace.asn1.CurvePrivateKey); + return this.importPrivateKey(asnKey, algorithm, extractable, keyUsages); + } + default: + throw new core__namespace.OperationError("format: Must be 'jwk', 'raw', 'pkcs8' or 'spki'"); + } + } + static importPrivateKey(asnKey, algorithm, extractable, keyUsages) { + const key = new EdPrivateKey(); + key.fromJSON({ + crv: algorithm.namedCurve, + d: pvtsutils.Convert.ToBase64Url(asnKey.d), + }); + key.algorithm = Object.assign({}, algorithm); + key.extractable = extractable; + key.usages = keyUsages; + return key; + } + static async importPublicKey(asnKey, algorithm, extractable, keyUsages) { + const key = new EdPublicKey(); + key.fromJSON({ + crv: algorithm.namedCurve, + x: pvtsutils.Convert.ToBase64Url(asnKey), + }); + key.algorithm = Object.assign({}, algorithm); + key.extractable = extractable; + key.usages = keyUsages; + return key; + } +} +EdCrypto.publicKeyUsages = ["verify"]; +EdCrypto.privateKeyUsages = ["sign", "deriveKey", "deriveBits"]; + +class EdDsaProvider extends core__namespace.EdDsaProvider { + async onGenerateKey(algorithm, extractable, keyUsages) { + const keys = await EdCrypto.generateKey({ + name: this.name, + namedCurve: algorithm.namedCurve.replace(/^ed/i, "Ed"), + }, extractable, keyUsages); + return { + privateKey: setCryptoKey(keys.privateKey), + publicKey: setCryptoKey(keys.publicKey), + }; + } + async onSign(algorithm, key, data) { + return EdCrypto.sign(algorithm, getCryptoKey(key), new Uint8Array(data)); + } + async onVerify(algorithm, key, signature, data) { + return EdCrypto.verify(algorithm, getCryptoKey(key), new Uint8Array(signature), new Uint8Array(data)); + } + async onExportKey(format, key) { + return EdCrypto.exportKey(format, getCryptoKey(key)); + } + async onImportKey(format, keyData, algorithm, extractable, keyUsages) { + const key = await EdCrypto.importKey(format, keyData, { ...algorithm, name: this.name }, extractable, keyUsages); + return setCryptoKey(key); + } +} + +class EcdhEsProvider extends core__namespace.EcdhEsProvider { + async onGenerateKey(algorithm, extractable, keyUsages) { + const keys = await EdCrypto.generateKey({ + name: this.name, + namedCurve: algorithm.namedCurve.toUpperCase(), + }, extractable, keyUsages); + return { + privateKey: setCryptoKey(keys.privateKey), + publicKey: setCryptoKey(keys.publicKey), + }; + } + async onDeriveBits(algorithm, baseKey, length) { + const bits = await EdCrypto.deriveBits({ ...algorithm, public: getCryptoKey(algorithm.public) }, getCryptoKey(baseKey), length); + return bits; + } + async onExportKey(format, key) { + return EdCrypto.exportKey(format, getCryptoKey(key)); + } + async onImportKey(format, keyData, algorithm, extractable, keyUsages) { + const key = await EdCrypto.importKey(format, keyData, { ...algorithm, name: this.name }, extractable, keyUsages); + return setCryptoKey(key); + } +} + +class Ed25519CryptoKey extends CryptoKey { + constructor(algorithm, extractable, usages, data) { + super(); + this.algorithm = algorithm; + this.extractable = extractable; + this.usages = usages; + this.data = Buffer.from(data); + } + toJWK() { + return { + kty: "OKP", + crv: this.algorithm.name, + key_ops: this.usages, + ext: this.extractable, + }; + } +} + +class Ed25519PrivateKey extends Ed25519CryptoKey { + constructor() { + super(...arguments); + this.type = "private"; + } + toJWK() { + const pubJwk = crypto.createPublicKey({ + key: this.data, + format: "pem", + }).export({ format: "jwk" }); + const raw = core__namespace.PemConverter.toUint8Array(this.data.toString()); + const pkcs8 = asn1Schema.AsnConvert.parse(raw, core__namespace.asn1.PrivateKeyInfo); + const d = asn1Schema.AsnConvert.parse(pkcs8.privateKey, core__namespace.asn1.EdPrivateKey).value; + return { + ...super.toJWK(), + ...pubJwk, + d: Buffer.from(new Uint8Array(d)).toString("base64url"), + }; + } +} + +class Ed25519PublicKey extends Ed25519CryptoKey { + constructor() { + super(...arguments); + this.type = "public"; + } + toJWK() { + const jwk = crypto.createPublicKey({ + key: this.data, + format: "pem", + }).export({ format: "jwk" }); + return { + ...super.toJWK(), + ...jwk, + }; + } +} + +class Ed25519Crypto { + static async generateKey(algorithm, extractable, keyUsages) { + const type = algorithm.name.toLowerCase(); + const keys = crypto.generateKeyPairSync(type, { + publicKeyEncoding: { + format: "pem", + type: "spki", + }, + privateKeyEncoding: { + format: "pem", + type: "pkcs8", + }, + }); + const keyAlg = { + name: type === "ed25519" ? "Ed25519" : "X25519", + }; + const privateKeyUsages = keyUsages.filter((usage) => this.privateKeyUsages.includes(usage)); + const publicKeyUsages = keyUsages.filter((usage) => this.publicKeyUsages.includes(usage)); + return { + privateKey: new Ed25519PrivateKey(keyAlg, extractable, privateKeyUsages, keys.privateKey), + publicKey: new Ed25519PublicKey(keyAlg, true, publicKeyUsages, keys.publicKey), + }; + } + static async sign(algorithm, key, data) { + const signature = crypto.sign(null, Buffer.from(data), key.data); + return core__namespace.BufferSourceConverter.toArrayBuffer(signature); + } + static async verify(algorithm, key, signature, data) { + return crypto.verify(null, Buffer.from(data), key.data, signature); + } + static async exportKey(format, key) { + switch (format) { + case "jwk": + return key.toJWK(); + case "pkcs8": { + return core__namespace.PemConverter.toArrayBuffer(key.data.toString()); + } + case "spki": { + return core__namespace.PemConverter.toArrayBuffer(key.data.toString()); + } + case "raw": { + const jwk = key.toJWK(); + return pvtsutils.Convert.FromBase64Url(jwk.x); + } + default: + return Promise.reject(new core__namespace.OperationError("format: Must be 'jwk', 'raw', pkcs8' or 'spki'")); + } + } + static async importKey(format, keyData, algorithm, extractable, keyUsages) { + switch (format) { + case "jwk": { + const jwk = keyData; + if (jwk.d) { + const privateData = new core__namespace.asn1.EdPrivateKey(); + privateData.value = core__namespace.BufferSourceConverter.toArrayBuffer(Buffer.from(jwk.d, "base64url")); + const pkcs8 = new core__namespace.asn1.PrivateKeyInfo(); + pkcs8.privateKeyAlgorithm.algorithm = algorithm.name.toLowerCase() === "ed25519" + ? core__namespace.asn1.idEd25519 + : core__namespace.asn1.idX25519; + pkcs8.privateKey = asn1Schema.AsnConvert.serialize(privateData); + const raw = asn1Schema.AsnConvert.serialize(pkcs8); + const pem = core__namespace.PemConverter.fromBufferSource(raw, "PRIVATE KEY"); + return new Ed25519PrivateKey(algorithm, extractable, keyUsages, pem); + } + else if (jwk.x) { + const pubKey = crypto.createPublicKey({ + format: "jwk", + key: jwk, + }); + const pem = pubKey.export({ format: "pem", type: "spki" }); + return new Ed25519PublicKey(algorithm, extractable, keyUsages, pem); + } + else { + throw new core__namespace.OperationError("keyData: Cannot import JWK. 'd' or 'x' must be presented"); + } + } + case "pkcs8": { + const pem = core__namespace.PemConverter.fromBufferSource(keyData, "PRIVATE KEY"); + return new Ed25519PrivateKey(algorithm, extractable, keyUsages, pem); + } + case "spki": { + const pem = core__namespace.PemConverter.fromBufferSource(keyData, "PUBLIC KEY"); + return new Ed25519PublicKey(algorithm, extractable, keyUsages, pem); + } + case "raw": { + const raw = keyData; + const key = crypto.createPublicKey({ + format: "jwk", + key: { + kty: "OKP", + crv: algorithm.name.toLowerCase() === "ed25519" ? "Ed25519" : "X25519", + x: pvtsutils.Convert.ToBase64Url(raw), + }, + }); + const pem = key.export({ format: "pem", type: "spki" }); + return new Ed25519PublicKey(algorithm, extractable, keyUsages, pem); + } + default: + return Promise.reject(new core__namespace.OperationError("format: Must be 'jwk', 'raw', pkcs8' or 'spki'")); + } + } +} +Ed25519Crypto.privateKeyUsages = ["sign", "deriveBits", "deriveKey"]; +Ed25519Crypto.publicKeyUsages = ["verify"]; + +class Ed25519Provider extends core__namespace.Ed25519Provider { + async onGenerateKey(algorithm, extractable, keyUsages) { + const keys = await Ed25519Crypto.generateKey(algorithm, extractable, keyUsages); + return { + privateKey: setCryptoKey(keys.privateKey), + publicKey: setCryptoKey(keys.publicKey), + }; + } + async onSign(algorithm, key, data) { + const internalKey = getCryptoKey(key); + const signature = Ed25519Crypto.sign(algorithm, internalKey, new Uint8Array(data)); + return signature; + } + onVerify(algorithm, key, signature, data) { + const internalKey = getCryptoKey(key); + return Ed25519Crypto.verify(algorithm, internalKey, new Uint8Array(signature), new Uint8Array(data)); + } + async onExportKey(format, key) { + const internalKey = getCryptoKey(key); + return Ed25519Crypto.exportKey(format, internalKey); + } + async onImportKey(format, keyData, algorithm, extractable, keyUsages) { + const internalKey = await Ed25519Crypto.importKey(format, keyData, algorithm, extractable, keyUsages); + return setCryptoKey(internalKey); + } +} + +class X25519Provider extends core__namespace.X25519Provider { + async onGenerateKey(algorithm, extractable, keyUsages) { + const keys = await Ed25519Crypto.generateKey(algorithm, extractable, keyUsages); + return { + privateKey: setCryptoKey(keys.privateKey), + publicKey: setCryptoKey(keys.publicKey), + }; + } + async onDeriveBits(algorithm, baseKey, length) { + const internalBaseKey = getCryptoKey(baseKey); + const internalPublicKey = getCryptoKey(algorithm.public); + const publicKey = crypto.createPublicKey({ + key: internalPublicKey.data.toString(), + format: "pem", + type: "spki", + }); + const privateKey = crypto.createPrivateKey({ + key: internalBaseKey.data.toString(), + format: "pem", + type: "pkcs8", + }); + const bits = crypto.diffieHellman({ + publicKey, + privateKey, + }); + return new Uint8Array(bits).buffer.slice(0, length >> 3); + } + async onExportKey(format, key) { + const internalKey = getCryptoKey(key); + return Ed25519Crypto.exportKey(format, internalKey); + } + async onImportKey(format, keyData, algorithm, extractable, keyUsages) { + const key = await Ed25519Crypto.importKey(format, keyData, algorithm, extractable, keyUsages); + return setCryptoKey(key); + } + checkCryptoKey(key, keyUsage) { + super.checkCryptoKey(key, keyUsage); + if (!(getCryptoKey(key) instanceof Ed25519CryptoKey)) { + throw new TypeError("key: Is not a Ed25519CryptoKey"); + } + } +} + +class PbkdfCryptoKey extends CryptoKey { +} + +class Pbkdf2Provider extends core__namespace.Pbkdf2Provider { + async onDeriveBits(algorithm, baseKey, length) { + return new Promise((resolve, reject) => { + const salt = core__namespace.BufferSourceConverter.toArrayBuffer(algorithm.salt); + const hash = algorithm.hash.name.replace("-", ""); + crypto.pbkdf2(getCryptoKey(baseKey).data, buffer.Buffer.from(salt), algorithm.iterations, length >> 3, hash, (err, derivedBits) => { + if (err) { + reject(err); + } + else { + resolve(new Uint8Array(derivedBits).buffer); + } + }); + }); + } + async onImportKey(format, keyData, algorithm, extractable, keyUsages) { + if (format === "raw") { + const key = new PbkdfCryptoKey(); + key.data = buffer.Buffer.from(keyData); + key.algorithm = { name: this.name }; + key.extractable = false; + key.usages = keyUsages; + return setCryptoKey(key); + } + throw new core__namespace.OperationError("format: Must be 'raw'"); + } + checkCryptoKey(key, keyUsage) { + super.checkCryptoKey(key, keyUsage); + if (!(getCryptoKey(key) instanceof PbkdfCryptoKey)) { + throw new TypeError("key: Is not PBKDF CryptoKey"); + } + } +} + +class HmacCryptoKey extends CryptoKey { + get alg() { + const hash = this.algorithm.hash.name.toUpperCase(); + return `HS${hash.replace("SHA-", "")}`; + } + set alg(value) { + } +} +tslib.__decorate([ + jsonSchema.JsonProp({ name: "k", converter: JsonBase64UrlConverter }) +], HmacCryptoKey.prototype, "data", void 0); + +class HmacProvider extends core__namespace.HmacProvider { + async onGenerateKey(algorithm, extractable, keyUsages) { + const length = (algorithm.length || this.getDefaultLength(algorithm.hash.name)) >> 3 << 3; + const key = new HmacCryptoKey(); + key.algorithm = { + ...algorithm, + length, + name: this.name, + }; + key.extractable = extractable; + key.usages = keyUsages; + key.data = crypto.randomBytes(length >> 3); + return setCryptoKey(key); + } + async onSign(algorithm, key, data) { + const cryptoAlg = ShaCrypto.getAlgorithmName(key.algorithm.hash); + const hmac = crypto.createHmac(cryptoAlg, getCryptoKey(key).data) + .update(buffer.Buffer.from(data)).digest(); + return new Uint8Array(hmac).buffer; + } + async onVerify(algorithm, key, signature, data) { + const cryptoAlg = ShaCrypto.getAlgorithmName(key.algorithm.hash); + const hmac = crypto.createHmac(cryptoAlg, getCryptoKey(key).data) + .update(buffer.Buffer.from(data)).digest(); + return hmac.compare(buffer.Buffer.from(signature)) === 0; + } + async onImportKey(format, keyData, algorithm, extractable, keyUsages) { + let key; + switch (format.toLowerCase()) { + case "jwk": + key = jsonSchema.JsonParser.fromJSON(keyData, { targetSchema: HmacCryptoKey }); + break; + case "raw": + key = new HmacCryptoKey(); + key.data = buffer.Buffer.from(keyData); + break; + default: + throw new core__namespace.OperationError("format: Must be 'jwk' or 'raw'"); + } + key.algorithm = { + hash: { name: algorithm.hash.name }, + name: this.name, + length: key.data.length << 3, + }; + key.extractable = extractable; + key.usages = keyUsages; + return setCryptoKey(key); + } + async onExportKey(format, key) { + switch (format.toLowerCase()) { + case "jwk": + return jsonSchema.JsonSerializer.toJSON(getCryptoKey(key)); + case "raw": + return new Uint8Array(getCryptoKey(key).data).buffer; + default: + throw new core__namespace.OperationError("format: Must be 'jwk' or 'raw'"); + } + } + checkCryptoKey(key, keyUsage) { + super.checkCryptoKey(key, keyUsage); + if (!(getCryptoKey(key) instanceof HmacCryptoKey)) { + throw new TypeError("key: Is not HMAC CryptoKey"); + } + } +} + +class HkdfCryptoKey extends CryptoKey { +} + +class HkdfProvider extends core__namespace.HkdfProvider { + async onImportKey(format, keyData, algorithm, extractable, keyUsages) { + if (format.toLowerCase() !== "raw") { + throw new core__namespace.OperationError("Operation not supported"); + } + const key = new HkdfCryptoKey(); + key.data = buffer.Buffer.from(keyData); + key.algorithm = { name: this.name }; + key.extractable = extractable; + key.usages = keyUsages; + return setCryptoKey(key); + } + async onDeriveBits(params, baseKey, length) { + const hash = params.hash.name.replace("-", ""); + const hashLength = crypto.createHash(hash).digest().length; + const byteLength = length / 8; + const info = core.BufferSourceConverter.toUint8Array(params.info); + const PRK = crypto.createHmac(hash, core.BufferSourceConverter.toUint8Array(params.salt)) + .update(core.BufferSourceConverter.toUint8Array(getCryptoKey(baseKey).data)) + .digest(); + const blocks = [buffer.Buffer.alloc(0)]; + const blockCount = Math.ceil(byteLength / hashLength) + 1; + for (let i = 1; i < blockCount; ++i) { + blocks.push(crypto.createHmac(hash, PRK) + .update(buffer.Buffer.concat([blocks[i - 1], info, buffer.Buffer.from([i])])) + .digest()); + } + return buffer.Buffer.concat(blocks).slice(0, byteLength); + } + checkCryptoKey(key, keyUsage) { + super.checkCryptoKey(key, keyUsage); + if (!(getCryptoKey(key) instanceof HkdfCryptoKey)) { + throw new TypeError("key: Is not HKDF CryptoKey"); + } + } +} + +class ShakeCrypto { + static digest(algorithm, data) { + const hash = crypto.createHash(algorithm.name.toLowerCase(), { outputLength: algorithm.length }) + .update(buffer.Buffer.from(data)).digest(); + return new Uint8Array(hash).buffer; + } +} + +class Shake128Provider extends core__namespace.Shake128Provider { + async onDigest(algorithm, data) { + return ShakeCrypto.digest(algorithm, data); + } +} + +class Shake256Provider extends core__namespace.Shake256Provider { + async onDigest(algorithm, data) { + return ShakeCrypto.digest(algorithm, data); + } +} + +class SubtleCrypto extends core__namespace.SubtleCrypto { + constructor() { + var _a; + super(); + this.providers.set(new AesCbcProvider()); + this.providers.set(new AesCtrProvider()); + this.providers.set(new AesGcmProvider()); + this.providers.set(new AesCmacProvider()); + this.providers.set(new AesKwProvider()); + this.providers.set(new AesEcbProvider()); + const ciphers = crypto.getCiphers(); + if (ciphers.includes("des-cbc")) { + this.providers.set(new DesCbcProvider()); + } + this.providers.set(new DesEde3CbcProvider()); + this.providers.set(new RsaSsaProvider()); + this.providers.set(new RsaPssProvider()); + this.providers.set(new RsaOaepProvider()); + this.providers.set(new RsaEsProvider()); + this.providers.set(new EcdsaProvider()); + this.providers.set(new EcdhProvider()); + this.providers.set(new Sha1Provider()); + this.providers.set(new Sha256Provider()); + this.providers.set(new Sha384Provider()); + this.providers.set(new Sha512Provider()); + this.providers.set(new Pbkdf2Provider()); + this.providers.set(new HmacProvider()); + this.providers.set(new HkdfProvider()); + const nodeMajorVersion = (_a = /^v(\d+)/.exec(process__namespace.version)) === null || _a === void 0 ? void 0 : _a[1]; + if (nodeMajorVersion && parseInt(nodeMajorVersion, 10) >= 12) { + this.providers.set(new Shake128Provider()); + this.providers.set(new Shake256Provider()); + } + const hashes = crypto.getHashes(); + if (hashes.includes("sha3-256")) { + this.providers.set(new Sha3256Provider()); + } + if (hashes.includes("sha3-384")) { + this.providers.set(new Sha3384Provider()); + } + if (hashes.includes("sha3-512")) { + this.providers.set(new Sha3512Provider()); + } + if (nodeMajorVersion && parseInt(nodeMajorVersion, 10) >= 14) { + this.providers.set(new EdDsaProvider()); + this.providers.set(new EcdhEsProvider()); + this.providers.set(new Ed25519Provider()); + this.providers.set(new X25519Provider()); + } + } +} + +class Crypto extends core__namespace.Crypto { + constructor() { + super(...arguments); + this.subtle = new SubtleCrypto(); + } + getRandomValues(array) { + if (!ArrayBuffer.isView(array)) { + throw new TypeError("Failed to execute 'getRandomValues' on 'Crypto': parameter 1 is not of type 'ArrayBufferView'"); + } + const buffer$1 = buffer.Buffer.from(array.buffer, array.byteOffset, array.byteLength); + crypto.randomFillSync(buffer$1); + return array; + } +} + +Object.defineProperty(exports, "CryptoKey", { + enumerable: true, + get: function () { return core.CryptoKey; } +}); +exports.Crypto = Crypto; diff --git a/gun-server/node_modules/@peculiar/webcrypto/index.d.ts b/gun-server/node_modules/@peculiar/webcrypto/index.d.ts new file mode 100644 index 0000000..8275665 --- /dev/null +++ b/gun-server/node_modules/@peculiar/webcrypto/index.d.ts @@ -0,0 +1,12 @@ +export declare class Crypto implements globalThis.Crypto { + public subtle: SubtleCrypto; + public getRandomValues(array: T): T; + randomUUID(): `${string}-${string}-${string}-${string}-${string}`; +} + +export declare class CryptoKey implements globalThis.CryptoKey { + public algorithm: KeyAlgorithm; + public extractable: boolean; + public type: KeyType; + public usages: KeyUsage[]; +} diff --git a/gun-server/node_modules/@peculiar/webcrypto/package.json b/gun-server/node_modules/@peculiar/webcrypto/package.json new file mode 100644 index 0000000..a219aa9 --- /dev/null +++ b/gun-server/node_modules/@peculiar/webcrypto/package.json @@ -0,0 +1,105 @@ +{ + "name": "@peculiar/webcrypto", + "version": "1.5.0", + "description": "A WebCrypto Polyfill for NodeJS", + "repository": { + "type": "git", + "url": "https://github.com/PeculiarVentures/webcrypto.git" + }, + "files": [ + "build/**/*.{ts,js}", + "index.d.ts", + "README.md", + "LICENSE.md" + ], + "main": "build/webcrypto.js", + "module": "build/webcrypto.es.js", + "react-native": "build/webcrypto.es.js", + "types": "index.d.ts", + "scripts": { + "test": "mocha", + "coverage": "nyc npm test", + "coveralls": "nyc report --reporter=text-lcov | coveralls", + "build": "rollup -c", + "clear": "rimraf build/*", + "rebuild": "npm run clear && npm run build", + "lint": "eslint . --ext .ts", + "lint:fix": "eslint --fix . --ext .ts" + }, + "keywords": [ + "webcrypto", + "crypto", + "sha", + "rsa", + "ec", + "aes", + "des", + "hmac", + "pbkdf2", + "eddsa", + "x25519", + "ed25519", + "x448", + "ed448", + "shake128", + "shake256" + ], + "author": "PeculiarVentures", + "contributors": [ + "Miroshin Stepan" + ], + "license": "MIT", + "bugs": { + "url": "https://github.com/PeculiarVentures/webcrypto/issues" + }, + "homepage": "https://github.com/PeculiarVentures/webcrypto#readme", + "devDependencies": { + "@peculiar/webcrypto-test": "^1.0.7", + "@types/mocha": "^10.0.6", + "@types/node": "^20.12.12", + "@typescript-eslint/eslint-plugin": "^7.10.0", + "@typescript-eslint/parser": "^7.10.0", + "eslint": "^8.57.0", + "eslint-plugin-import": "^2.29.1", + "mocha": "^10.4.0", + "rimraf": "^5.0.7", + "rollup": "^4.17.2", + "rollup-plugin-typescript2": "^0.36.0", + "ts-node": "^10.9.2", + "typescript": "^5.4.5" + }, + "dependencies": { + "@peculiar/asn1-schema": "^2.3.8", + "@peculiar/json-schema": "^1.1.12", + "pvtsutils": "^1.3.5", + "tslib": "^2.6.2", + "webcrypto-core": "^1.8.0" + }, + "nyc": { + "extension": [ + ".ts", + ".tsx" + ], + "include": [ + "src/**/*.ts" + ], + "exclude": [ + "**/*.d.ts" + ], + "reporter": [ + "lcov", + "text-summary", + "html" + ] + }, + "engines": { + "node": ">=10.12.0" + }, + "mocha": { + "require": "ts-node/register", + "extension": [ + "ts" + ], + "spec": "test/**/*.ts" + } +} diff --git a/gun-server/node_modules/accepts/HISTORY.md b/gun-server/node_modules/accepts/HISTORY.md new file mode 100644 index 0000000..cb5990c --- /dev/null +++ b/gun-server/node_modules/accepts/HISTORY.md @@ -0,0 +1,243 @@ +1.3.8 / 2022-02-02 +================== + + * deps: mime-types@~2.1.34 + - deps: mime-db@~1.51.0 + * deps: negotiator@0.6.3 + +1.3.7 / 2019-04-29 +================== + + * deps: negotiator@0.6.2 + - Fix sorting charset, encoding, and language with extra parameters + +1.3.6 / 2019-04-28 +================== + + * deps: mime-types@~2.1.24 + - deps: mime-db@~1.40.0 + +1.3.5 / 2018-02-28 +================== + + * deps: mime-types@~2.1.18 + - deps: mime-db@~1.33.0 + +1.3.4 / 2017-08-22 +================== + + * deps: mime-types@~2.1.16 + - deps: mime-db@~1.29.0 + +1.3.3 / 2016-05-02 +================== + + * deps: mime-types@~2.1.11 + - deps: mime-db@~1.23.0 + * deps: negotiator@0.6.1 + - perf: improve `Accept` parsing speed + - perf: improve `Accept-Charset` parsing speed + - perf: improve `Accept-Encoding` parsing speed + - perf: improve `Accept-Language` parsing speed + +1.3.2 / 2016-03-08 +================== + + * deps: mime-types@~2.1.10 + - Fix extension of `application/dash+xml` + - Update primary extension for `audio/mp4` + - deps: mime-db@~1.22.0 + +1.3.1 / 2016-01-19 +================== + + * deps: mime-types@~2.1.9 + - deps: mime-db@~1.21.0 + +1.3.0 / 2015-09-29 +================== + + * deps: mime-types@~2.1.7 + - deps: mime-db@~1.19.0 + * deps: negotiator@0.6.0 + - Fix including type extensions in parameters in `Accept` parsing + - Fix parsing `Accept` parameters with quoted equals + - Fix parsing `Accept` parameters with quoted semicolons + - Lazy-load modules from main entry point + - perf: delay type concatenation until needed + - perf: enable strict mode + - perf: hoist regular expressions + - perf: remove closures getting spec properties + - perf: remove a closure from media type parsing + - perf: remove property delete from media type parsing + +1.2.13 / 2015-09-06 +=================== + + * deps: mime-types@~2.1.6 + - deps: mime-db@~1.18.0 + +1.2.12 / 2015-07-30 +=================== + + * deps: mime-types@~2.1.4 + - deps: mime-db@~1.16.0 + +1.2.11 / 2015-07-16 +=================== + + * deps: mime-types@~2.1.3 + - deps: mime-db@~1.15.0 + +1.2.10 / 2015-07-01 +=================== + + * deps: mime-types@~2.1.2 + - deps: mime-db@~1.14.0 + +1.2.9 / 2015-06-08 +================== + + * deps: mime-types@~2.1.1 + - perf: fix deopt during mapping + +1.2.8 / 2015-06-07 +================== + + * deps: mime-types@~2.1.0 + - deps: mime-db@~1.13.0 + * perf: avoid argument reassignment & argument slice + * perf: avoid negotiator recursive construction + * perf: enable strict mode + * perf: remove unnecessary bitwise operator + +1.2.7 / 2015-05-10 +================== + + * deps: negotiator@0.5.3 + - Fix media type parameter matching to be case-insensitive + +1.2.6 / 2015-05-07 +================== + + * deps: mime-types@~2.0.11 + - deps: mime-db@~1.9.1 + * deps: negotiator@0.5.2 + - Fix comparing media types with quoted values + - Fix splitting media types with quoted commas + +1.2.5 / 2015-03-13 +================== + + * deps: mime-types@~2.0.10 + - deps: mime-db@~1.8.0 + +1.2.4 / 2015-02-14 +================== + + * Support Node.js 0.6 + * deps: mime-types@~2.0.9 + - deps: mime-db@~1.7.0 + * deps: negotiator@0.5.1 + - Fix preference sorting to be stable for long acceptable lists + +1.2.3 / 2015-01-31 +================== + + * deps: mime-types@~2.0.8 + - deps: mime-db@~1.6.0 + +1.2.2 / 2014-12-30 +================== + + * deps: mime-types@~2.0.7 + - deps: mime-db@~1.5.0 + +1.2.1 / 2014-12-30 +================== + + * deps: mime-types@~2.0.5 + - deps: mime-db@~1.3.1 + +1.2.0 / 2014-12-19 +================== + + * deps: negotiator@0.5.0 + - Fix list return order when large accepted list + - Fix missing identity encoding when q=0 exists + - Remove dynamic building of Negotiator class + +1.1.4 / 2014-12-10 +================== + + * deps: mime-types@~2.0.4 + - deps: mime-db@~1.3.0 + +1.1.3 / 2014-11-09 +================== + + * deps: mime-types@~2.0.3 + - deps: mime-db@~1.2.0 + +1.1.2 / 2014-10-14 +================== + + * deps: negotiator@0.4.9 + - Fix error when media type has invalid parameter + +1.1.1 / 2014-09-28 +================== + + * deps: mime-types@~2.0.2 + - deps: mime-db@~1.1.0 + * deps: negotiator@0.4.8 + - Fix all negotiations to be case-insensitive + - Stable sort preferences of same quality according to client order + +1.1.0 / 2014-09-02 +================== + + * update `mime-types` + +1.0.7 / 2014-07-04 +================== + + * Fix wrong type returned from `type` when match after unknown extension + +1.0.6 / 2014-06-24 +================== + + * deps: negotiator@0.4.7 + +1.0.5 / 2014-06-20 +================== + + * fix crash when unknown extension given + +1.0.4 / 2014-06-19 +================== + + * use `mime-types` + +1.0.3 / 2014-06-11 +================== + + * deps: negotiator@0.4.6 + - Order by specificity when quality is the same + +1.0.2 / 2014-05-29 +================== + + * Fix interpretation when header not in request + * deps: pin negotiator@0.4.5 + +1.0.1 / 2014-01-18 +================== + + * Identity encoding isn't always acceptable + * deps: negotiator@~0.4.0 + +1.0.0 / 2013-12-27 +================== + + * Genesis diff --git a/gun-server/node_modules/accepts/LICENSE b/gun-server/node_modules/accepts/LICENSE new file mode 100644 index 0000000..0616607 --- /dev/null +++ b/gun-server/node_modules/accepts/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2015 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/gun-server/node_modules/accepts/README.md b/gun-server/node_modules/accepts/README.md new file mode 100644 index 0000000..82680c5 --- /dev/null +++ b/gun-server/node_modules/accepts/README.md @@ -0,0 +1,140 @@ +# accepts + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][github-actions-ci-image]][github-actions-ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Higher level content negotiation based on [negotiator](https://www.npmjs.com/package/negotiator). +Extracted from [koa](https://www.npmjs.com/package/koa) for general use. + +In addition to negotiator, it allows: + +- Allows types as an array or arguments list, ie `(['text/html', 'application/json'])` + as well as `('text/html', 'application/json')`. +- Allows type shorthands such as `json`. +- Returns `false` when no types match +- Treats non-existent headers as `*` + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install accepts +``` + +## API + +```js +var accepts = require('accepts') +``` + +### accepts(req) + +Create a new `Accepts` object for the given `req`. + +#### .charset(charsets) + +Return the first accepted charset. If nothing in `charsets` is accepted, +then `false` is returned. + +#### .charsets() + +Return the charsets that the request accepts, in the order of the client's +preference (most preferred first). + +#### .encoding(encodings) + +Return the first accepted encoding. If nothing in `encodings` is accepted, +then `false` is returned. + +#### .encodings() + +Return the encodings that the request accepts, in the order of the client's +preference (most preferred first). + +#### .language(languages) + +Return the first accepted language. If nothing in `languages` is accepted, +then `false` is returned. + +#### .languages() + +Return the languages that the request accepts, in the order of the client's +preference (most preferred first). + +#### .type(types) + +Return the first accepted type (and it is returned as the same text as what +appears in the `types` array). If nothing in `types` is accepted, then `false` +is returned. + +The `types` array can contain full MIME types or file extensions. Any value +that is not a full MIME types is passed to `require('mime-types').lookup`. + +#### .types() + +Return the types that the request accepts, in the order of the client's +preference (most preferred first). + +## Examples + +### Simple type negotiation + +This simple example shows how to use `accepts` to return a different typed +respond body based on what the client wants to accept. The server lists it's +preferences in order and will get back the best match between the client and +server. + +```js +var accepts = require('accepts') +var http = require('http') + +function app (req, res) { + var accept = accepts(req) + + // the order of this list is significant; should be server preferred order + switch (accept.type(['json', 'html'])) { + case 'json': + res.setHeader('Content-Type', 'application/json') + res.write('{"hello":"world!"}') + break + case 'html': + res.setHeader('Content-Type', 'text/html') + res.write('hello, world!') + break + default: + // the fallback is text/plain, so no need to specify it above + res.setHeader('Content-Type', 'text/plain') + res.write('hello, world!') + break + } + + res.end() +} + +http.createServer(app).listen(3000) +``` + +You can test this out with the cURL program: +```sh +curl -I -H'Accept: text/html' http://localhost:3000/ +``` + +## License + +[MIT](LICENSE) + +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/accepts/master +[coveralls-url]: https://coveralls.io/r/jshttp/accepts?branch=master +[github-actions-ci-image]: https://badgen.net/github/checks/jshttp/accepts/master?label=ci +[github-actions-ci-url]: https://github.com/jshttp/accepts/actions/workflows/ci.yml +[node-version-image]: https://badgen.net/npm/node/accepts +[node-version-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/accepts +[npm-url]: https://npmjs.org/package/accepts +[npm-version-image]: https://badgen.net/npm/v/accepts diff --git a/gun-server/node_modules/accepts/index.js b/gun-server/node_modules/accepts/index.js new file mode 100644 index 0000000..e9b2f63 --- /dev/null +++ b/gun-server/node_modules/accepts/index.js @@ -0,0 +1,238 @@ +/*! + * accepts + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var Negotiator = require('negotiator') +var mime = require('mime-types') + +/** + * Module exports. + * @public + */ + +module.exports = Accepts + +/** + * Create a new Accepts object for the given req. + * + * @param {object} req + * @public + */ + +function Accepts (req) { + if (!(this instanceof Accepts)) { + return new Accepts(req) + } + + this.headers = req.headers + this.negotiator = new Negotiator(req) +} + +/** + * Check if the given `type(s)` is acceptable, returning + * the best match when true, otherwise `undefined`, in which + * case you should respond with 406 "Not Acceptable". + * + * The `type` value may be a single mime type string + * such as "application/json", the extension name + * such as "json" or an array `["json", "html", "text/plain"]`. When a list + * or array is given the _best_ match, if any is returned. + * + * Examples: + * + * // Accept: text/html + * this.types('html'); + * // => "html" + * + * // Accept: text/*, application/json + * this.types('html'); + * // => "html" + * this.types('text/html'); + * // => "text/html" + * this.types('json', 'text'); + * // => "json" + * this.types('application/json'); + * // => "application/json" + * + * // Accept: text/*, application/json + * this.types('image/png'); + * this.types('png'); + * // => undefined + * + * // Accept: text/*;q=.5, application/json + * this.types(['html', 'json']); + * this.types('html', 'json'); + * // => "json" + * + * @param {String|Array} types... + * @return {String|Array|Boolean} + * @public + */ + +Accepts.prototype.type = +Accepts.prototype.types = function (types_) { + var types = types_ + + // support flattened arguments + if (types && !Array.isArray(types)) { + types = new Array(arguments.length) + for (var i = 0; i < types.length; i++) { + types[i] = arguments[i] + } + } + + // no types, return all requested types + if (!types || types.length === 0) { + return this.negotiator.mediaTypes() + } + + // no accept header, return first given type + if (!this.headers.accept) { + return types[0] + } + + var mimes = types.map(extToMime) + var accepts = this.negotiator.mediaTypes(mimes.filter(validMime)) + var first = accepts[0] + + return first + ? types[mimes.indexOf(first)] + : false +} + +/** + * Return accepted encodings or best fit based on `encodings`. + * + * Given `Accept-Encoding: gzip, deflate` + * an array sorted by quality is returned: + * + * ['gzip', 'deflate'] + * + * @param {String|Array} encodings... + * @return {String|Array} + * @public + */ + +Accepts.prototype.encoding = +Accepts.prototype.encodings = function (encodings_) { + var encodings = encodings_ + + // support flattened arguments + if (encodings && !Array.isArray(encodings)) { + encodings = new Array(arguments.length) + for (var i = 0; i < encodings.length; i++) { + encodings[i] = arguments[i] + } + } + + // no encodings, return all requested encodings + if (!encodings || encodings.length === 0) { + return this.negotiator.encodings() + } + + return this.negotiator.encodings(encodings)[0] || false +} + +/** + * Return accepted charsets or best fit based on `charsets`. + * + * Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5` + * an array sorted by quality is returned: + * + * ['utf-8', 'utf-7', 'iso-8859-1'] + * + * @param {String|Array} charsets... + * @return {String|Array} + * @public + */ + +Accepts.prototype.charset = +Accepts.prototype.charsets = function (charsets_) { + var charsets = charsets_ + + // support flattened arguments + if (charsets && !Array.isArray(charsets)) { + charsets = new Array(arguments.length) + for (var i = 0; i < charsets.length; i++) { + charsets[i] = arguments[i] + } + } + + // no charsets, return all requested charsets + if (!charsets || charsets.length === 0) { + return this.negotiator.charsets() + } + + return this.negotiator.charsets(charsets)[0] || false +} + +/** + * Return accepted languages or best fit based on `langs`. + * + * Given `Accept-Language: en;q=0.8, es, pt` + * an array sorted by quality is returned: + * + * ['es', 'pt', 'en'] + * + * @param {String|Array} langs... + * @return {Array|String} + * @public + */ + +Accepts.prototype.lang = +Accepts.prototype.langs = +Accepts.prototype.language = +Accepts.prototype.languages = function (languages_) { + var languages = languages_ + + // support flattened arguments + if (languages && !Array.isArray(languages)) { + languages = new Array(arguments.length) + for (var i = 0; i < languages.length; i++) { + languages[i] = arguments[i] + } + } + + // no languages, return all requested languages + if (!languages || languages.length === 0) { + return this.negotiator.languages() + } + + return this.negotiator.languages(languages)[0] || false +} + +/** + * Convert extnames to mime. + * + * @param {String} type + * @return {String} + * @private + */ + +function extToMime (type) { + return type.indexOf('/') === -1 + ? mime.lookup(type) + : type +} + +/** + * Check if mime is valid. + * + * @param {String} type + * @return {String} + * @private + */ + +function validMime (type) { + return typeof type === 'string' +} diff --git a/gun-server/node_modules/accepts/package.json b/gun-server/node_modules/accepts/package.json new file mode 100644 index 0000000..0f2d15d --- /dev/null +++ b/gun-server/node_modules/accepts/package.json @@ -0,0 +1,47 @@ +{ + "name": "accepts", + "description": "Higher-level content negotiation", + "version": "1.3.8", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)" + ], + "license": "MIT", + "repository": "jshttp/accepts", + "dependencies": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + }, + "devDependencies": { + "deep-equal": "1.0.1", + "eslint": "7.32.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.25.4", + "eslint-plugin-markdown": "2.2.1", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "4.3.1", + "eslint-plugin-standard": "4.1.0", + "mocha": "9.2.0", + "nyc": "15.1.0" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec --check-leaks --bail test/", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + }, + "keywords": [ + "content", + "negotiation", + "accept", + "accepts" + ] +} diff --git a/gun-server/node_modules/array-flatten/LICENSE b/gun-server/node_modules/array-flatten/LICENSE new file mode 100644 index 0000000..983fbe8 --- /dev/null +++ b/gun-server/node_modules/array-flatten/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Blake Embrey (hello@blakeembrey.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/gun-server/node_modules/array-flatten/README.md b/gun-server/node_modules/array-flatten/README.md new file mode 100644 index 0000000..91fa5b6 --- /dev/null +++ b/gun-server/node_modules/array-flatten/README.md @@ -0,0 +1,43 @@ +# Array Flatten + +[![NPM version][npm-image]][npm-url] +[![NPM downloads][downloads-image]][downloads-url] +[![Build status][travis-image]][travis-url] +[![Test coverage][coveralls-image]][coveralls-url] + +> Flatten an array of nested arrays into a single flat array. Accepts an optional depth. + +## Installation + +``` +npm install array-flatten --save +``` + +## Usage + +```javascript +var flatten = require('array-flatten') + +flatten([1, [2, [3, [4, [5], 6], 7], 8], 9]) +//=> [1, 2, 3, 4, 5, 6, 7, 8, 9] + +flatten([1, [2, [3, [4, [5], 6], 7], 8], 9], 2) +//=> [1, 2, 3, [4, [5], 6], 7, 8, 9] + +(function () { + flatten(arguments) //=> [1, 2, 3] +})(1, [2, 3]) +``` + +## License + +MIT + +[npm-image]: https://img.shields.io/npm/v/array-flatten.svg?style=flat +[npm-url]: https://npmjs.org/package/array-flatten +[downloads-image]: https://img.shields.io/npm/dm/array-flatten.svg?style=flat +[downloads-url]: https://npmjs.org/package/array-flatten +[travis-image]: https://img.shields.io/travis/blakeembrey/array-flatten.svg?style=flat +[travis-url]: https://travis-ci.org/blakeembrey/array-flatten +[coveralls-image]: https://img.shields.io/coveralls/blakeembrey/array-flatten.svg?style=flat +[coveralls-url]: https://coveralls.io/r/blakeembrey/array-flatten?branch=master diff --git a/gun-server/node_modules/array-flatten/array-flatten.js b/gun-server/node_modules/array-flatten/array-flatten.js new file mode 100644 index 0000000..089117b --- /dev/null +++ b/gun-server/node_modules/array-flatten/array-flatten.js @@ -0,0 +1,64 @@ +'use strict' + +/** + * Expose `arrayFlatten`. + */ +module.exports = arrayFlatten + +/** + * Recursive flatten function with depth. + * + * @param {Array} array + * @param {Array} result + * @param {Number} depth + * @return {Array} + */ +function flattenWithDepth (array, result, depth) { + for (var i = 0; i < array.length; i++) { + var value = array[i] + + if (depth > 0 && Array.isArray(value)) { + flattenWithDepth(value, result, depth - 1) + } else { + result.push(value) + } + } + + return result +} + +/** + * Recursive flatten function. Omitting depth is slightly faster. + * + * @param {Array} array + * @param {Array} result + * @return {Array} + */ +function flattenForever (array, result) { + for (var i = 0; i < array.length; i++) { + var value = array[i] + + if (Array.isArray(value)) { + flattenForever(value, result) + } else { + result.push(value) + } + } + + return result +} + +/** + * Flatten an array, with the ability to define a depth. + * + * @param {Array} array + * @param {Number} depth + * @return {Array} + */ +function arrayFlatten (array, depth) { + if (depth == null) { + return flattenForever(array, []) + } + + return flattenWithDepth(array, [], depth) +} diff --git a/gun-server/node_modules/array-flatten/package.json b/gun-server/node_modules/array-flatten/package.json new file mode 100644 index 0000000..1a24e2a --- /dev/null +++ b/gun-server/node_modules/array-flatten/package.json @@ -0,0 +1,39 @@ +{ + "name": "array-flatten", + "version": "1.1.1", + "description": "Flatten an array of nested arrays into a single flat array", + "main": "array-flatten.js", + "files": [ + "array-flatten.js", + "LICENSE" + ], + "scripts": { + "test": "istanbul cover _mocha -- -R spec" + }, + "repository": { + "type": "git", + "url": "git://github.com/blakeembrey/array-flatten.git" + }, + "keywords": [ + "array", + "flatten", + "arguments", + "depth" + ], + "author": { + "name": "Blake Embrey", + "email": "hello@blakeembrey.com", + "url": "http://blakeembrey.me" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/blakeembrey/array-flatten/issues" + }, + "homepage": "https://github.com/blakeembrey/array-flatten", + "devDependencies": { + "istanbul": "^0.3.13", + "mocha": "^2.2.4", + "pre-commit": "^1.0.7", + "standard": "^3.7.3" + } +} diff --git a/gun-server/node_modules/asn1js/LICENSE b/gun-server/node_modules/asn1js/LICENSE new file mode 100644 index 0000000..8d57190 --- /dev/null +++ b/gun-server/node_modules/asn1js/LICENSE @@ -0,0 +1,30 @@ +Copyright (c) 2014, GMO GlobalSign +Copyright (c) 2015-2022, Peculiar Ventures +All rights reserved. + +Author 2014-2019, Yury Strozhevsky + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, this + list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. + +* Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/gun-server/node_modules/asn1js/README.md b/gun-server/node_modules/asn1js/README.md new file mode 100644 index 0000000..c5535ce --- /dev/null +++ b/gun-server/node_modules/asn1js/README.md @@ -0,0 +1,177 @@ +## ASN1js + +[![License](https://img.shields.io/badge/license-BSD-green.svg?style=flat)](https://raw.githubusercontent.com/PeculiarVentures/ASN1.js/master/LICENSE) [![Test](https://github.com/PeculiarVentures/ASN1.js/actions/workflows/test.yml/badge.svg)](https://github.com/PeculiarVentures/ASN1.js/actions/workflows/test.yml) [![NPM version](https://badge.fury.io/js/asn1js.svg)](http://badge.fury.io/js/asn1js) [![Coverage Status](https://coveralls.io/repos/github/PeculiarVentures/ASN1.js/badge.svg?branch=master)](https://coveralls.io/github/PeculiarVentures/ASN1.js?branch=master) + +[![NPM](https://nodei.co/npm-dl/asn1js.png?months=3&height=2)](https://nodei.co/npm/asn1js/) + +Abstract Syntax Notation One (ASN.1) is a standard and notation that describes rules and structures for representing, encoding, transmitting, and decoding data in telecommunications and computer networking. [ASN1js] is a pure JavaScript library implementing this standard. ASN.1 is the basis of all X.509 related data structures and numerous other protocols used on the web. + +## Important Information for ASN1.js V1 Users +ASN1.js V2 (ES2015 version) is **incompatible** with ASN1.js V1 code. + +## Introduction + +[ASN1js] is the first library for [BER] encoding/decoding in Javascript designed for browser use. [BER] is the basic encoding rules for [ASN.1] that all others are based on, [DER] is the encoding rules used by PKI applications - it is a subset of [BER]. The [ASN1js] library was tested against [freely available ASN.1:2008 test suite], with some limitations related to JavaScript language. + +## Features of the library + +* Based on latest features of JavaScript language from ES2015 standard; +* [ASN1js] is a "base layer" for full-featured JS library [PKIjs], which is using Web Cryptography API and has all classes, necessary to work with PKI-related data; +* Fully object-oriented library. Inheritance is using everywhere inside the lib; +* Working with HTML5 data objects (ArrayBuffer, Uint8Array etc.); +* Working with all ASN.1:2008 types; +* Working with [BER] encoded data; +* All types inside the library constantly stores information about all ASN.1 sub blocks (tag block, length block or value block); +* User may have access to any byte inside any ASN.1 sub-block; +* Any sub-block may have unlimited length, as it described in ASN.1 standard (even "tag block"); +* Ability to work with ASN.1 string date types (including all "international" strings like UniversalString, BMPString, UTF8String) by passing native JavaScript strings into constructors. And vice versa - all initially parsed data of ASN.1 string types right after decoding automatically converts into native JavaScript strings; +* Same with ASN.1 date-time types: for major types like UTCTime and GeneralizedTime there are automatic conversion between "JS date type - ASN.1 date-time type" + vice versa; +* Same with ASN.1 OBJECT-IDENTIFIER (OID) data-type: you can initialize OID by JavaScript string and can get string representation via calling "oid.valueBlock.toString()"; +* Working with "easy-to-understand" ASN.1 schemas (pre-defined or built by user); +* Has special types to work with ASN.1 schemas: + * Any + * Choice + * Repeated +* User can name any block inside ASN.1 schema and easily get information by name; +* Ability to parse internal data inside a primitively encoded data types and automatically validate it against special schema; +* All types inside library are dynamic; +* All types can be initialized in static or dynamic ways. +* [ASN1js] fully tested against [ASN.1:2008 TestSuite]. + +## Examples + +### How to create new ASN. structures +```javascript +var sequence = new asn1js.Sequence(); +sequence.valueBlock.value.push(new asn1js.Integer({ value: 1 })); + +var sequence_buffer = sequence.toBER(false); // Encode current sequence to BER (in ArrayBuffer) +var current_size = sequence_buffer.byteLength; + +var integer_data = new ArrayBuffer(8); +var integer_view = new Uint8Array(integer_data); +integer_view[0] = 0x01; +integer_view[1] = 0x01; +integer_view[2] = 0x01; +integer_view[3] = 0x01; +integer_view[4] = 0x01; +integer_view[5] = 0x01; +integer_view[6] = 0x01; +integer_view[7] = 0x01; + +sequence.valueBlock.value.push(new asn1js.Integer({ + isHexOnly: true, + valueHex: integer_data, +})); // Put too long for decoding Integer value + +sequence_buffer = sequence.toBER(); +current_size = sequence_buffer.byteLength; +``` + +### How to create new ASN.1 structures by calling constructors with parameters +```javascript +var sequence2 = new asn1js.Sequence({ + value: [ + new asn1js.Integer({ value: 1 }), + new asn1js.Integer({ + isHexOnly: true, + valueHex: integer_data + }), + ] +}); +``` + +### How to validate ASN.1 against pre-defined schema +```javascript +var asn1_schema = new asn1js.Sequence({ + name: "block1", + value: [ + new asn1js.Null({ + name: "block2" + }), + new asn1js.Integer({ + name: "block3", + optional: true // This block is absent inside data, but it's "optional". Hence verification against the schema will be passed. + }) + ] +}); + +var variant1 = org.pkijs.verifySchema(encoded_sequence, asn1_schema); // Verify schema together with decoding of raw data +var variant1_verified = variant1.verified; +var variant1_result = variant1.result; // Verified decoded data with all block names inside +``` + +### How to use "internal schemas" for primitively encoded data types +```javascript +var primitive_octetstring = new asn1js.OctetString({ valueHex: encoded_sequence }); // Create a primitively encoded OctetString where internal data is an encoded Sequence + +var asn1_schema_internal = new asn1js.OctetString({ + name: "outer_block", + primitiveSchema: new asn1js.Sequence({ + name: "block1", + value: [ + new asn1js.Null({ + name: "block2" + }) + ] + }) +}); + +var variant6 = org.pkijs.compareSchema(primitive_octetstring, primitive_octetstring, asn1_schema_internal); +var variant6_verified = variant4.verified; +var variant6_block1_tag_num = variant6.result.block1.idBlock.tagNumber; +var variant6_block2_tag_num = variant6.result.block2.idBlock.tagNumber; +``` + +More examples could be found in "examples" directory or inside [PKIjs] library. + +## Related source code + +* [C++ ASN1:2008 BER coder/decoder](https://github.com/YuryStrozhevsky/C-plus-plus-ASN.1-2008-coder-decoder) - the "father" of [ASN1js] project; +* [Freely available ASN.1:2008 test suite](https://github.com/YuryStrozhevsky/ASN1-2008-free-test-suite) - the suite which can help you to validate (and better understand) any ASN.1 coder/decoder; +* [NPM package for ASN.1:2008 test suite](https://github.com/YuryStrozhevsky/asn1-test-suite) + +## Suitability +There are several commercial products, enterprise solutions as well as open source project based on versions of ASN1js. You should, however, do your own code and security review before utilization in a production application before utilizing any open source library to ensure it will meet your needs. + +## License + +Copyright (c) 2014, [GMO GlobalSign](http://www.globalsign.com/) +Copyright (c) 2015-2022, [Peculiar Ventures](http://peculiarventures.com/) +All rights reserved. + +Author 2014-2018, [Yury Strozhevsky](http://www.strozhevsky.com/). + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors + may be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, +INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY +OF SUCH DAMAGE. + + +[ASN.1]: http://en.wikipedia.org/wiki/Abstract_Syntax_Notation_One +[ASN1js]: http://asn1js.org/ +[PKIjs]: http://pkijs.org/ +[BER]: http://en.wikipedia.org/wiki/X.690#BER_encoding +[DER]: http://en.wikipedia.org/wiki/X.690#DER_encoding +[freely available ASN.1:2008 test suite]: http://www.strozhevsky.com/free_docs/free_asn1_testsuite_descr.pdf +[ASN.1:2008 TestSuite]: https://github.com/YuryStrozhevsky/asn1-test-suite diff --git a/gun-server/node_modules/asn1js/build/index.d.ts b/gun-server/node_modules/asn1js/build/index.d.ts new file mode 100644 index 0000000..5e17a58 --- /dev/null +++ b/gun-server/node_modules/asn1js/build/index.d.ts @@ -0,0 +1,1358 @@ +/*! + * Copyright (c) 2014, GMO GlobalSign + * Copyright (c) 2015-2022, Peculiar Ventures + * All rights reserved. + * + * Author 2014-2019, Yury Strozhevsky + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * * Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +import * as pvtsutils from 'pvtsutils'; + +interface IBerConvertible { + /** + * Base function for converting block from BER encoded array of bytes + * @param inputBuffer ASN.1 BER encoded array + * @param inputOffset Offset in ASN.1 BER encoded array where decoding should be started + * @param inputLength Maximum length of array of bytes which can be using in this function + * @returns Offset after least decoded byte + */ + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number): number; + /** + * Encoding of current ASN.1 block into ASN.1 encoded array (BER rules) + * @param sizeOnly Flag that we need only a size of encoding, not a real array of bytes + * @returns ASN.1 BER encoded array + */ + toBER(sizeOnly?: boolean): ArrayBuffer; +} +interface IDerConvertible { + /** + * Base function for converting block from DER encoded array of bytes + * @param inputBuffer ASN.1 DER encoded array + * @param inputOffset Offset in ASN.1 DER encoded array where decoding should be started + * @param inputLength Maximum length of array of bytes which can be using in this function + * @param expectedLength Expected length of converted VALUE_HEX buffer + * @returns Offset after least decoded byte + */ + fromDER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number, expectedLength?: number): number; + /** + * Encoding of current ASN.1 block into ASN.1 encoded array (DER rules) + * @param sizeOnly Flag that we need only a size of encoding, not a real array of bytes + * @returns ASN.1 DER encoded array + */ + toDER(sizeOnly?: boolean): ArrayBuffer; +} +interface IStringConvertible { + /** + * Returns a string representation of an object + * @returns String representation of the class object + */ + toString(): string; + /** + * Creates a class object from the string + * @param data Input string to convert from + */ + fromString(data: string): void; +} +interface IDateConvertible { + /** + * Converts a class object into the JavaScrip Date Object + * @returns Date object + */ + toDate(): Date; + /** + * Creates a class object from the JavaScript Date object + * @param date Date object + */ + fromDate(date: Date): void; +} + +declare class ViewWriter { + items: ArrayBuffer[]; + /** + * Writes buffer + * @param buf + */ + write(buf: ArrayBuffer): void; + /** + * Concatenates all buffers + * @returns Concatenated buffer + */ + final(): ArrayBuffer; +} + +interface ILocalBaseBlock { + blockLength: number; + error: string; + warnings: string[]; +} +interface LocalBaseBlockJson extends ILocalBaseBlock { + blockName: string; + valueBeforeDecode: string; +} +interface LocalBaseBlockParams extends Partial { + valueBeforeDecode?: pvtsutils.BufferSource; +} +interface LocalBaseBlockConstructor { + new (...args: any[]): T; + prototype: T; + NAME: string; + blockName(): string; +} +/** + * Class used as a base block for all remaining ASN.1 classes + */ +declare class LocalBaseBlock implements ILocalBaseBlock { + /** + * Name of the block + */ + static NAME: string; + /** + * Aux function, need to get a block name. Need to have it here for inheritance + * @returns Returns name of the block + */ + static blockName(): string; + blockLength: number; + error: string; + warnings: string[]; + /** + * @deprecated since version 3.0.0 + */ + get valueBeforeDecode(): ArrayBuffer; + /** + * @deprecated since version 3.0.0 + */ + set valueBeforeDecode(value: ArrayBuffer); + /** + * @since 3.0.0 + */ + valueBeforeDecodeView: Uint8Array; + /** + * Creates and initializes an object instance of that class + * @param param0 Initialization parameters + */ + constructor({ blockLength, error, warnings, valueBeforeDecode, }?: LocalBaseBlockParams); + /** + * Returns a JSON representation of an object + * @returns JSON object + */ + toJSON(): LocalBaseBlockJson; +} + +interface IHexBlock { + isHexOnly: boolean; + valueHex: pvtsutils.BufferSource; +} +interface HexBlockJson extends Omit { + valueHex: string; +} +declare type HexBlockParams = Partial; +/** + * Class used as a base block for all remaining ASN.1 classes + */ +declare function HexBlock(BaseClass: T): { + new (...args: any[]): { + isHexOnly: boolean; + /** + * Binary data in ArrayBuffer representation + * + * @deprecated since version 3.0.0 + */ + valueHex: ArrayBuffer; + /** + * Binary data in Uint8Array representation + * + * @since 3.0.0 + */ + valueHexView: Uint8Array; + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + /** + * Returns a JSON representation of an object + * @returns JSON object + */ + toJSON(): { + isHexOnly: boolean; + valueHex: string; + blockName: string; + valueBeforeDecode: string; + blockLength: number; + error: string; + warnings: string[]; + }; + blockLength: number; + error: string; + warnings: string[]; + /** + * Binary data in ArrayBuffer representation + * + * @deprecated since version 3.0.0 + */ + valueBeforeDecode: ArrayBuffer; + valueBeforeDecodeView: Uint8Array; + }; + NAME: string; + blockName(): string; +} & T; + +declare type IValueBlock = ILocalBaseBlock; +declare type ValueBlockParams = LocalBaseBlockParams; +declare type ValueBlockJson = LocalBaseBlockJson; +declare class ValueBlock extends LocalBaseBlock implements IValueBlock, IBerConvertible { + static NAME: string; + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean, writer?: ViewWriter): ArrayBuffer; +} + +interface ILocalIdentificationBlock { + tagClass: number; + tagNumber: number; + isConstructed: boolean; +} +interface LocalIdentificationBlockParams { + idBlock?: Partial & HexBlockParams; +} +interface LocalIdentificationBlockJson extends HexBlockJson, LocalBaseBlockJson, ILocalIdentificationBlock { +} +declare const LocalIdentificationBlock_base: { + new (...args: any[]): { + isHexOnly: boolean; + valueHex: ArrayBuffer; + valueHexView: Uint8Array; + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + toJSON(): { + isHexOnly: boolean; + valueHex: string; + blockName: string; + valueBeforeDecode: string; + blockLength: number; + error: string; + warnings: string[]; + }; + blockLength: number; + error: string; + warnings: string[]; + valueBeforeDecode: ArrayBuffer; + valueBeforeDecodeView: Uint8Array; + }; + NAME: string; + blockName(): string; +} & typeof LocalBaseBlock; +declare class LocalIdentificationBlock extends LocalIdentificationBlock_base implements ILocalIdentificationBlock { + static NAME: string; + tagClass: number; + tagNumber: number; + isConstructed: boolean; + constructor({ idBlock, }?: LocalIdentificationBlockParams); + toBER(sizeOnly?: boolean): ArrayBuffer; + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number): number; + toJSON(): LocalIdentificationBlockJson; +} +interface LocalIdentificationBlock { + /** + * @deprecated since version 3.0.0 + */ + valueBeforeDecode: ArrayBuffer; + /** + * Binary data in ArrayBuffer representation + * + * @deprecated since version 3.0.0 + */ + valueHex: ArrayBuffer; +} + +interface ILocalLengthBlock { + isIndefiniteForm: boolean; + longFormUsed: boolean; + length: number; +} +interface LocalLengthBlockParams { + lenBlock?: Partial; +} +interface LocalLengthBlockJson extends LocalBaseBlockJson, ILocalLengthBlock { + isIndefiniteForm: boolean; + longFormUsed: boolean; + length: number; +} +declare class LocalLengthBlock extends LocalBaseBlock implements ILocalLengthBlock, IBerConvertible { + static NAME: string; + isIndefiniteForm: boolean; + longFormUsed: boolean; + length: number; + constructor({ lenBlock, }?: LocalLengthBlockParams); + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + toJSON(): LocalLengthBlockJson; +} + +interface IBaseBlock { + name: string; + optional: boolean; + primitiveSchema?: BaseBlock; +} +interface BaseBlockParams extends LocalBaseBlockParams, LocalIdentificationBlockParams, LocalLengthBlockParams, Partial { +} +interface ValueBlockConstructor { + new (...args: any[]): T; +} +interface BaseBlockJson extends LocalBaseBlockJson, Omit { + idBlock: LocalIdentificationBlockJson; + lenBlock: LocalLengthBlockJson; + valueBlock: T; + primitiveSchema?: BaseBlockJson; +} +declare type StringEncoding = "ascii" | "hex"; +declare class BaseBlock extends LocalBaseBlock implements IBaseBlock, IBerConvertible { + static NAME: string; + idBlock: LocalIdentificationBlock; + lenBlock: LocalLengthBlock; + valueBlock: T; + name: string; + optional: boolean; + primitiveSchema?: BaseBlock; + constructor({ name, optional, primitiveSchema, ...parameters }?: BaseBlockParams, valueBlockType?: ValueBlockConstructor); + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean, writer?: ViewWriter): ArrayBuffer; + toJSON(): BaseBlockJson; + toString(encoding?: StringEncoding): string; + protected onAsciiEncoding(): string; + /** + * Determines whether two object instances are equal + * @param other Object to compare with the current object + */ + isEqual(other: unknown): other is this; +} + +declare type LocalSimpleStringValueBlockParams = LocalStringValueBlockParams; +declare type LocalSimpleStringValueBlockJson = LocalStringValueBlockJson; +declare class LocalSimpleStringValueBlock extends LocalStringValueBlock { + static NAME: string; +} + +interface LocalSimpleStringBlockParams extends BaseBlockParams, LocalSimpleStringValueBlockParams { +} +declare type LocalSimpleStringBlockJson = LocalSimpleStringValueBlockJson; +declare class LocalSimpleStringBlock extends BaseStringBlock { + static NAME: string; + constructor({ ...parameters }?: LocalSimpleStringBlockParams); + fromBuffer(inputBuffer: ArrayBuffer | Uint8Array): void; + fromString(inputString: string): void; +} + +declare type LocalUtf8StringValueBlockParams = LocalSimpleStringBlockParams; +declare type LocalUtf8StringValueBlockJson = LocalSimpleStringBlockJson; +declare class LocalUtf8StringValueBlock extends LocalSimpleStringBlock { + static NAME: string; + fromBuffer(inputBuffer: ArrayBuffer | Uint8Array): void; + fromString(inputString: string): void; +} + +interface ILocalStringValueBlock { + value: string; +} +interface LocalStringValueBlockParams extends Omit, ValueBlockParams, Partial { +} +interface LocalStringValueBlockJson extends HexBlockJson, ValueBlockJson, ILocalStringValueBlock { +} +declare const LocalStringValueBlock_base: { + new (...args: any[]): { + isHexOnly: boolean; + valueHex: ArrayBuffer; + valueHexView: Uint8Array; + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + toJSON(): { + isHexOnly: boolean; + valueHex: string; + blockName: string; + valueBeforeDecode: string; + blockLength: number; + error: string; + warnings: string[]; + }; + blockLength: number; + error: string; + warnings: string[]; + valueBeforeDecode: ArrayBuffer; + valueBeforeDecodeView: Uint8Array; + }; + NAME: string; + blockName(): string; +} & typeof ValueBlock; +declare abstract class LocalStringValueBlock extends LocalStringValueBlock_base implements ILocalStringValueBlock { + static NAME: string; + value: string; + constructor({ ...parameters }?: LocalUtf8StringValueBlockParams); + toJSON(): LocalUtf8StringValueBlockJson; +} +interface LocalStringValueBlock { + /** + * @deprecated since version 3.0.0 + */ + valueBeforeDecode: ArrayBuffer; + /** + * Binary data in ArrayBuffer representation + * + * @deprecated since version 3.0.0 + */ + valueHex: ArrayBuffer; +} + +interface BaseStringBlockParams extends BaseBlockParams, LocalStringValueBlockParams { +} +declare type BaseStringBlockJson = LocalStringValueBlockJson; +declare abstract class BaseStringBlock extends BaseBlock implements IStringConvertible { + static NAME: string; + /** + * String value + * @since 3.0.0 + */ + getValue(): string; + /** + * String value + * @param value String value + * @since 3.0.0 + */ + setValue(value: string): void; + constructor({ value, ...parameters }: BaseStringBlockParams | undefined, stringValueBlockType: new () => T); + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number): number; + /** + * Function converting ArrayBuffer into ASN.1 internal string + * @param inputBuffer ASN.1 BER encoded array + */ + abstract fromBuffer(inputBuffer: ArrayBuffer | Uint8Array): void; + abstract fromString(inputString: string): void; + protected onAsciiEncoding(): string; +} + +interface LocalPrimitiveValueBlockParams extends HexBlockParams, ValueBlockParams { +} +interface LocalPrimitiveValueBlockJson extends HexBlockJson, ValueBlockJson { +} +declare const LocalPrimitiveValueBlock_base: { + new (...args: any[]): { + isHexOnly: boolean; + valueHex: ArrayBuffer; + valueHexView: Uint8Array; + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + toJSON(): { + isHexOnly: boolean; + valueHex: string; + blockName: string; + valueBeforeDecode: string; + blockLength: number; + error: string; + warnings: string[]; + }; + blockLength: number; + error: string; + warnings: string[]; + valueBeforeDecode: ArrayBuffer; + valueBeforeDecodeView: Uint8Array; + }; + NAME: string; + blockName(): string; +} & typeof ValueBlock; +declare class LocalPrimitiveValueBlock extends LocalPrimitiveValueBlock_base { + static NAME: string; + constructor({ isHexOnly, ...parameters }?: LocalPrimitiveValueBlockParams); +} +interface LocalPrimitiveValueBlock { + /** + * @deprecated since version 3.0.0 + */ + valueBeforeDecode: ArrayBuffer; + /** + * Binary data in ArrayBuffer representation + * + * @deprecated since version 3.0.0 + */ + valueHex: ArrayBuffer; +} + +interface PrimitiveParams extends BaseBlockParams, LocalPrimitiveValueBlockParams { +} +declare type PrimitiveJson = BaseBlockJson; +declare class Primitive extends BaseBlock { + static NAME: string; + constructor(parameters?: PrimitiveParams); +} + +interface IAny { + name: string; + optional: boolean; +} +declare type AnyParams = Partial; +declare class Any implements IAny { + name: string; + optional: boolean; + constructor({ name, optional, }?: AnyParams); +} + +declare type ConstructedItem = BaseBlock | Any; +interface ILocalConstructedValueBlock { + value: ConstructedItem[]; + isIndefiniteForm: boolean; +} +interface LocalConstructedValueBlockParams extends ValueBlockParams, Partial { +} +interface LocalConstructedValueBlockJson extends LocalBaseBlockJson, Omit { + value: LocalBaseBlockJson[]; +} +declare class LocalConstructedValueBlock extends ValueBlock implements ILocalConstructedValueBlock { + static NAME: string; + value: BaseBlock[]; + isIndefiniteForm: boolean; + constructor({ value, isIndefiniteForm, ...parameters }?: LocalConstructedValueBlockParams); + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean, writer?: ViewWriter): ArrayBuffer; + toJSON(): LocalConstructedValueBlockJson; +} + +interface ConstructedParams extends BaseBlockParams, LocalConstructedValueBlockParams { +} +declare type ConstructedJson = BaseBlockJson; +declare class Constructed extends BaseBlock { + static NAME: string; + constructor(parameters?: ConstructedParams); + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number): number; +} + +declare class LocalEndOfContentValueBlock extends ValueBlock { + static override: string; + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean): ArrayBuffer; +} + +declare type EndOfContentParams = BaseBlockParams; +declare type EndOfContentJson = BaseBlockJson; +declare class EndOfContent extends BaseBlock { + static NAME: string; + constructor(parameters?: EndOfContentParams); +} + +declare type NullParams = BaseBlockParams; +declare type NullJson = BaseBlockJson; +declare class Null extends BaseBlock { + static NAME: string; + constructor(parameters?: NullParams); + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean, writer?: ViewWriter): ArrayBuffer; + protected onAsciiEncoding(): string; +} + +interface ILocalBooleanValueBlock { + value: boolean; +} +interface LocalBooleanValueBlockParams extends ValueBlockParams, HexBlockParams, Partial { +} +interface LocalBooleanValueBlockJson extends ValueBlockJson, HexBlockJson, ILocalBooleanValueBlock { +} +declare const LocalBooleanValueBlock_base: { + new (...args: any[]): { + isHexOnly: boolean; + valueHex: ArrayBuffer; + valueHexView: Uint8Array; + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + toJSON(): { + isHexOnly: boolean; + valueHex: string; + blockName: string; + valueBeforeDecode: string; + blockLength: number; + error: string; + warnings: string[]; + }; + blockLength: number; + error: string; + warnings: string[]; + valueBeforeDecode: ArrayBuffer; + valueBeforeDecodeView: Uint8Array; + }; + NAME: string; + blockName(): string; +} & typeof ValueBlock; +declare class LocalBooleanValueBlock extends LocalBooleanValueBlock_base implements ILocalBooleanValueBlock { + static NAME: string; + get value(): boolean; + set value(value: boolean); + constructor({ value, ...parameters }?: LocalBooleanValueBlockParams); + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number): number; + toBER(): ArrayBuffer; + toJSON(): LocalBooleanValueBlockJson; +} +interface LocalBooleanValueBlock { + /** + * @deprecated since version 3.0.0 + */ + valueBeforeDecode: ArrayBuffer; + /** + * Binary data in ArrayBuffer representation + * + * @deprecated since version 3.0.0 + */ + valueHex: ArrayBuffer; +} + +interface BooleanParams extends BaseBlockParams, LocalBooleanValueBlockParams { +} +declare type BooleanJson = BaseBlockJson; +declare class Boolean extends BaseBlock { + /** + * Gets value + * @since 3.0.0 + */ + getValue(): boolean; + /** + * Sets value + * @param value Boolean value + * @since 3.0.0 + */ + setValue(value: boolean): void; + static NAME: string; + constructor(parameters?: BooleanParams); + protected onAsciiEncoding(): string; +} + +interface ILocalOctetStringValueBlock { + isConstructed: boolean; +} +interface LocalOctetStringValueBlockParams extends HexBlockParams, LocalConstructedValueBlockParams, Partial { + value?: OctetString[]; +} +interface LocalOctetStringValueBlockJson extends HexBlockJson, LocalConstructedValueBlockJson, ILocalOctetStringValueBlock { +} +declare const LocalOctetStringValueBlock_base: { + new (...args: any[]): { + isHexOnly: boolean; + valueHex: ArrayBuffer; + valueHexView: Uint8Array; + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + toJSON(): { + isHexOnly: boolean; + valueHex: string; + blockName: string; + valueBeforeDecode: string; + blockLength: number; + error: string; + warnings: string[]; + }; + blockLength: number; + error: string; + warnings: string[]; + valueBeforeDecode: ArrayBuffer; + valueBeforeDecodeView: Uint8Array; + }; + NAME: string; + blockName(): string; +} & typeof LocalConstructedValueBlock; +declare class LocalOctetStringValueBlock extends LocalOctetStringValueBlock_base { + static NAME: string; + isConstructed: boolean; + constructor({ isConstructed, ...parameters }?: LocalOctetStringValueBlockParams); + fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean, writer?: ViewWriter): ArrayBuffer; + toJSON(): LocalOctetStringValueBlockJson; +} +interface LocalOctetStringValueBlock { + /** + * @deprecated since version 3.0.0 + */ + valueBeforeDecode: ArrayBuffer; + /** + * Binary data in ArrayBuffer representation + * + * @deprecated since version 3.0.0 + */ + valueHex: ArrayBuffer; +} + +interface OctetStringParams extends BaseBlockParams, LocalOctetStringValueBlockParams { +} +declare type OctetStringJson = BaseBlockJson; +declare class OctetString extends BaseBlock { + static NAME: string; + constructor({ idBlock, lenBlock, ...parameters }?: OctetStringParams); + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number): number; + protected onAsciiEncoding(): string; + /** + * Returns OctetString value. If OctetString is constructed, returns concatenated internal OctetString values + * @returns Array buffer + * @since 3.0.0 + */ + getValue(): ArrayBuffer; +} + +interface ILocalBitStringValueBlock { + unusedBits: number; + isConstructed: boolean; +} +interface LocalBitStringValueBlockParams extends HexBlockParams, LocalConstructedValueBlockParams, Partial { + value?: BitString[]; +} +interface LocalBitStringValueBlockJson extends HexBlockJson, LocalConstructedValueBlockJson, ILocalBitStringValueBlock { +} +declare const LocalBitStringValueBlock_base: { + new (...args: any[]): { + isHexOnly: boolean; + valueHex: ArrayBuffer; + valueHexView: Uint8Array; + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + toJSON(): { + isHexOnly: boolean; + valueHex: string; + blockName: string; + valueBeforeDecode: string; + blockLength: number; + error: string; + warnings: string[]; + }; + blockLength: number; + error: string; + warnings: string[]; + valueBeforeDecode: ArrayBuffer; + valueBeforeDecodeView: Uint8Array; + }; + NAME: string; + blockName(): string; +} & typeof LocalConstructedValueBlock; +declare class LocalBitStringValueBlock extends LocalBitStringValueBlock_base implements ILocalBitStringValueBlock { + static NAME: string; + unusedBits: number; + isConstructed: boolean; + constructor({ unusedBits, isConstructed, ...parameters }?: LocalBitStringValueBlockParams); + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean, writer?: ViewWriter): ArrayBuffer; + toJSON(): LocalBitStringValueBlockJson; +} +interface LocalBitStringValueBlock { + /** + * @deprecated since version 3.0.0 + */ + valueBeforeDecode: ArrayBuffer; + /** + * Binary data in ArrayBuffer representation + * + * @deprecated since version 3.0.0 + */ + valueHex: ArrayBuffer; +} + +interface BitStringParams extends BaseBlockParams, LocalBitStringValueBlockParams { +} +declare type BitStringJson = BaseBlockJson; +declare class BitString extends BaseBlock { + static NAME: string; + constructor({ idBlock, lenBlock, ...parameters }?: BitStringParams); + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number): number; + protected onAsciiEncoding(): string; +} + +interface ILocalIntegerValueBlock { + value: number; +} +interface LocalIntegerValueBlockParams extends HexBlockParams, ValueBlockParams, Partial { +} +interface LocalIntegerValueBlockJson extends HexBlockJson, ValueBlockJson { + valueDec: number; +} +declare const LocalIntegerValueBlock_base: { + new (...args: any[]): { + isHexOnly: boolean; + valueHex: ArrayBuffer; + valueHexView: Uint8Array; + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + toJSON(): { + isHexOnly: boolean; + valueHex: string; + blockName: string; + valueBeforeDecode: string; + blockLength: number; + error: string; + warnings: string[]; + }; + blockLength: number; + error: string; + warnings: string[]; + valueBeforeDecode: ArrayBuffer; + valueBeforeDecodeView: Uint8Array; + }; + NAME: string; + blockName(): string; +} & typeof ValueBlock; +declare class LocalIntegerValueBlock extends LocalIntegerValueBlock_base implements IDerConvertible { + protected setValueHex(): void; + static NAME: string; + private _valueDec; + constructor({ value, ...parameters }?: LocalIntegerValueBlockParams); + set valueDec(v: number); + get valueDec(): number; + fromDER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number, expectedLength?: number): number; + toDER(sizeOnly?: boolean): ArrayBuffer; + fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + toJSON(): LocalIntegerValueBlockJson; + toString(): string; +} +interface LocalIntegerValueBlock { + /** + * @deprecated since version 3.0.0 + */ + valueBeforeDecode: ArrayBuffer; + /** + * Binary data in ArrayBuffer representation + * + * @deprecated since version 3.0.0 + */ + valueHex: ArrayBuffer; +} + +interface IntegerParams extends BaseBlockParams, LocalIntegerValueBlockParams { +} +declare type IntegerJson = BaseBlockJson; +declare class Integer extends BaseBlock { + static NAME: string; + constructor(parameters?: IntegerParams); + /** + * Converts Integer into BigInt + * @throws Throws Error if BigInt is not supported + * @since 3.0.0 + */ + toBigInt(): bigint; + /** + * Creates Integer from BigInt value + * @param value BigInt value + * @returns ASN.1 Integer + * @throws Throws Error if BigInt is not supported + * @since 3.0.0 + */ + static fromBigInt(value: number | string | bigint | boolean): Integer; + convertToDER(): Integer; + /** + * Convert current Integer value from DER to BER format + * @returns + */ + convertFromDER(): Integer; + protected onAsciiEncoding(): string; +} + +declare type EnumeratedParams = IntegerParams; +declare type EnumeratedJson = IntegerJson; +declare class Enumerated extends Integer { + static NAME: string; + constructor(parameters?: EnumeratedParams); +} + +interface ILocalSidValueBlock { + valueDec: number; + isFirstSid: boolean; +} +interface LocalSidValueBlockParams extends HexBlockParams, ValueBlockParams, Partial { +} +interface LocalSidValueBlockJson extends HexBlockJson, ValueBlockJson, ILocalSidValueBlock { +} +declare const LocalSidValueBlock_base: { + new (...args: any[]): { + isHexOnly: boolean; + valueHex: ArrayBuffer; + valueHexView: Uint8Array; + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + toJSON(): { + isHexOnly: boolean; + valueHex: string; + blockName: string; + valueBeforeDecode: string; + blockLength: number; + error: string; + warnings: string[]; + }; + blockLength: number; + error: string; + warnings: string[]; + valueBeforeDecode: ArrayBuffer; + valueBeforeDecodeView: Uint8Array; + }; + NAME: string; + blockName(): string; +} & typeof ValueBlock; +declare class LocalSidValueBlock extends LocalSidValueBlock_base implements ILocalSidValueBlock { + static NAME: string; + valueDec: number; + isFirstSid: boolean; + constructor({ valueDec, isFirstSid, ...parameters }?: LocalSidValueBlockParams); + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number): number; + set valueBigInt(value: bigint); + toBER(sizeOnly?: boolean): ArrayBuffer; + toString(): string; + toJSON(): LocalSidValueBlockJson; +} +interface LocalSidValueBlock { + /** + * @deprecated since version 3.0.0 + */ + valueBeforeDecode: ArrayBuffer; + /** + * Binary data in ArrayBuffer representation + * + * @deprecated since version 3.0.0 + */ + valueHex: ArrayBuffer; +} + +interface ILocalObjectIdentifierValueBlock { + value: string; +} +interface LocalObjectIdentifierValueBlockParams extends ValueBlockParams, Partial { +} +interface LocalObjectIdentifierValueBlockJson extends ValueBlockJson, ILocalObjectIdentifierValueBlock { + sidArray: LocalSidValueBlockJson[]; +} +declare class LocalObjectIdentifierValueBlock extends ValueBlock implements IStringConvertible { + static NAME: string; + value: LocalSidValueBlock[]; + constructor({ value, ...parameters }?: LocalObjectIdentifierValueBlockParams); + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + fromString(string: string): void; + toString(): string; + toJSON(): LocalObjectIdentifierValueBlockJson; +} + +interface ObjectIdentifierParams extends BaseBlockParams, LocalObjectIdentifierValueBlockParams { +} +interface ObjectIdentifierJson extends BaseBlockJson { + value: string; +} +declare class ObjectIdentifier extends BaseBlock { + static NAME: string; + /** + * Gets string representation of Object Identifier + * @since 3.0.0 + */ + getValue(): string; + /** + * Sets Object Identifier value from string + * @param value String value + * @since 3.0.0 + */ + setValue(value: string): void; + constructor(parameters?: ObjectIdentifierParams); + protected onAsciiEncoding(): string; + toJSON(): ObjectIdentifierJson; +} + +interface ILocalRelativeSidValueBlock { + valueDec: number; +} +interface LocalRelativeSidValueBlockParams extends HexBlockParams, ValueBlockParams, Partial { +} +interface LocalRelativeSidValueBlockJson extends HexBlockJson, ValueBlockJson, ILocalRelativeSidValueBlock { +} +declare const LocalRelativeSidValueBlock_base: { + new (...args: any[]): { + isHexOnly: boolean; + valueHex: ArrayBuffer; + valueHexView: Uint8Array; + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + toJSON(): { + isHexOnly: boolean; + valueHex: string; + blockName: string; + valueBeforeDecode: string; + blockLength: number; + error: string; + warnings: string[]; + }; + blockLength: number; + error: string; + warnings: string[]; + valueBeforeDecode: ArrayBuffer; + valueBeforeDecodeView: Uint8Array; + }; + NAME: string; + blockName(): string; +} & typeof LocalBaseBlock; +declare class LocalRelativeSidValueBlock extends LocalRelativeSidValueBlock_base implements ILocalRelativeSidValueBlock { + static NAME: string; + valueDec: number; + constructor({ valueDec, ...parameters }?: LocalRelativeSidValueBlockParams); + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + toString(): string; + toJSON(): LocalRelativeSidValueBlockJson; +} + +interface ILocalRelativeObjectIdentifierValueBlock { + value: string; +} +interface LocalRelativeObjectIdentifierValueBlockParams extends ValueBlockParams, Partial { +} +interface LocalRelativeObjectIdentifierValueBlockJson extends ValueBlockJson, ILocalRelativeObjectIdentifierValueBlock { + sidArray: LocalRelativeSidValueBlockJson[]; +} +declare class LocalRelativeObjectIdentifierValueBlock extends ValueBlock implements IStringConvertible { + static NAME: string; + value: LocalRelativeSidValueBlock[]; + constructor({ value, ...parameters }?: LocalRelativeObjectIdentifierValueBlockParams); + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean, writer?: ViewWriter): ArrayBuffer; + fromString(string: string): boolean; + toString(): string; + toJSON(): LocalRelativeObjectIdentifierValueBlockJson; +} + +interface RelativeObjectIdentifierParams extends BaseBlockParams, LocalRelativeObjectIdentifierValueBlockParams { +} +interface RelativeObjectIdentifierJson extends BaseBlockJson { + value: string; +} +declare class RelativeObjectIdentifier extends BaseBlock { + /** + * Gets string representation of Relative Object Identifier + * @since 3.0.0 + */ + getValue(): string; + /** + * Sets Relative Object Identifier value from string + * @param value String value + * @since 3.0.0 + */ + setValue(value: string): void; + static NAME: string; + constructor(parameters?: RelativeObjectIdentifierParams); + protected onAsciiEncoding(): string; + toJSON(): RelativeObjectIdentifierJson; +} + +declare type SequenceParams = ConstructedParams; +declare type SequenceJson = ConstructedJson; +declare class Sequence extends Constructed { + static NAME: string; + constructor(parameters?: SequenceParams); +} + +declare type SetParams = ConstructedParams; +declare type SetJson = ConstructedJson; +declare class Set extends Constructed { + static NAME: string; + constructor(parameters?: SetParams); +} + +interface Utf8StringParams extends BaseStringBlockParams, LocalUtf8StringValueBlockParams { +} +declare type Utf8StringJson = BaseBlockJson; +declare class Utf8String extends LocalUtf8StringValueBlock { + static NAME: string; + constructor(parameters?: Utf8StringParams); +} + +declare type LocalBmpStringValueBlockParams = LocalSimpleStringBlockParams; +declare type LocalBmpStringValueBlockJson = LocalSimpleStringBlockJson; +declare class LocalBmpStringValueBlock extends LocalSimpleStringBlock { + static NAME: string; + fromBuffer(inputBuffer: ArrayBuffer | Uint8Array): void; + fromString(inputString: string): void; +} + +declare type BmpStringParams = LocalBmpStringValueBlockParams; +declare type BmpStringJson = LocalBmpStringValueBlockJson; +declare class BmpString extends LocalBmpStringValueBlock { + static NAME: string; + constructor({ ...parameters }?: BmpStringParams); +} + +declare type LocalUniversalStringValueBlockParams = LocalSimpleStringBlockParams; +declare type LocalUniversalStringValueBlockJson = LocalSimpleStringBlockJson; +declare class LocalUniversalStringValueBlock extends LocalSimpleStringBlock { + static NAME: string; + fromBuffer(inputBuffer: ArrayBuffer | Uint8Array): void; + fromString(inputString: string): void; +} + +declare type UniversalStringParams = LocalUniversalStringValueBlockParams; +declare type UniversalStringJson = LocalUniversalStringValueBlockJson; +declare class UniversalString extends LocalUniversalStringValueBlock { + static NAME: string; + constructor({ ...parameters }?: UniversalStringParams); +} + +declare type NumericStringParams = LocalSimpleStringBlockParams; +declare type NumericStringJson = LocalSimpleStringBlockJson; +declare class NumericString extends LocalSimpleStringBlock { + static NAME: string; + constructor(parameters?: NumericStringParams); +} + +declare type PrintableStringParams = LocalSimpleStringBlockParams; +declare type PrintableStringJson = LocalSimpleStringBlockJson; +declare class PrintableString extends LocalSimpleStringBlock { + static NAME: string; + constructor(parameters?: PrintableStringParams); +} + +declare type TeletexStringParams = LocalSimpleStringBlockParams; +declare type TeletexStringJson = LocalSimpleStringBlockJson; +declare class TeletexString extends LocalSimpleStringBlock { + static NAME: string; + constructor(parameters?: TeletexStringParams); +} + +declare type VideotexStringParams = LocalSimpleStringBlockParams; +declare type VideotexStringJson = LocalSimpleStringBlockJson; +declare class VideotexString extends LocalSimpleStringBlock { + static NAME: string; + constructor(parameters?: VideotexStringParams); +} + +declare type IA5StringParams = LocalSimpleStringBlockParams; +declare type IA5StringJson = LocalSimpleStringBlockJson; +declare class IA5String extends LocalSimpleStringBlock { + static NAME: string; + constructor(parameters?: IA5StringParams); +} + +declare type GraphicStringParams = LocalSimpleStringBlockParams; +declare type GraphicStringJson = LocalSimpleStringBlockJson; +declare class GraphicString extends LocalSimpleStringBlock { + static NAME: string; + constructor(parameters?: GraphicStringParams); +} + +declare type VisibleStringParams = LocalSimpleStringBlockParams; +declare type VisibleStringJson = LocalSimpleStringBlockJson; +declare class VisibleString extends LocalSimpleStringBlock { + static NAME: string; + constructor(parameters?: VisibleStringParams); +} + +declare type GeneralStringParams = LocalSimpleStringBlockParams; +declare type GeneralStringJson = LocalSimpleStringBlockJson; +declare class GeneralString extends LocalSimpleStringBlock { + static NAME: string; + constructor(parameters?: GeneralStringParams); +} + +declare type CharacterStringParams = LocalSimpleStringBlockParams; +declare type CharacterStringJson = LocalSimpleStringBlockJson; +declare class CharacterString extends LocalSimpleStringBlock { + static NAME: string; + constructor(parameters?: CharacterStringParams); +} + +interface IUTCTime { + year: number; + month: number; + day: number; + hour: number; + minute: number; + second: number; +} +interface UTCTimeParams extends VisibleStringParams { + value?: string; + valueDate?: Date; +} +interface UTCTimeJson extends BaseBlockJson, IUTCTime { +} +declare type DateStringEncoding = StringEncoding | "iso"; +declare class UTCTime extends VisibleString implements IUTCTime, IDateConvertible { + static NAME: string; + year: number; + month: number; + day: number; + hour: number; + minute: number; + second: number; + constructor({ value, valueDate, ...parameters }?: UTCTimeParams); + fromBuffer(inputBuffer: ArrayBuffer | Uint8Array): void; + /** + * Function converting ASN.1 internal string into ArrayBuffer + * @returns + */ + toBuffer(): ArrayBuffer; + /** + * Function converting "Date" object into ASN.1 internal string + * @param {!Date} inputDate JavaScript "Date" object + */ + fromDate(inputDate: Date): void; + toDate(): Date; + fromString(inputString: string): void; + toString(encoding?: DateStringEncoding): string; + protected onAsciiEncoding(): string; + toJSON(): UTCTimeJson; +} + +interface IGeneralizedTime extends IUTCTime { + millisecond: number; +} +declare type GeneralizedTimeParams = UTCTimeParams; +interface GeneralizedTimeJson extends UTCTimeJson { + millisecond: number; +} +declare class GeneralizedTime extends UTCTime { + static NAME: string; + millisecond: number; + constructor(parameters?: GeneralizedTimeParams); + fromDate(inputDate: Date): void; + toDate(): Date; + fromString(inputString: string): void; + toString(encoding?: DateStringEncoding): string; + toJSON(): GeneralizedTimeJson; +} + +declare type DATEParams = Utf8StringParams; +declare type DATEJson = Utf8StringJson; +declare class DATE extends Utf8String { + static NAME: string; + constructor(parameters?: DATEParams); +} + +declare type TimeOfDayParams = Utf8StringParams; +declare type TimeOfDayJson = Utf8StringJson; +declare class TimeOfDay extends Utf8String { + static NAME: string; + constructor(parameters?: TimeOfDayParams); +} + +declare type DateTimeParams = Utf8StringParams; +declare type DateTimeJson = Utf8StringJson; +declare class DateTime extends Utf8String { + static NAME: string; + constructor(parameters?: DateTimeParams); +} + +declare type DurationParams = Utf8StringParams; +declare type DurationJson = Utf8StringJson; +declare class Duration extends Utf8String { + static NAME: string; + constructor(parameters?: DurationParams); +} + +declare type TIMEParams = Utf8StringParams; +declare type TIMEJson = Utf8StringJson; +declare class TIME extends Utf8String { + static NAME: string; + constructor(parameters?: TIMEParams); +} + +interface IChoice extends IAny { + value: BaseBlock[]; +} +declare type ChoiceParams = Partial; +declare class Choice extends Any implements IChoice { + value: BaseBlock[]; + constructor({ value, ...parameters }?: ChoiceParams); +} + +interface IRepeated extends IAny { + value: Any; + local: boolean; +} +declare type RepeatedParams = Partial; +declare class Repeated extends Any { + value: Any; + local: boolean; + constructor({ value, local, ...parameters }?: RepeatedParams); +} + +interface IRawData { + data: ArrayBuffer; +} +declare type RawDataParams = Partial; +/** + * Special class providing ability to have "toBER/fromBER" for raw ArrayBuffer + */ +declare class RawData implements IBerConvertible { + /** + * @deprecated Since v3.0.0 + */ + get data(): ArrayBuffer; + /** + * @deprecated Since v3.0.0 + */ + set data(value: ArrayBuffer); + /** + * @since 3.0.0 + */ + dataView: Uint8Array; + constructor({ data }?: RawDataParams); + fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean): ArrayBuffer; +} + +declare type AsnType = BaseBlock | EndOfContent | Boolean | Integer | BitString | OctetString | Null | ObjectIdentifier | Enumerated | Utf8String | RelativeObjectIdentifier | TIME | Sequence | Set | NumericString | PrintableString | TeletexString | VideotexString | IA5String | UTCTime | GeneralizedTime | GraphicString | VisibleString | GeneralString | UniversalString | CharacterString | BmpString | DATE | TimeOfDay | DateTime | Duration | Constructed | Primitive; + +interface FromBerResult { + offset: number; + result: AsnType; +} +/** + * Major function for decoding ASN.1 BER array into internal library structures + * @param inputBuffer ASN.1 BER encoded array of bytes + */ +declare function fromBER(inputBuffer: pvtsutils.BufferSource): FromBerResult; + +declare type AsnSchemaType = AsnType | Any | Choice | Repeated; +interface CompareSchemaSuccess { + verified: true; + result: AsnType & { + [key: string]: any; + }; +} +interface CompareSchemaFail { + verified: false; + name?: string; + result: AsnType | { + error: string; + }; +} +declare type CompareSchemaResult = CompareSchemaSuccess | CompareSchemaFail; +/** + * Compare of two ASN.1 object trees + * @param root Root of input ASN.1 object tree + * @param inputData Input ASN.1 object tree + * @param inputSchema Input ASN.1 schema to compare with + * @return Returns result of comparison + */ +declare function compareSchema(root: AsnType, inputData: AsnType, inputSchema: AsnSchemaType): CompareSchemaResult; +/** + * ASN.1 schema verification for ArrayBuffer data + * @param inputBuffer Input BER-encoded ASN.1 data + * @param inputSchema Input ASN.1 schema to verify against to + * @return + */ +declare function verifySchema(inputBuffer: pvtsutils.BufferSource, inputSchema: AsnSchemaType): CompareSchemaResult; + +export { Any, AnyParams, AsnSchemaType, AsnType, BaseBlock, BaseBlockJson, BaseBlockParams, BaseStringBlock, BaseStringBlockJson, BaseStringBlockParams, BitString, BitStringJson, BitStringParams, BmpString, BmpStringJson, BmpStringParams, Boolean, BooleanJson, BooleanParams, CharacterString, CharacterStringJson, CharacterStringParams, Choice, ChoiceParams, CompareSchemaFail, CompareSchemaResult, CompareSchemaSuccess, Constructed, ConstructedJson, ConstructedParams, DATE, DATEJson, DATEParams, DateStringEncoding, DateTime, DateTimeJson, DateTimeParams, Duration, DurationJson, DurationParams, EndOfContent, EndOfContentJson, EndOfContentParams, Enumerated, EnumeratedJson, EnumeratedParams, FromBerResult, GeneralString, GeneralStringJson, GeneralStringParams, GeneralizedTime, GeneralizedTimeJson, GeneralizedTimeParams, GraphicString, GraphicStringJson, GraphicStringParams, HexBlock, HexBlockJson, HexBlockParams, IA5String, IA5StringJson, IA5StringParams, IAny, IBaseBlock, IBerConvertible, IChoice, IDateConvertible, IDerConvertible, IGeneralizedTime, IHexBlock, IRawData, IRepeated, IStringConvertible, IUTCTime, IValueBlock, Integer, IntegerJson, IntegerParams, Null, NullJson, NullParams, NumericString, NumericStringJson, NumericStringParams, ObjectIdentifier, ObjectIdentifierJson, ObjectIdentifierParams, OctetString, OctetStringJson, OctetStringParams, Primitive, PrimitiveJson, PrimitiveParams, PrintableString, PrintableStringJson, PrintableStringParams, RawData, RawDataParams, RelativeObjectIdentifier, RelativeObjectIdentifierJson, RelativeObjectIdentifierParams, Repeated, RepeatedParams, Sequence, SequenceJson, SequenceParams, Set, SetJson, SetParams, StringEncoding, TIME, TIMEJson, TIMEParams, TeletexString, TeletexStringJson, TeletexStringParams, TimeOfDay, TimeOfDayJson, TimeOfDayParams, UTCTime, UTCTimeJson, UTCTimeParams, UniversalString, UniversalStringJson, UniversalStringParams, Utf8String, Utf8StringJson, Utf8StringParams, ValueBlock, ValueBlockConstructor, ValueBlockJson, ValueBlockParams, VideotexString, VideotexStringJson, VideotexStringParams, ViewWriter, VisibleString, VisibleStringJson, VisibleStringParams, compareSchema, fromBER, verifySchema }; diff --git a/gun-server/node_modules/asn1js/build/index.es.js b/gun-server/node_modules/asn1js/build/index.es.js new file mode 100644 index 0000000..0196a95 --- /dev/null +++ b/gun-server/node_modules/asn1js/build/index.es.js @@ -0,0 +1,3128 @@ +/*! + * Copyright (c) 2014, GMO GlobalSign + * Copyright (c) 2015-2022, Peculiar Ventures + * All rights reserved. + * + * Author 2014-2019, Yury Strozhevsky + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * * Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +import * as pvtsutils from 'pvtsutils'; +import * as pvutils from 'pvutils'; + +function assertBigInt() { + if (typeof BigInt === "undefined") { + throw new Error("BigInt is not defined. Your environment doesn't implement BigInt."); + } +} +function concat(buffers) { + let outputLength = 0; + let prevLength = 0; + for (let i = 0; i < buffers.length; i++) { + const buffer = buffers[i]; + outputLength += buffer.byteLength; + } + const retView = new Uint8Array(outputLength); + for (let i = 0; i < buffers.length; i++) { + const buffer = buffers[i]; + retView.set(new Uint8Array(buffer), prevLength); + prevLength += buffer.byteLength; + } + return retView.buffer; +} +function checkBufferParams(baseBlock, inputBuffer, inputOffset, inputLength) { + if (!(inputBuffer instanceof Uint8Array)) { + baseBlock.error = "Wrong parameter: inputBuffer must be 'Uint8Array'"; + return false; + } + if (!inputBuffer.byteLength) { + baseBlock.error = "Wrong parameter: inputBuffer has zero length"; + return false; + } + if (inputOffset < 0) { + baseBlock.error = "Wrong parameter: inputOffset less than zero"; + return false; + } + if (inputLength < 0) { + baseBlock.error = "Wrong parameter: inputLength less than zero"; + return false; + } + if ((inputBuffer.byteLength - inputOffset - inputLength) < 0) { + baseBlock.error = "End of input reached before message was fully decoded (inconsistent offset and length values)"; + return false; + } + return true; +} + +class ViewWriter { + constructor() { + this.items = []; + } + write(buf) { + this.items.push(buf); + } + final() { + return concat(this.items); + } +} + +const powers2 = [new Uint8Array([1])]; +const digitsString = "0123456789"; +const NAME = "name"; +const VALUE_HEX_VIEW = "valueHexView"; +const IS_HEX_ONLY = "isHexOnly"; +const ID_BLOCK = "idBlock"; +const TAG_CLASS = "tagClass"; +const TAG_NUMBER = "tagNumber"; +const IS_CONSTRUCTED = "isConstructed"; +const FROM_BER = "fromBER"; +const TO_BER = "toBER"; +const LOCAL = "local"; +const EMPTY_STRING = ""; +const EMPTY_BUFFER = new ArrayBuffer(0); +const EMPTY_VIEW = new Uint8Array(0); +const END_OF_CONTENT_NAME = "EndOfContent"; +const OCTET_STRING_NAME = "OCTET STRING"; +const BIT_STRING_NAME = "BIT STRING"; + +function HexBlock(BaseClass) { + var _a; + return _a = class Some extends BaseClass { + constructor(...args) { + var _a; + super(...args); + const params = args[0] || {}; + this.isHexOnly = (_a = params.isHexOnly) !== null && _a !== void 0 ? _a : false; + this.valueHexView = params.valueHex ? pvtsutils.BufferSourceConverter.toUint8Array(params.valueHex) : EMPTY_VIEW; + } + get valueHex() { + return this.valueHexView.slice().buffer; + } + set valueHex(value) { + this.valueHexView = new Uint8Array(value); + } + fromBER(inputBuffer, inputOffset, inputLength) { + const view = inputBuffer instanceof ArrayBuffer ? new Uint8Array(inputBuffer) : inputBuffer; + if (!checkBufferParams(this, view, inputOffset, inputLength)) { + return -1; + } + const endLength = inputOffset + inputLength; + this.valueHexView = view.subarray(inputOffset, endLength); + if (!this.valueHexView.length) { + this.warnings.push("Zero buffer length"); + return inputOffset; + } + this.blockLength = inputLength; + return endLength; + } + toBER(sizeOnly = false) { + if (!this.isHexOnly) { + this.error = "Flag 'isHexOnly' is not set, abort"; + return EMPTY_BUFFER; + } + if (sizeOnly) { + return new ArrayBuffer(this.valueHexView.byteLength); + } + return (this.valueHexView.byteLength === this.valueHexView.buffer.byteLength) + ? this.valueHexView.buffer + : this.valueHexView.slice().buffer; + } + toJSON() { + return { + ...super.toJSON(), + isHexOnly: this.isHexOnly, + valueHex: pvtsutils.Convert.ToHex(this.valueHexView), + }; + } + }, + _a.NAME = "hexBlock", + _a; +} + +class LocalBaseBlock { + constructor({ blockLength = 0, error = EMPTY_STRING, warnings = [], valueBeforeDecode = EMPTY_VIEW, } = {}) { + this.blockLength = blockLength; + this.error = error; + this.warnings = warnings; + this.valueBeforeDecodeView = pvtsutils.BufferSourceConverter.toUint8Array(valueBeforeDecode); + } + static blockName() { + return this.NAME; + } + get valueBeforeDecode() { + return this.valueBeforeDecodeView.slice().buffer; + } + set valueBeforeDecode(value) { + this.valueBeforeDecodeView = new Uint8Array(value); + } + toJSON() { + return { + blockName: this.constructor.NAME, + blockLength: this.blockLength, + error: this.error, + warnings: this.warnings, + valueBeforeDecode: pvtsutils.Convert.ToHex(this.valueBeforeDecodeView), + }; + } +} +LocalBaseBlock.NAME = "baseBlock"; + +class ValueBlock extends LocalBaseBlock { + fromBER(inputBuffer, inputOffset, inputLength) { + throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'"); + } + toBER(sizeOnly, writer) { + throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'"); + } +} +ValueBlock.NAME = "valueBlock"; + +class LocalIdentificationBlock extends HexBlock(LocalBaseBlock) { + constructor({ idBlock = {}, } = {}) { + var _a, _b, _c, _d; + super(); + if (idBlock) { + this.isHexOnly = (_a = idBlock.isHexOnly) !== null && _a !== void 0 ? _a : false; + this.valueHexView = idBlock.valueHex ? pvtsutils.BufferSourceConverter.toUint8Array(idBlock.valueHex) : EMPTY_VIEW; + this.tagClass = (_b = idBlock.tagClass) !== null && _b !== void 0 ? _b : -1; + this.tagNumber = (_c = idBlock.tagNumber) !== null && _c !== void 0 ? _c : -1; + this.isConstructed = (_d = idBlock.isConstructed) !== null && _d !== void 0 ? _d : false; + } + else { + this.tagClass = -1; + this.tagNumber = -1; + this.isConstructed = false; + } + } + toBER(sizeOnly = false) { + let firstOctet = 0; + switch (this.tagClass) { + case 1: + firstOctet |= 0x00; + break; + case 2: + firstOctet |= 0x40; + break; + case 3: + firstOctet |= 0x80; + break; + case 4: + firstOctet |= 0xC0; + break; + default: + this.error = "Unknown tag class"; + return EMPTY_BUFFER; + } + if (this.isConstructed) + firstOctet |= 0x20; + if (this.tagNumber < 31 && !this.isHexOnly) { + const retView = new Uint8Array(1); + if (!sizeOnly) { + let number = this.tagNumber; + number &= 0x1F; + firstOctet |= number; + retView[0] = firstOctet; + } + return retView.buffer; + } + if (!this.isHexOnly) { + const encodedBuf = pvutils.utilToBase(this.tagNumber, 7); + const encodedView = new Uint8Array(encodedBuf); + const size = encodedBuf.byteLength; + const retView = new Uint8Array(size + 1); + retView[0] = (firstOctet | 0x1F); + if (!sizeOnly) { + for (let i = 0; i < (size - 1); i++) + retView[i + 1] = encodedView[i] | 0x80; + retView[size] = encodedView[size - 1]; + } + return retView.buffer; + } + const retView = new Uint8Array(this.valueHexView.byteLength + 1); + retView[0] = (firstOctet | 0x1F); + if (!sizeOnly) { + const curView = this.valueHexView; + for (let i = 0; i < (curView.length - 1); i++) + retView[i + 1] = curView[i] | 0x80; + retView[this.valueHexView.byteLength] = curView[curView.length - 1]; + } + return retView.buffer; + } + fromBER(inputBuffer, inputOffset, inputLength) { + const inputView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer); + if (!checkBufferParams(this, inputView, inputOffset, inputLength)) { + return -1; + } + const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength); + if (intBuffer.length === 0) { + this.error = "Zero buffer length"; + return -1; + } + const tagClassMask = intBuffer[0] & 0xC0; + switch (tagClassMask) { + case 0x00: + this.tagClass = (1); + break; + case 0x40: + this.tagClass = (2); + break; + case 0x80: + this.tagClass = (3); + break; + case 0xC0: + this.tagClass = (4); + break; + default: + this.error = "Unknown tag class"; + return -1; + } + this.isConstructed = (intBuffer[0] & 0x20) === 0x20; + this.isHexOnly = false; + const tagNumberMask = intBuffer[0] & 0x1F; + if (tagNumberMask !== 0x1F) { + this.tagNumber = (tagNumberMask); + this.blockLength = 1; + } + else { + let count = 1; + let intTagNumberBuffer = this.valueHexView = new Uint8Array(255); + let tagNumberBufferMaxLength = 255; + while (intBuffer[count] & 0x80) { + intTagNumberBuffer[count - 1] = intBuffer[count] & 0x7F; + count++; + if (count >= intBuffer.length) { + this.error = "End of input reached before message was fully decoded"; + return -1; + } + if (count === tagNumberBufferMaxLength) { + tagNumberBufferMaxLength += 255; + const tempBufferView = new Uint8Array(tagNumberBufferMaxLength); + for (let i = 0; i < intTagNumberBuffer.length; i++) + tempBufferView[i] = intTagNumberBuffer[i]; + intTagNumberBuffer = this.valueHexView = new Uint8Array(tagNumberBufferMaxLength); + } + } + this.blockLength = (count + 1); + intTagNumberBuffer[count - 1] = intBuffer[count] & 0x7F; + const tempBufferView = new Uint8Array(count); + for (let i = 0; i < count; i++) + tempBufferView[i] = intTagNumberBuffer[i]; + intTagNumberBuffer = this.valueHexView = new Uint8Array(count); + intTagNumberBuffer.set(tempBufferView); + if (this.blockLength <= 9) + this.tagNumber = pvutils.utilFromBase(intTagNumberBuffer, 7); + else { + this.isHexOnly = true; + this.warnings.push("Tag too long, represented as hex-coded"); + } + } + if (((this.tagClass === 1)) && + (this.isConstructed)) { + switch (this.tagNumber) { + case 1: + case 2: + case 5: + case 6: + case 9: + case 13: + case 14: + case 23: + case 24: + case 31: + case 32: + case 33: + case 34: + this.error = "Constructed encoding used for primitive type"; + return -1; + } + } + return (inputOffset + this.blockLength); + } + toJSON() { + return { + ...super.toJSON(), + tagClass: this.tagClass, + tagNumber: this.tagNumber, + isConstructed: this.isConstructed, + }; + } +} +LocalIdentificationBlock.NAME = "identificationBlock"; + +class LocalLengthBlock extends LocalBaseBlock { + constructor({ lenBlock = {}, } = {}) { + var _a, _b, _c; + super(); + this.isIndefiniteForm = (_a = lenBlock.isIndefiniteForm) !== null && _a !== void 0 ? _a : false; + this.longFormUsed = (_b = lenBlock.longFormUsed) !== null && _b !== void 0 ? _b : false; + this.length = (_c = lenBlock.length) !== null && _c !== void 0 ? _c : 0; + } + fromBER(inputBuffer, inputOffset, inputLength) { + const view = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer); + if (!checkBufferParams(this, view, inputOffset, inputLength)) { + return -1; + } + const intBuffer = view.subarray(inputOffset, inputOffset + inputLength); + if (intBuffer.length === 0) { + this.error = "Zero buffer length"; + return -1; + } + if (intBuffer[0] === 0xFF) { + this.error = "Length block 0xFF is reserved by standard"; + return -1; + } + this.isIndefiniteForm = intBuffer[0] === 0x80; + if (this.isIndefiniteForm) { + this.blockLength = 1; + return (inputOffset + this.blockLength); + } + this.longFormUsed = !!(intBuffer[0] & 0x80); + if (this.longFormUsed === false) { + this.length = (intBuffer[0]); + this.blockLength = 1; + return (inputOffset + this.blockLength); + } + const count = intBuffer[0] & 0x7F; + if (count > 8) { + this.error = "Too big integer"; + return -1; + } + if ((count + 1) > intBuffer.length) { + this.error = "End of input reached before message was fully decoded"; + return -1; + } + const lenOffset = inputOffset + 1; + const lengthBufferView = view.subarray(lenOffset, lenOffset + count); + if (lengthBufferView[count - 1] === 0x00) + this.warnings.push("Needlessly long encoded length"); + this.length = pvutils.utilFromBase(lengthBufferView, 8); + if (this.longFormUsed && (this.length <= 127)) + this.warnings.push("Unnecessary usage of long length form"); + this.blockLength = count + 1; + return (inputOffset + this.blockLength); + } + toBER(sizeOnly = false) { + let retBuf; + let retView; + if (this.length > 127) + this.longFormUsed = true; + if (this.isIndefiniteForm) { + retBuf = new ArrayBuffer(1); + if (sizeOnly === false) { + retView = new Uint8Array(retBuf); + retView[0] = 0x80; + } + return retBuf; + } + if (this.longFormUsed) { + const encodedBuf = pvutils.utilToBase(this.length, 8); + if (encodedBuf.byteLength > 127) { + this.error = "Too big length"; + return (EMPTY_BUFFER); + } + retBuf = new ArrayBuffer(encodedBuf.byteLength + 1); + if (sizeOnly) + return retBuf; + const encodedView = new Uint8Array(encodedBuf); + retView = new Uint8Array(retBuf); + retView[0] = encodedBuf.byteLength | 0x80; + for (let i = 0; i < encodedBuf.byteLength; i++) + retView[i + 1] = encodedView[i]; + return retBuf; + } + retBuf = new ArrayBuffer(1); + if (sizeOnly === false) { + retView = new Uint8Array(retBuf); + retView[0] = this.length; + } + return retBuf; + } + toJSON() { + return { + ...super.toJSON(), + isIndefiniteForm: this.isIndefiniteForm, + longFormUsed: this.longFormUsed, + length: this.length, + }; + } +} +LocalLengthBlock.NAME = "lengthBlock"; + +const typeStore = {}; + +class BaseBlock extends LocalBaseBlock { + constructor({ name = EMPTY_STRING, optional = false, primitiveSchema, ...parameters } = {}, valueBlockType) { + super(parameters); + this.name = name; + this.optional = optional; + if (primitiveSchema) { + this.primitiveSchema = primitiveSchema; + } + this.idBlock = new LocalIdentificationBlock(parameters); + this.lenBlock = new LocalLengthBlock(parameters); + this.valueBlock = valueBlockType ? new valueBlockType(parameters) : new ValueBlock(parameters); + } + fromBER(inputBuffer, inputOffset, inputLength) { + const resultOffset = this.valueBlock.fromBER(inputBuffer, inputOffset, (this.lenBlock.isIndefiniteForm) ? inputLength : this.lenBlock.length); + if (resultOffset === -1) { + this.error = this.valueBlock.error; + return resultOffset; + } + if (!this.idBlock.error.length) + this.blockLength += this.idBlock.blockLength; + if (!this.lenBlock.error.length) + this.blockLength += this.lenBlock.blockLength; + if (!this.valueBlock.error.length) + this.blockLength += this.valueBlock.blockLength; + return resultOffset; + } + toBER(sizeOnly, writer) { + const _writer = writer || new ViewWriter(); + if (!writer) { + prepareIndefiniteForm(this); + } + const idBlockBuf = this.idBlock.toBER(sizeOnly); + _writer.write(idBlockBuf); + if (this.lenBlock.isIndefiniteForm) { + _writer.write(new Uint8Array([0x80]).buffer); + this.valueBlock.toBER(sizeOnly, _writer); + _writer.write(new ArrayBuffer(2)); + } + else { + const valueBlockBuf = this.valueBlock.toBER(sizeOnly); + this.lenBlock.length = valueBlockBuf.byteLength; + const lenBlockBuf = this.lenBlock.toBER(sizeOnly); + _writer.write(lenBlockBuf); + _writer.write(valueBlockBuf); + } + if (!writer) { + return _writer.final(); + } + return EMPTY_BUFFER; + } + toJSON() { + const object = { + ...super.toJSON(), + idBlock: this.idBlock.toJSON(), + lenBlock: this.lenBlock.toJSON(), + valueBlock: this.valueBlock.toJSON(), + name: this.name, + optional: this.optional, + }; + if (this.primitiveSchema) + object.primitiveSchema = this.primitiveSchema.toJSON(); + return object; + } + toString(encoding = "ascii") { + if (encoding === "ascii") { + return this.onAsciiEncoding(); + } + return pvtsutils.Convert.ToHex(this.toBER()); + } + onAsciiEncoding() { + return `${this.constructor.NAME} : ${pvtsutils.Convert.ToHex(this.valueBlock.valueBeforeDecodeView)}`; + } + isEqual(other) { + if (this === other) { + return true; + } + if (!(other instanceof this.constructor)) { + return false; + } + const thisRaw = this.toBER(); + const otherRaw = other.toBER(); + return pvutils.isEqualBuffer(thisRaw, otherRaw); + } +} +BaseBlock.NAME = "BaseBlock"; +function prepareIndefiniteForm(baseBlock) { + if (baseBlock instanceof typeStore.Constructed) { + for (const value of baseBlock.valueBlock.value) { + if (prepareIndefiniteForm(value)) { + baseBlock.lenBlock.isIndefiniteForm = true; + } + } + } + return !!baseBlock.lenBlock.isIndefiniteForm; +} + +class BaseStringBlock extends BaseBlock { + constructor({ value = EMPTY_STRING, ...parameters } = {}, stringValueBlockType) { + super(parameters, stringValueBlockType); + if (value) { + this.fromString(value); + } + } + getValue() { + return this.valueBlock.value; + } + setValue(value) { + this.valueBlock.value = value; + } + fromBER(inputBuffer, inputOffset, inputLength) { + const resultOffset = this.valueBlock.fromBER(inputBuffer, inputOffset, (this.lenBlock.isIndefiniteForm) ? inputLength : this.lenBlock.length); + if (resultOffset === -1) { + this.error = this.valueBlock.error; + return resultOffset; + } + this.fromBuffer(this.valueBlock.valueHexView); + if (!this.idBlock.error.length) + this.blockLength += this.idBlock.blockLength; + if (!this.lenBlock.error.length) + this.blockLength += this.lenBlock.blockLength; + if (!this.valueBlock.error.length) + this.blockLength += this.valueBlock.blockLength; + return resultOffset; + } + onAsciiEncoding() { + return `${this.constructor.NAME} : '${this.valueBlock.value}'`; + } +} +BaseStringBlock.NAME = "BaseStringBlock"; + +class LocalPrimitiveValueBlock extends HexBlock(ValueBlock) { + constructor({ isHexOnly = true, ...parameters } = {}) { + super(parameters); + this.isHexOnly = isHexOnly; + } +} +LocalPrimitiveValueBlock.NAME = "PrimitiveValueBlock"; + +var _a$w; +class Primitive extends BaseBlock { + constructor(parameters = {}) { + super(parameters, LocalPrimitiveValueBlock); + this.idBlock.isConstructed = false; + } +} +_a$w = Primitive; +(() => { + typeStore.Primitive = _a$w; +})(); +Primitive.NAME = "PRIMITIVE"; + +function localChangeType(inputObject, newType) { + if (inputObject instanceof newType) { + return inputObject; + } + const newObject = new newType(); + newObject.idBlock = inputObject.idBlock; + newObject.lenBlock = inputObject.lenBlock; + newObject.warnings = inputObject.warnings; + newObject.valueBeforeDecodeView = inputObject.valueBeforeDecodeView; + return newObject; +} +function localFromBER(inputBuffer, inputOffset = 0, inputLength = inputBuffer.length) { + const incomingOffset = inputOffset; + let returnObject = new BaseBlock({}, ValueBlock); + const baseBlock = new LocalBaseBlock(); + if (!checkBufferParams(baseBlock, inputBuffer, inputOffset, inputLength)) { + returnObject.error = baseBlock.error; + return { + offset: -1, + result: returnObject + }; + } + const intBuffer = inputBuffer.subarray(inputOffset, inputOffset + inputLength); + if (!intBuffer.length) { + returnObject.error = "Zero buffer length"; + return { + offset: -1, + result: returnObject + }; + } + let resultOffset = returnObject.idBlock.fromBER(inputBuffer, inputOffset, inputLength); + if (returnObject.idBlock.warnings.length) { + returnObject.warnings.concat(returnObject.idBlock.warnings); + } + if (resultOffset === -1) { + returnObject.error = returnObject.idBlock.error; + return { + offset: -1, + result: returnObject + }; + } + inputOffset = resultOffset; + inputLength -= returnObject.idBlock.blockLength; + resultOffset = returnObject.lenBlock.fromBER(inputBuffer, inputOffset, inputLength); + if (returnObject.lenBlock.warnings.length) { + returnObject.warnings.concat(returnObject.lenBlock.warnings); + } + if (resultOffset === -1) { + returnObject.error = returnObject.lenBlock.error; + return { + offset: -1, + result: returnObject + }; + } + inputOffset = resultOffset; + inputLength -= returnObject.lenBlock.blockLength; + if (!returnObject.idBlock.isConstructed && + returnObject.lenBlock.isIndefiniteForm) { + returnObject.error = "Indefinite length form used for primitive encoding form"; + return { + offset: -1, + result: returnObject + }; + } + let newASN1Type = BaseBlock; + switch (returnObject.idBlock.tagClass) { + case 1: + if ((returnObject.idBlock.tagNumber >= 37) && + (returnObject.idBlock.isHexOnly === false)) { + returnObject.error = "UNIVERSAL 37 and upper tags are reserved by ASN.1 standard"; + return { + offset: -1, + result: returnObject + }; + } + switch (returnObject.idBlock.tagNumber) { + case 0: + if ((returnObject.idBlock.isConstructed) && + (returnObject.lenBlock.length > 0)) { + returnObject.error = "Type [UNIVERSAL 0] is reserved"; + return { + offset: -1, + result: returnObject + }; + } + newASN1Type = typeStore.EndOfContent; + break; + case 1: + newASN1Type = typeStore.Boolean; + break; + case 2: + newASN1Type = typeStore.Integer; + break; + case 3: + newASN1Type = typeStore.BitString; + break; + case 4: + newASN1Type = typeStore.OctetString; + break; + case 5: + newASN1Type = typeStore.Null; + break; + case 6: + newASN1Type = typeStore.ObjectIdentifier; + break; + case 10: + newASN1Type = typeStore.Enumerated; + break; + case 12: + newASN1Type = typeStore.Utf8String; + break; + case 13: + newASN1Type = typeStore.RelativeObjectIdentifier; + break; + case 14: + newASN1Type = typeStore.TIME; + break; + case 15: + returnObject.error = "[UNIVERSAL 15] is reserved by ASN.1 standard"; + return { + offset: -1, + result: returnObject + }; + case 16: + newASN1Type = typeStore.Sequence; + break; + case 17: + newASN1Type = typeStore.Set; + break; + case 18: + newASN1Type = typeStore.NumericString; + break; + case 19: + newASN1Type = typeStore.PrintableString; + break; + case 20: + newASN1Type = typeStore.TeletexString; + break; + case 21: + newASN1Type = typeStore.VideotexString; + break; + case 22: + newASN1Type = typeStore.IA5String; + break; + case 23: + newASN1Type = typeStore.UTCTime; + break; + case 24: + newASN1Type = typeStore.GeneralizedTime; + break; + case 25: + newASN1Type = typeStore.GraphicString; + break; + case 26: + newASN1Type = typeStore.VisibleString; + break; + case 27: + newASN1Type = typeStore.GeneralString; + break; + case 28: + newASN1Type = typeStore.UniversalString; + break; + case 29: + newASN1Type = typeStore.CharacterString; + break; + case 30: + newASN1Type = typeStore.BmpString; + break; + case 31: + newASN1Type = typeStore.DATE; + break; + case 32: + newASN1Type = typeStore.TimeOfDay; + break; + case 33: + newASN1Type = typeStore.DateTime; + break; + case 34: + newASN1Type = typeStore.Duration; + break; + default: { + const newObject = returnObject.idBlock.isConstructed + ? new typeStore.Constructed() + : new typeStore.Primitive(); + newObject.idBlock = returnObject.idBlock; + newObject.lenBlock = returnObject.lenBlock; + newObject.warnings = returnObject.warnings; + returnObject = newObject; + } + } + break; + case 2: + case 3: + case 4: + default: { + newASN1Type = returnObject.idBlock.isConstructed + ? typeStore.Constructed + : typeStore.Primitive; + } + } + returnObject = localChangeType(returnObject, newASN1Type); + resultOffset = returnObject.fromBER(inputBuffer, inputOffset, returnObject.lenBlock.isIndefiniteForm ? inputLength : returnObject.lenBlock.length); + returnObject.valueBeforeDecodeView = inputBuffer.subarray(incomingOffset, incomingOffset + returnObject.blockLength); + return { + offset: resultOffset, + result: returnObject + }; +} +function fromBER(inputBuffer) { + if (!inputBuffer.byteLength) { + const result = new BaseBlock({}, ValueBlock); + result.error = "Input buffer has zero length"; + return { + offset: -1, + result + }; + } + return localFromBER(pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer).slice(), 0, inputBuffer.byteLength); +} + +function checkLen(indefiniteLength, length) { + if (indefiniteLength) { + return 1; + } + return length; +} +class LocalConstructedValueBlock extends ValueBlock { + constructor({ value = [], isIndefiniteForm = false, ...parameters } = {}) { + super(parameters); + this.value = value; + this.isIndefiniteForm = isIndefiniteForm; + } + fromBER(inputBuffer, inputOffset, inputLength) { + const view = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer); + if (!checkBufferParams(this, view, inputOffset, inputLength)) { + return -1; + } + this.valueBeforeDecodeView = view.subarray(inputOffset, inputOffset + inputLength); + if (this.valueBeforeDecodeView.length === 0) { + this.warnings.push("Zero buffer length"); + return inputOffset; + } + let currentOffset = inputOffset; + while (checkLen(this.isIndefiniteForm, inputLength) > 0) { + const returnObject = localFromBER(view, currentOffset, inputLength); + if (returnObject.offset === -1) { + this.error = returnObject.result.error; + this.warnings.concat(returnObject.result.warnings); + return -1; + } + currentOffset = returnObject.offset; + this.blockLength += returnObject.result.blockLength; + inputLength -= returnObject.result.blockLength; + this.value.push(returnObject.result); + if (this.isIndefiniteForm && returnObject.result.constructor.NAME === END_OF_CONTENT_NAME) { + break; + } + } + if (this.isIndefiniteForm) { + if (this.value[this.value.length - 1].constructor.NAME === END_OF_CONTENT_NAME) { + this.value.pop(); + } + else { + this.warnings.push("No EndOfContent block encoded"); + } + } + return currentOffset; + } + toBER(sizeOnly, writer) { + const _writer = writer || new ViewWriter(); + for (let i = 0; i < this.value.length; i++) { + this.value[i].toBER(sizeOnly, _writer); + } + if (!writer) { + return _writer.final(); + } + return EMPTY_BUFFER; + } + toJSON() { + const object = { + ...super.toJSON(), + isIndefiniteForm: this.isIndefiniteForm, + value: [], + }; + for (const value of this.value) { + object.value.push(value.toJSON()); + } + return object; + } +} +LocalConstructedValueBlock.NAME = "ConstructedValueBlock"; + +var _a$v; +class Constructed extends BaseBlock { + constructor(parameters = {}) { + super(parameters, LocalConstructedValueBlock); + this.idBlock.isConstructed = true; + } + fromBER(inputBuffer, inputOffset, inputLength) { + this.valueBlock.isIndefiniteForm = this.lenBlock.isIndefiniteForm; + const resultOffset = this.valueBlock.fromBER(inputBuffer, inputOffset, (this.lenBlock.isIndefiniteForm) ? inputLength : this.lenBlock.length); + if (resultOffset === -1) { + this.error = this.valueBlock.error; + return resultOffset; + } + if (!this.idBlock.error.length) + this.blockLength += this.idBlock.blockLength; + if (!this.lenBlock.error.length) + this.blockLength += this.lenBlock.blockLength; + if (!this.valueBlock.error.length) + this.blockLength += this.valueBlock.blockLength; + return resultOffset; + } + onAsciiEncoding() { + const values = []; + for (const value of this.valueBlock.value) { + values.push(value.toString("ascii").split("\n").map(o => ` ${o}`).join("\n")); + } + const blockName = this.idBlock.tagClass === 3 + ? `[${this.idBlock.tagNumber}]` + : this.constructor.NAME; + return values.length + ? `${blockName} :\n${values.join("\n")}` + : `${blockName} :`; + } +} +_a$v = Constructed; +(() => { + typeStore.Constructed = _a$v; +})(); +Constructed.NAME = "CONSTRUCTED"; + +class LocalEndOfContentValueBlock extends ValueBlock { + fromBER(inputBuffer, inputOffset, inputLength) { + return inputOffset; + } + toBER(sizeOnly) { + return EMPTY_BUFFER; + } +} +LocalEndOfContentValueBlock.override = "EndOfContentValueBlock"; + +var _a$u; +class EndOfContent extends BaseBlock { + constructor(parameters = {}) { + super(parameters, LocalEndOfContentValueBlock); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 0; + } +} +_a$u = EndOfContent; +(() => { + typeStore.EndOfContent = _a$u; +})(); +EndOfContent.NAME = END_OF_CONTENT_NAME; + +var _a$t; +class Null extends BaseBlock { + constructor(parameters = {}) { + super(parameters, ValueBlock); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 5; + } + fromBER(inputBuffer, inputOffset, inputLength) { + if (this.lenBlock.length > 0) + this.warnings.push("Non-zero length of value block for Null type"); + if (!this.idBlock.error.length) + this.blockLength += this.idBlock.blockLength; + if (!this.lenBlock.error.length) + this.blockLength += this.lenBlock.blockLength; + this.blockLength += inputLength; + if ((inputOffset + inputLength) > inputBuffer.byteLength) { + this.error = "End of input reached before message was fully decoded (inconsistent offset and length values)"; + return -1; + } + return (inputOffset + inputLength); + } + toBER(sizeOnly, writer) { + const retBuf = new ArrayBuffer(2); + if (!sizeOnly) { + const retView = new Uint8Array(retBuf); + retView[0] = 0x05; + retView[1] = 0x00; + } + if (writer) { + writer.write(retBuf); + } + return retBuf; + } + onAsciiEncoding() { + return `${this.constructor.NAME}`; + } +} +_a$t = Null; +(() => { + typeStore.Null = _a$t; +})(); +Null.NAME = "NULL"; + +class LocalBooleanValueBlock extends HexBlock(ValueBlock) { + constructor({ value, ...parameters } = {}) { + super(parameters); + if (parameters.valueHex) { + this.valueHexView = pvtsutils.BufferSourceConverter.toUint8Array(parameters.valueHex); + } + else { + this.valueHexView = new Uint8Array(1); + } + if (value) { + this.value = value; + } + } + get value() { + for (const octet of this.valueHexView) { + if (octet > 0) { + return true; + } + } + return false; + } + set value(value) { + this.valueHexView[0] = value ? 0xFF : 0x00; + } + fromBER(inputBuffer, inputOffset, inputLength) { + const inputView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer); + if (!checkBufferParams(this, inputView, inputOffset, inputLength)) { + return -1; + } + this.valueHexView = inputView.subarray(inputOffset, inputOffset + inputLength); + if (inputLength > 1) + this.warnings.push("Boolean value encoded in more then 1 octet"); + this.isHexOnly = true; + pvutils.utilDecodeTC.call(this); + this.blockLength = inputLength; + return (inputOffset + inputLength); + } + toBER() { + return this.valueHexView.slice(); + } + toJSON() { + return { + ...super.toJSON(), + value: this.value, + }; + } +} +LocalBooleanValueBlock.NAME = "BooleanValueBlock"; + +var _a$s; +class Boolean extends BaseBlock { + constructor(parameters = {}) { + super(parameters, LocalBooleanValueBlock); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 1; + } + getValue() { + return this.valueBlock.value; + } + setValue(value) { + this.valueBlock.value = value; + } + onAsciiEncoding() { + return `${this.constructor.NAME} : ${this.getValue}`; + } +} +_a$s = Boolean; +(() => { + typeStore.Boolean = _a$s; +})(); +Boolean.NAME = "BOOLEAN"; + +class LocalOctetStringValueBlock extends HexBlock(LocalConstructedValueBlock) { + constructor({ isConstructed = false, ...parameters } = {}) { + super(parameters); + this.isConstructed = isConstructed; + } + fromBER(inputBuffer, inputOffset, inputLength) { + let resultOffset = 0; + if (this.isConstructed) { + this.isHexOnly = false; + resultOffset = LocalConstructedValueBlock.prototype.fromBER.call(this, inputBuffer, inputOffset, inputLength); + if (resultOffset === -1) + return resultOffset; + for (let i = 0; i < this.value.length; i++) { + const currentBlockName = this.value[i].constructor.NAME; + if (currentBlockName === END_OF_CONTENT_NAME) { + if (this.isIndefiniteForm) + break; + else { + this.error = "EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only"; + return -1; + } + } + if (currentBlockName !== OCTET_STRING_NAME) { + this.error = "OCTET STRING may consists of OCTET STRINGs only"; + return -1; + } + } + } + else { + this.isHexOnly = true; + resultOffset = super.fromBER(inputBuffer, inputOffset, inputLength); + this.blockLength = inputLength; + } + return resultOffset; + } + toBER(sizeOnly, writer) { + if (this.isConstructed) + return LocalConstructedValueBlock.prototype.toBER.call(this, sizeOnly, writer); + return sizeOnly + ? new ArrayBuffer(this.valueHexView.byteLength) + : this.valueHexView.slice().buffer; + } + toJSON() { + return { + ...super.toJSON(), + isConstructed: this.isConstructed, + }; + } +} +LocalOctetStringValueBlock.NAME = "OctetStringValueBlock"; + +var _a$r; +class OctetString extends BaseBlock { + constructor({ idBlock = {}, lenBlock = {}, ...parameters } = {}) { + var _b, _c; + (_b = parameters.isConstructed) !== null && _b !== void 0 ? _b : (parameters.isConstructed = !!((_c = parameters.value) === null || _c === void 0 ? void 0 : _c.length)); + super({ + idBlock: { + isConstructed: parameters.isConstructed, + ...idBlock, + }, + lenBlock: { + ...lenBlock, + isIndefiniteForm: !!parameters.isIndefiniteForm, + }, + ...parameters, + }, LocalOctetStringValueBlock); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 4; + } + fromBER(inputBuffer, inputOffset, inputLength) { + this.valueBlock.isConstructed = this.idBlock.isConstructed; + this.valueBlock.isIndefiniteForm = this.lenBlock.isIndefiniteForm; + if (inputLength === 0) { + if (this.idBlock.error.length === 0) + this.blockLength += this.idBlock.blockLength; + if (this.lenBlock.error.length === 0) + this.blockLength += this.lenBlock.blockLength; + return inputOffset; + } + if (!this.valueBlock.isConstructed) { + const view = inputBuffer instanceof ArrayBuffer ? new Uint8Array(inputBuffer) : inputBuffer; + const buf = view.subarray(inputOffset, inputOffset + inputLength); + try { + if (buf.byteLength) { + const asn = localFromBER(buf, 0, buf.byteLength); + if (asn.offset !== -1 && asn.offset === inputLength) { + this.valueBlock.value = [asn.result]; + } + } + } + catch (e) { + } + } + return super.fromBER(inputBuffer, inputOffset, inputLength); + } + onAsciiEncoding() { + if (this.valueBlock.isConstructed || (this.valueBlock.value && this.valueBlock.value.length)) { + return Constructed.prototype.onAsciiEncoding.call(this); + } + return `${this.constructor.NAME} : ${pvtsutils.Convert.ToHex(this.valueBlock.valueHexView)}`; + } + getValue() { + if (!this.idBlock.isConstructed) { + return this.valueBlock.valueHexView.slice().buffer; + } + const array = []; + for (const content of this.valueBlock.value) { + if (content instanceof OctetString) { + array.push(content.valueBlock.valueHexView); + } + } + return pvtsutils.BufferSourceConverter.concat(array); + } +} +_a$r = OctetString; +(() => { + typeStore.OctetString = _a$r; +})(); +OctetString.NAME = OCTET_STRING_NAME; + +class LocalBitStringValueBlock extends HexBlock(LocalConstructedValueBlock) { + constructor({ unusedBits = 0, isConstructed = false, ...parameters } = {}) { + super(parameters); + this.unusedBits = unusedBits; + this.isConstructed = isConstructed; + this.blockLength = this.valueHexView.byteLength; + } + fromBER(inputBuffer, inputOffset, inputLength) { + if (!inputLength) { + return inputOffset; + } + let resultOffset = -1; + if (this.isConstructed) { + resultOffset = LocalConstructedValueBlock.prototype.fromBER.call(this, inputBuffer, inputOffset, inputLength); + if (resultOffset === -1) + return resultOffset; + for (const value of this.value) { + const currentBlockName = value.constructor.NAME; + if (currentBlockName === END_OF_CONTENT_NAME) { + if (this.isIndefiniteForm) + break; + else { + this.error = "EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only"; + return -1; + } + } + if (currentBlockName !== BIT_STRING_NAME) { + this.error = "BIT STRING may consists of BIT STRINGs only"; + return -1; + } + const valueBlock = value.valueBlock; + if ((this.unusedBits > 0) && (valueBlock.unusedBits > 0)) { + this.error = "Using of \"unused bits\" inside constructive BIT STRING allowed for least one only"; + return -1; + } + this.unusedBits = valueBlock.unusedBits; + } + return resultOffset; + } + const inputView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer); + if (!checkBufferParams(this, inputView, inputOffset, inputLength)) { + return -1; + } + const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength); + this.unusedBits = intBuffer[0]; + if (this.unusedBits > 7) { + this.error = "Unused bits for BitString must be in range 0-7"; + return -1; + } + if (!this.unusedBits) { + const buf = intBuffer.subarray(1); + try { + if (buf.byteLength) { + const asn = localFromBER(buf, 0, buf.byteLength); + if (asn.offset !== -1 && asn.offset === (inputLength - 1)) { + this.value = [asn.result]; + } + } + } + catch (e) { + } + } + this.valueHexView = intBuffer.subarray(1); + this.blockLength = intBuffer.length; + return (inputOffset + inputLength); + } + toBER(sizeOnly, writer) { + if (this.isConstructed) { + return LocalConstructedValueBlock.prototype.toBER.call(this, sizeOnly, writer); + } + if (sizeOnly) { + return new ArrayBuffer(this.valueHexView.byteLength + 1); + } + if (!this.valueHexView.byteLength) { + return EMPTY_BUFFER; + } + const retView = new Uint8Array(this.valueHexView.length + 1); + retView[0] = this.unusedBits; + retView.set(this.valueHexView, 1); + return retView.buffer; + } + toJSON() { + return { + ...super.toJSON(), + unusedBits: this.unusedBits, + isConstructed: this.isConstructed, + }; + } +} +LocalBitStringValueBlock.NAME = "BitStringValueBlock"; + +var _a$q; +class BitString extends BaseBlock { + constructor({ idBlock = {}, lenBlock = {}, ...parameters } = {}) { + var _b, _c; + (_b = parameters.isConstructed) !== null && _b !== void 0 ? _b : (parameters.isConstructed = !!((_c = parameters.value) === null || _c === void 0 ? void 0 : _c.length)); + super({ + idBlock: { + isConstructed: parameters.isConstructed, + ...idBlock, + }, + lenBlock: { + ...lenBlock, + isIndefiniteForm: !!parameters.isIndefiniteForm, + }, + ...parameters, + }, LocalBitStringValueBlock); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 3; + } + fromBER(inputBuffer, inputOffset, inputLength) { + this.valueBlock.isConstructed = this.idBlock.isConstructed; + this.valueBlock.isIndefiniteForm = this.lenBlock.isIndefiniteForm; + return super.fromBER(inputBuffer, inputOffset, inputLength); + } + onAsciiEncoding() { + if (this.valueBlock.isConstructed || (this.valueBlock.value && this.valueBlock.value.length)) { + return Constructed.prototype.onAsciiEncoding.call(this); + } + else { + const bits = []; + const valueHex = this.valueBlock.valueHexView; + for (const byte of valueHex) { + bits.push(byte.toString(2).padStart(8, "0")); + } + const bitsStr = bits.join(""); + return `${this.constructor.NAME} : ${bitsStr.substring(0, bitsStr.length - this.valueBlock.unusedBits)}`; + } + } +} +_a$q = BitString; +(() => { + typeStore.BitString = _a$q; +})(); +BitString.NAME = BIT_STRING_NAME; + +var _a$p; +function viewAdd(first, second) { + const c = new Uint8Array([0]); + const firstView = new Uint8Array(first); + const secondView = new Uint8Array(second); + let firstViewCopy = firstView.slice(0); + const firstViewCopyLength = firstViewCopy.length - 1; + const secondViewCopy = secondView.slice(0); + const secondViewCopyLength = secondViewCopy.length - 1; + let value = 0; + const max = (secondViewCopyLength < firstViewCopyLength) ? firstViewCopyLength : secondViewCopyLength; + let counter = 0; + for (let i = max; i >= 0; i--, counter++) { + switch (true) { + case (counter < secondViewCopy.length): + value = firstViewCopy[firstViewCopyLength - counter] + secondViewCopy[secondViewCopyLength - counter] + c[0]; + break; + default: + value = firstViewCopy[firstViewCopyLength - counter] + c[0]; + } + c[0] = value / 10; + switch (true) { + case (counter >= firstViewCopy.length): + firstViewCopy = pvutils.utilConcatView(new Uint8Array([value % 10]), firstViewCopy); + break; + default: + firstViewCopy[firstViewCopyLength - counter] = value % 10; + } + } + if (c[0] > 0) + firstViewCopy = pvutils.utilConcatView(c, firstViewCopy); + return firstViewCopy; +} +function power2(n) { + if (n >= powers2.length) { + for (let p = powers2.length; p <= n; p++) { + const c = new Uint8Array([0]); + let digits = (powers2[p - 1]).slice(0); + for (let i = (digits.length - 1); i >= 0; i--) { + const newValue = new Uint8Array([(digits[i] << 1) + c[0]]); + c[0] = newValue[0] / 10; + digits[i] = newValue[0] % 10; + } + if (c[0] > 0) + digits = pvutils.utilConcatView(c, digits); + powers2.push(digits); + } + } + return powers2[n]; +} +function viewSub(first, second) { + let b = 0; + const firstView = new Uint8Array(first); + const secondView = new Uint8Array(second); + const firstViewCopy = firstView.slice(0); + const firstViewCopyLength = firstViewCopy.length - 1; + const secondViewCopy = secondView.slice(0); + const secondViewCopyLength = secondViewCopy.length - 1; + let value; + let counter = 0; + for (let i = secondViewCopyLength; i >= 0; i--, counter++) { + value = firstViewCopy[firstViewCopyLength - counter] - secondViewCopy[secondViewCopyLength - counter] - b; + switch (true) { + case (value < 0): + b = 1; + firstViewCopy[firstViewCopyLength - counter] = value + 10; + break; + default: + b = 0; + firstViewCopy[firstViewCopyLength - counter] = value; + } + } + if (b > 0) { + for (let i = (firstViewCopyLength - secondViewCopyLength + 1); i >= 0; i--, counter++) { + value = firstViewCopy[firstViewCopyLength - counter] - b; + if (value < 0) { + b = 1; + firstViewCopy[firstViewCopyLength - counter] = value + 10; + } + else { + b = 0; + firstViewCopy[firstViewCopyLength - counter] = value; + break; + } + } + } + return firstViewCopy.slice(); +} +class LocalIntegerValueBlock extends HexBlock(ValueBlock) { + constructor({ value, ...parameters } = {}) { + super(parameters); + this._valueDec = 0; + if (parameters.valueHex) { + this.setValueHex(); + } + if (value !== undefined) { + this.valueDec = value; + } + } + setValueHex() { + if (this.valueHexView.length >= 4) { + this.warnings.push("Too big Integer for decoding, hex only"); + this.isHexOnly = true; + this._valueDec = 0; + } + else { + this.isHexOnly = false; + if (this.valueHexView.length > 0) { + this._valueDec = pvutils.utilDecodeTC.call(this); + } + } + } + set valueDec(v) { + this._valueDec = v; + this.isHexOnly = false; + this.valueHexView = new Uint8Array(pvutils.utilEncodeTC(v)); + } + get valueDec() { + return this._valueDec; + } + fromDER(inputBuffer, inputOffset, inputLength, expectedLength = 0) { + const offset = this.fromBER(inputBuffer, inputOffset, inputLength); + if (offset === -1) + return offset; + const view = this.valueHexView; + if ((view[0] === 0x00) && ((view[1] & 0x80) !== 0)) { + this.valueHexView = view.subarray(1); + } + else { + if (expectedLength !== 0) { + if (view.length < expectedLength) { + if ((expectedLength - view.length) > 1) + expectedLength = view.length + 1; + this.valueHexView = view.subarray(expectedLength - view.length); + } + } + } + return offset; + } + toDER(sizeOnly = false) { + const view = this.valueHexView; + switch (true) { + case ((view[0] & 0x80) !== 0): + { + const updatedView = new Uint8Array(this.valueHexView.length + 1); + updatedView[0] = 0x00; + updatedView.set(view, 1); + this.valueHexView = updatedView; + } + break; + case ((view[0] === 0x00) && ((view[1] & 0x80) === 0)): + { + this.valueHexView = this.valueHexView.subarray(1); + } + break; + } + return this.toBER(sizeOnly); + } + fromBER(inputBuffer, inputOffset, inputLength) { + const resultOffset = super.fromBER(inputBuffer, inputOffset, inputLength); + if (resultOffset === -1) { + return resultOffset; + } + this.setValueHex(); + return resultOffset; + } + toBER(sizeOnly) { + return sizeOnly + ? new ArrayBuffer(this.valueHexView.length) + : this.valueHexView.slice().buffer; + } + toJSON() { + return { + ...super.toJSON(), + valueDec: this.valueDec, + }; + } + toString() { + const firstBit = (this.valueHexView.length * 8) - 1; + let digits = new Uint8Array((this.valueHexView.length * 8) / 3); + let bitNumber = 0; + let currentByte; + const asn1View = this.valueHexView; + let result = ""; + let flag = false; + for (let byteNumber = (asn1View.byteLength - 1); byteNumber >= 0; byteNumber--) { + currentByte = asn1View[byteNumber]; + for (let i = 0; i < 8; i++) { + if ((currentByte & 1) === 1) { + switch (bitNumber) { + case firstBit: + digits = viewSub(power2(bitNumber), digits); + result = "-"; + break; + default: + digits = viewAdd(digits, power2(bitNumber)); + } + } + bitNumber++; + currentByte >>= 1; + } + } + for (let i = 0; i < digits.length; i++) { + if (digits[i]) + flag = true; + if (flag) + result += digitsString.charAt(digits[i]); + } + if (flag === false) + result += digitsString.charAt(0); + return result; + } +} +_a$p = LocalIntegerValueBlock; +LocalIntegerValueBlock.NAME = "IntegerValueBlock"; +(() => { + Object.defineProperty(_a$p.prototype, "valueHex", { + set: function (v) { + this.valueHexView = new Uint8Array(v); + this.setValueHex(); + }, + get: function () { + return this.valueHexView.slice().buffer; + }, + }); +})(); + +var _a$o; +class Integer extends BaseBlock { + constructor(parameters = {}) { + super(parameters, LocalIntegerValueBlock); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 2; + } + toBigInt() { + assertBigInt(); + return BigInt(this.valueBlock.toString()); + } + static fromBigInt(value) { + assertBigInt(); + const bigIntValue = BigInt(value); + const writer = new ViewWriter(); + const hex = bigIntValue.toString(16).replace(/^-/, ""); + const view = new Uint8Array(pvtsutils.Convert.FromHex(hex)); + if (bigIntValue < 0) { + const first = new Uint8Array(view.length + (view[0] & 0x80 ? 1 : 0)); + first[0] |= 0x80; + const firstInt = BigInt(`0x${pvtsutils.Convert.ToHex(first)}`); + const secondInt = firstInt + bigIntValue; + const second = pvtsutils.BufferSourceConverter.toUint8Array(pvtsutils.Convert.FromHex(secondInt.toString(16))); + second[0] |= 0x80; + writer.write(second); + } + else { + if (view[0] & 0x80) { + writer.write(new Uint8Array([0])); + } + writer.write(view); + } + const res = new Integer({ + valueHex: writer.final(), + }); + return res; + } + convertToDER() { + const integer = new Integer({ valueHex: this.valueBlock.valueHexView }); + integer.valueBlock.toDER(); + return integer; + } + convertFromDER() { + return new Integer({ + valueHex: this.valueBlock.valueHexView[0] === 0 + ? this.valueBlock.valueHexView.subarray(1) + : this.valueBlock.valueHexView, + }); + } + onAsciiEncoding() { + return `${this.constructor.NAME} : ${this.valueBlock.toString()}`; + } +} +_a$o = Integer; +(() => { + typeStore.Integer = _a$o; +})(); +Integer.NAME = "INTEGER"; + +var _a$n; +class Enumerated extends Integer { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 10; + } +} +_a$n = Enumerated; +(() => { + typeStore.Enumerated = _a$n; +})(); +Enumerated.NAME = "ENUMERATED"; + +class LocalSidValueBlock extends HexBlock(ValueBlock) { + constructor({ valueDec = -1, isFirstSid = false, ...parameters } = {}) { + super(parameters); + this.valueDec = valueDec; + this.isFirstSid = isFirstSid; + } + fromBER(inputBuffer, inputOffset, inputLength) { + if (!inputLength) { + return inputOffset; + } + const inputView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer); + if (!checkBufferParams(this, inputView, inputOffset, inputLength)) { + return -1; + } + const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength); + this.valueHexView = new Uint8Array(inputLength); + for (let i = 0; i < inputLength; i++) { + this.valueHexView[i] = intBuffer[i] & 0x7F; + this.blockLength++; + if ((intBuffer[i] & 0x80) === 0x00) + break; + } + const tempView = new Uint8Array(this.blockLength); + for (let i = 0; i < this.blockLength; i++) { + tempView[i] = this.valueHexView[i]; + } + this.valueHexView = tempView; + if ((intBuffer[this.blockLength - 1] & 0x80) !== 0x00) { + this.error = "End of input reached before message was fully decoded"; + return -1; + } + if (this.valueHexView[0] === 0x00) + this.warnings.push("Needlessly long format of SID encoding"); + if (this.blockLength <= 8) + this.valueDec = pvutils.utilFromBase(this.valueHexView, 7); + else { + this.isHexOnly = true; + this.warnings.push("Too big SID for decoding, hex only"); + } + return (inputOffset + this.blockLength); + } + set valueBigInt(value) { + assertBigInt(); + let bits = BigInt(value).toString(2); + while (bits.length % 7) { + bits = "0" + bits; + } + const bytes = new Uint8Array(bits.length / 7); + for (let i = 0; i < bytes.length; i++) { + bytes[i] = parseInt(bits.slice(i * 7, i * 7 + 7), 2) + (i + 1 < bytes.length ? 0x80 : 0); + } + this.fromBER(bytes.buffer, 0, bytes.length); + } + toBER(sizeOnly) { + if (this.isHexOnly) { + if (sizeOnly) + return (new ArrayBuffer(this.valueHexView.byteLength)); + const curView = this.valueHexView; + const retView = new Uint8Array(this.blockLength); + for (let i = 0; i < (this.blockLength - 1); i++) + retView[i] = curView[i] | 0x80; + retView[this.blockLength - 1] = curView[this.blockLength - 1]; + return retView.buffer; + } + const encodedBuf = pvutils.utilToBase(this.valueDec, 7); + if (encodedBuf.byteLength === 0) { + this.error = "Error during encoding SID value"; + return EMPTY_BUFFER; + } + const retView = new Uint8Array(encodedBuf.byteLength); + if (!sizeOnly) { + const encodedView = new Uint8Array(encodedBuf); + const len = encodedBuf.byteLength - 1; + for (let i = 0; i < len; i++) + retView[i] = encodedView[i] | 0x80; + retView[len] = encodedView[len]; + } + return retView; + } + toString() { + let result = ""; + if (this.isHexOnly) + result = pvtsutils.Convert.ToHex(this.valueHexView); + else { + if (this.isFirstSid) { + let sidValue = this.valueDec; + if (this.valueDec <= 39) + result = "0."; + else { + if (this.valueDec <= 79) { + result = "1."; + sidValue -= 40; + } + else { + result = "2."; + sidValue -= 80; + } + } + result += sidValue.toString(); + } + else + result = this.valueDec.toString(); + } + return result; + } + toJSON() { + return { + ...super.toJSON(), + valueDec: this.valueDec, + isFirstSid: this.isFirstSid, + }; + } +} +LocalSidValueBlock.NAME = "sidBlock"; + +class LocalObjectIdentifierValueBlock extends ValueBlock { + constructor({ value = EMPTY_STRING, ...parameters } = {}) { + super(parameters); + this.value = []; + if (value) { + this.fromString(value); + } + } + fromBER(inputBuffer, inputOffset, inputLength) { + let resultOffset = inputOffset; + while (inputLength > 0) { + const sidBlock = new LocalSidValueBlock(); + resultOffset = sidBlock.fromBER(inputBuffer, resultOffset, inputLength); + if (resultOffset === -1) { + this.blockLength = 0; + this.error = sidBlock.error; + return resultOffset; + } + if (this.value.length === 0) + sidBlock.isFirstSid = true; + this.blockLength += sidBlock.blockLength; + inputLength -= sidBlock.blockLength; + this.value.push(sidBlock); + } + return resultOffset; + } + toBER(sizeOnly) { + const retBuffers = []; + for (let i = 0; i < this.value.length; i++) { + const valueBuf = this.value[i].toBER(sizeOnly); + if (valueBuf.byteLength === 0) { + this.error = this.value[i].error; + return EMPTY_BUFFER; + } + retBuffers.push(valueBuf); + } + return concat(retBuffers); + } + fromString(string) { + this.value = []; + let pos1 = 0; + let pos2 = 0; + let sid = ""; + let flag = false; + do { + pos2 = string.indexOf(".", pos1); + if (pos2 === -1) + sid = string.substring(pos1); + else + sid = string.substring(pos1, pos2); + pos1 = pos2 + 1; + if (flag) { + const sidBlock = this.value[0]; + let plus = 0; + switch (sidBlock.valueDec) { + case 0: + break; + case 1: + plus = 40; + break; + case 2: + plus = 80; + break; + default: + this.value = []; + return; + } + const parsedSID = parseInt(sid, 10); + if (isNaN(parsedSID)) + return; + sidBlock.valueDec = parsedSID + plus; + flag = false; + } + else { + const sidBlock = new LocalSidValueBlock(); + if (sid > Number.MAX_SAFE_INTEGER) { + assertBigInt(); + const sidValue = BigInt(sid); + sidBlock.valueBigInt = sidValue; + } + else { + sidBlock.valueDec = parseInt(sid, 10); + if (isNaN(sidBlock.valueDec)) + return; + } + if (!this.value.length) { + sidBlock.isFirstSid = true; + flag = true; + } + this.value.push(sidBlock); + } + } while (pos2 !== -1); + } + toString() { + let result = ""; + let isHexOnly = false; + for (let i = 0; i < this.value.length; i++) { + isHexOnly = this.value[i].isHexOnly; + let sidStr = this.value[i].toString(); + if (i !== 0) + result = `${result}.`; + if (isHexOnly) { + sidStr = `{${sidStr}}`; + if (this.value[i].isFirstSid) + result = `2.{${sidStr} - 80}`; + else + result += sidStr; + } + else + result += sidStr; + } + return result; + } + toJSON() { + const object = { + ...super.toJSON(), + value: this.toString(), + sidArray: [], + }; + for (let i = 0; i < this.value.length; i++) { + object.sidArray.push(this.value[i].toJSON()); + } + return object; + } +} +LocalObjectIdentifierValueBlock.NAME = "ObjectIdentifierValueBlock"; + +var _a$m; +class ObjectIdentifier extends BaseBlock { + constructor(parameters = {}) { + super(parameters, LocalObjectIdentifierValueBlock); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 6; + } + getValue() { + return this.valueBlock.toString(); + } + setValue(value) { + this.valueBlock.fromString(value); + } + onAsciiEncoding() { + return `${this.constructor.NAME} : ${this.valueBlock.toString() || "empty"}`; + } + toJSON() { + return { + ...super.toJSON(), + value: this.getValue(), + }; + } +} +_a$m = ObjectIdentifier; +(() => { + typeStore.ObjectIdentifier = _a$m; +})(); +ObjectIdentifier.NAME = "OBJECT IDENTIFIER"; + +class LocalRelativeSidValueBlock extends HexBlock(LocalBaseBlock) { + constructor({ valueDec = 0, ...parameters } = {}) { + super(parameters); + this.valueDec = valueDec; + } + fromBER(inputBuffer, inputOffset, inputLength) { + if (inputLength === 0) + return inputOffset; + const inputView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer); + if (!checkBufferParams(this, inputView, inputOffset, inputLength)) + return -1; + const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength); + this.valueHexView = new Uint8Array(inputLength); + for (let i = 0; i < inputLength; i++) { + this.valueHexView[i] = intBuffer[i] & 0x7F; + this.blockLength++; + if ((intBuffer[i] & 0x80) === 0x00) + break; + } + const tempView = new Uint8Array(this.blockLength); + for (let i = 0; i < this.blockLength; i++) + tempView[i] = this.valueHexView[i]; + this.valueHexView = tempView; + if ((intBuffer[this.blockLength - 1] & 0x80) !== 0x00) { + this.error = "End of input reached before message was fully decoded"; + return -1; + } + if (this.valueHexView[0] === 0x00) + this.warnings.push("Needlessly long format of SID encoding"); + if (this.blockLength <= 8) + this.valueDec = pvutils.utilFromBase(this.valueHexView, 7); + else { + this.isHexOnly = true; + this.warnings.push("Too big SID for decoding, hex only"); + } + return (inputOffset + this.blockLength); + } + toBER(sizeOnly) { + if (this.isHexOnly) { + if (sizeOnly) + return (new ArrayBuffer(this.valueHexView.byteLength)); + const curView = this.valueHexView; + const retView = new Uint8Array(this.blockLength); + for (let i = 0; i < (this.blockLength - 1); i++) + retView[i] = curView[i] | 0x80; + retView[this.blockLength - 1] = curView[this.blockLength - 1]; + return retView.buffer; + } + const encodedBuf = pvutils.utilToBase(this.valueDec, 7); + if (encodedBuf.byteLength === 0) { + this.error = "Error during encoding SID value"; + return EMPTY_BUFFER; + } + const retView = new Uint8Array(encodedBuf.byteLength); + if (!sizeOnly) { + const encodedView = new Uint8Array(encodedBuf); + const len = encodedBuf.byteLength - 1; + for (let i = 0; i < len; i++) + retView[i] = encodedView[i] | 0x80; + retView[len] = encodedView[len]; + } + return retView.buffer; + } + toString() { + let result = ""; + if (this.isHexOnly) + result = pvtsutils.Convert.ToHex(this.valueHexView); + else { + result = this.valueDec.toString(); + } + return result; + } + toJSON() { + return { + ...super.toJSON(), + valueDec: this.valueDec, + }; + } +} +LocalRelativeSidValueBlock.NAME = "relativeSidBlock"; + +class LocalRelativeObjectIdentifierValueBlock extends ValueBlock { + constructor({ value = EMPTY_STRING, ...parameters } = {}) { + super(parameters); + this.value = []; + if (value) { + this.fromString(value); + } + } + fromBER(inputBuffer, inputOffset, inputLength) { + let resultOffset = inputOffset; + while (inputLength > 0) { + const sidBlock = new LocalRelativeSidValueBlock(); + resultOffset = sidBlock.fromBER(inputBuffer, resultOffset, inputLength); + if (resultOffset === -1) { + this.blockLength = 0; + this.error = sidBlock.error; + return resultOffset; + } + this.blockLength += sidBlock.blockLength; + inputLength -= sidBlock.blockLength; + this.value.push(sidBlock); + } + return resultOffset; + } + toBER(sizeOnly, writer) { + const retBuffers = []; + for (let i = 0; i < this.value.length; i++) { + const valueBuf = this.value[i].toBER(sizeOnly); + if (valueBuf.byteLength === 0) { + this.error = this.value[i].error; + return EMPTY_BUFFER; + } + retBuffers.push(valueBuf); + } + return concat(retBuffers); + } + fromString(string) { + this.value = []; + let pos1 = 0; + let pos2 = 0; + let sid = ""; + do { + pos2 = string.indexOf(".", pos1); + if (pos2 === -1) + sid = string.substring(pos1); + else + sid = string.substring(pos1, pos2); + pos1 = pos2 + 1; + const sidBlock = new LocalRelativeSidValueBlock(); + sidBlock.valueDec = parseInt(sid, 10); + if (isNaN(sidBlock.valueDec)) + return true; + this.value.push(sidBlock); + } while (pos2 !== -1); + return true; + } + toString() { + let result = ""; + let isHexOnly = false; + for (let i = 0; i < this.value.length; i++) { + isHexOnly = this.value[i].isHexOnly; + let sidStr = this.value[i].toString(); + if (i !== 0) + result = `${result}.`; + if (isHexOnly) { + sidStr = `{${sidStr}}`; + result += sidStr; + } + else + result += sidStr; + } + return result; + } + toJSON() { + const object = { + ...super.toJSON(), + value: this.toString(), + sidArray: [], + }; + for (let i = 0; i < this.value.length; i++) + object.sidArray.push(this.value[i].toJSON()); + return object; + } +} +LocalRelativeObjectIdentifierValueBlock.NAME = "RelativeObjectIdentifierValueBlock"; + +var _a$l; +class RelativeObjectIdentifier extends BaseBlock { + constructor(parameters = {}) { + super(parameters, LocalRelativeObjectIdentifierValueBlock); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 13; + } + getValue() { + return this.valueBlock.toString(); + } + setValue(value) { + this.valueBlock.fromString(value); + } + onAsciiEncoding() { + return `${this.constructor.NAME} : ${this.valueBlock.toString() || "empty"}`; + } + toJSON() { + return { + ...super.toJSON(), + value: this.getValue(), + }; + } +} +_a$l = RelativeObjectIdentifier; +(() => { + typeStore.RelativeObjectIdentifier = _a$l; +})(); +RelativeObjectIdentifier.NAME = "RelativeObjectIdentifier"; + +var _a$k; +class Sequence extends Constructed { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 16; + } +} +_a$k = Sequence; +(() => { + typeStore.Sequence = _a$k; +})(); +Sequence.NAME = "SEQUENCE"; + +var _a$j; +class Set extends Constructed { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 17; + } +} +_a$j = Set; +(() => { + typeStore.Set = _a$j; +})(); +Set.NAME = "SET"; + +class LocalStringValueBlock extends HexBlock(ValueBlock) { + constructor({ ...parameters } = {}) { + super(parameters); + this.isHexOnly = true; + this.value = EMPTY_STRING; + } + toJSON() { + return { + ...super.toJSON(), + value: this.value, + }; + } +} +LocalStringValueBlock.NAME = "StringValueBlock"; + +class LocalSimpleStringValueBlock extends LocalStringValueBlock { +} +LocalSimpleStringValueBlock.NAME = "SimpleStringValueBlock"; + +class LocalSimpleStringBlock extends BaseStringBlock { + constructor({ ...parameters } = {}) { + super(parameters, LocalSimpleStringValueBlock); + } + fromBuffer(inputBuffer) { + this.valueBlock.value = String.fromCharCode.apply(null, pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer)); + } + fromString(inputString) { + const strLen = inputString.length; + const view = this.valueBlock.valueHexView = new Uint8Array(strLen); + for (let i = 0; i < strLen; i++) + view[i] = inputString.charCodeAt(i); + this.valueBlock.value = inputString; + } +} +LocalSimpleStringBlock.NAME = "SIMPLE STRING"; + +class LocalUtf8StringValueBlock extends LocalSimpleStringBlock { + fromBuffer(inputBuffer) { + this.valueBlock.valueHexView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer); + try { + this.valueBlock.value = pvtsutils.Convert.ToUtf8String(inputBuffer); + } + catch (ex) { + this.warnings.push(`Error during "decodeURIComponent": ${ex}, using raw string`); + this.valueBlock.value = pvtsutils.Convert.ToBinary(inputBuffer); + } + } + fromString(inputString) { + this.valueBlock.valueHexView = new Uint8Array(pvtsutils.Convert.FromUtf8String(inputString)); + this.valueBlock.value = inputString; + } +} +LocalUtf8StringValueBlock.NAME = "Utf8StringValueBlock"; + +var _a$i; +class Utf8String extends LocalUtf8StringValueBlock { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 12; + } +} +_a$i = Utf8String; +(() => { + typeStore.Utf8String = _a$i; +})(); +Utf8String.NAME = "UTF8String"; + +class LocalBmpStringValueBlock extends LocalSimpleStringBlock { + fromBuffer(inputBuffer) { + this.valueBlock.value = pvtsutils.Convert.ToUtf16String(inputBuffer); + this.valueBlock.valueHexView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer); + } + fromString(inputString) { + this.valueBlock.value = inputString; + this.valueBlock.valueHexView = new Uint8Array(pvtsutils.Convert.FromUtf16String(inputString)); + } +} +LocalBmpStringValueBlock.NAME = "BmpStringValueBlock"; + +var _a$h; +class BmpString extends LocalBmpStringValueBlock { + constructor({ ...parameters } = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 30; + } +} +_a$h = BmpString; +(() => { + typeStore.BmpString = _a$h; +})(); +BmpString.NAME = "BMPString"; + +class LocalUniversalStringValueBlock extends LocalSimpleStringBlock { + fromBuffer(inputBuffer) { + const copyBuffer = ArrayBuffer.isView(inputBuffer) ? inputBuffer.slice().buffer : inputBuffer.slice(0); + const valueView = new Uint8Array(copyBuffer); + for (let i = 0; i < valueView.length; i += 4) { + valueView[i] = valueView[i + 3]; + valueView[i + 1] = valueView[i + 2]; + valueView[i + 2] = 0x00; + valueView[i + 3] = 0x00; + } + this.valueBlock.value = String.fromCharCode.apply(null, new Uint32Array(copyBuffer)); + } + fromString(inputString) { + const strLength = inputString.length; + const valueHexView = this.valueBlock.valueHexView = new Uint8Array(strLength * 4); + for (let i = 0; i < strLength; i++) { + const codeBuf = pvutils.utilToBase(inputString.charCodeAt(i), 8); + const codeView = new Uint8Array(codeBuf); + if (codeView.length > 4) + continue; + const dif = 4 - codeView.length; + for (let j = (codeView.length - 1); j >= 0; j--) + valueHexView[i * 4 + j + dif] = codeView[j]; + } + this.valueBlock.value = inputString; + } +} +LocalUniversalStringValueBlock.NAME = "UniversalStringValueBlock"; + +var _a$g; +class UniversalString extends LocalUniversalStringValueBlock { + constructor({ ...parameters } = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 28; + } +} +_a$g = UniversalString; +(() => { + typeStore.UniversalString = _a$g; +})(); +UniversalString.NAME = "UniversalString"; + +var _a$f; +class NumericString extends LocalSimpleStringBlock { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 18; + } +} +_a$f = NumericString; +(() => { + typeStore.NumericString = _a$f; +})(); +NumericString.NAME = "NumericString"; + +var _a$e; +class PrintableString extends LocalSimpleStringBlock { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 19; + } +} +_a$e = PrintableString; +(() => { + typeStore.PrintableString = _a$e; +})(); +PrintableString.NAME = "PrintableString"; + +var _a$d; +class TeletexString extends LocalSimpleStringBlock { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 20; + } +} +_a$d = TeletexString; +(() => { + typeStore.TeletexString = _a$d; +})(); +TeletexString.NAME = "TeletexString"; + +var _a$c; +class VideotexString extends LocalSimpleStringBlock { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 21; + } +} +_a$c = VideotexString; +(() => { + typeStore.VideotexString = _a$c; +})(); +VideotexString.NAME = "VideotexString"; + +var _a$b; +class IA5String extends LocalSimpleStringBlock { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 22; + } +} +_a$b = IA5String; +(() => { + typeStore.IA5String = _a$b; +})(); +IA5String.NAME = "IA5String"; + +var _a$a; +class GraphicString extends LocalSimpleStringBlock { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 25; + } +} +_a$a = GraphicString; +(() => { + typeStore.GraphicString = _a$a; +})(); +GraphicString.NAME = "GraphicString"; + +var _a$9; +class VisibleString extends LocalSimpleStringBlock { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 26; + } +} +_a$9 = VisibleString; +(() => { + typeStore.VisibleString = _a$9; +})(); +VisibleString.NAME = "VisibleString"; + +var _a$8; +class GeneralString extends LocalSimpleStringBlock { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 27; + } +} +_a$8 = GeneralString; +(() => { + typeStore.GeneralString = _a$8; +})(); +GeneralString.NAME = "GeneralString"; + +var _a$7; +class CharacterString extends LocalSimpleStringBlock { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 29; + } +} +_a$7 = CharacterString; +(() => { + typeStore.CharacterString = _a$7; +})(); +CharacterString.NAME = "CharacterString"; + +var _a$6; +class UTCTime extends VisibleString { + constructor({ value, valueDate, ...parameters } = {}) { + super(parameters); + this.year = 0; + this.month = 0; + this.day = 0; + this.hour = 0; + this.minute = 0; + this.second = 0; + if (value) { + this.fromString(value); + this.valueBlock.valueHexView = new Uint8Array(value.length); + for (let i = 0; i < value.length; i++) + this.valueBlock.valueHexView[i] = value.charCodeAt(i); + } + if (valueDate) { + this.fromDate(valueDate); + this.valueBlock.valueHexView = new Uint8Array(this.toBuffer()); + } + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 23; + } + fromBuffer(inputBuffer) { + this.fromString(String.fromCharCode.apply(null, pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer))); + } + toBuffer() { + const str = this.toString(); + const buffer = new ArrayBuffer(str.length); + const view = new Uint8Array(buffer); + for (let i = 0; i < str.length; i++) + view[i] = str.charCodeAt(i); + return buffer; + } + fromDate(inputDate) { + this.year = inputDate.getUTCFullYear(); + this.month = inputDate.getUTCMonth() + 1; + this.day = inputDate.getUTCDate(); + this.hour = inputDate.getUTCHours(); + this.minute = inputDate.getUTCMinutes(); + this.second = inputDate.getUTCSeconds(); + } + toDate() { + return (new Date(Date.UTC(this.year, this.month - 1, this.day, this.hour, this.minute, this.second))); + } + fromString(inputString) { + const parser = /(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig; + const parserArray = parser.exec(inputString); + if (parserArray === null) { + this.error = "Wrong input string for conversion"; + return; + } + const year = parseInt(parserArray[1], 10); + if (year >= 50) + this.year = 1900 + year; + else + this.year = 2000 + year; + this.month = parseInt(parserArray[2], 10); + this.day = parseInt(parserArray[3], 10); + this.hour = parseInt(parserArray[4], 10); + this.minute = parseInt(parserArray[5], 10); + this.second = parseInt(parserArray[6], 10); + } + toString(encoding = "iso") { + if (encoding === "iso") { + const outputArray = new Array(7); + outputArray[0] = pvutils.padNumber(((this.year < 2000) ? (this.year - 1900) : (this.year - 2000)), 2); + outputArray[1] = pvutils.padNumber(this.month, 2); + outputArray[2] = pvutils.padNumber(this.day, 2); + outputArray[3] = pvutils.padNumber(this.hour, 2); + outputArray[4] = pvutils.padNumber(this.minute, 2); + outputArray[5] = pvutils.padNumber(this.second, 2); + outputArray[6] = "Z"; + return outputArray.join(""); + } + return super.toString(encoding); + } + onAsciiEncoding() { + return `${this.constructor.NAME} : ${this.toDate().toISOString()}`; + } + toJSON() { + return { + ...super.toJSON(), + year: this.year, + month: this.month, + day: this.day, + hour: this.hour, + minute: this.minute, + second: this.second, + }; + } +} +_a$6 = UTCTime; +(() => { + typeStore.UTCTime = _a$6; +})(); +UTCTime.NAME = "UTCTime"; + +var _a$5; +class GeneralizedTime extends UTCTime { + constructor(parameters = {}) { + var _b; + super(parameters); + (_b = this.millisecond) !== null && _b !== void 0 ? _b : (this.millisecond = 0); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 24; + } + fromDate(inputDate) { + super.fromDate(inputDate); + this.millisecond = inputDate.getUTCMilliseconds(); + } + toDate() { + return (new Date(Date.UTC(this.year, this.month - 1, this.day, this.hour, this.minute, this.second, this.millisecond))); + } + fromString(inputString) { + let isUTC = false; + let timeString = ""; + let dateTimeString = ""; + let fractionPart = 0; + let parser; + let hourDifference = 0; + let minuteDifference = 0; + if (inputString[inputString.length - 1] === "Z") { + timeString = inputString.substring(0, inputString.length - 1); + isUTC = true; + } + else { + const number = new Number(inputString[inputString.length - 1]); + if (isNaN(number.valueOf())) + throw new Error("Wrong input string for conversion"); + timeString = inputString; + } + if (isUTC) { + if (timeString.indexOf("+") !== -1) + throw new Error("Wrong input string for conversion"); + if (timeString.indexOf("-") !== -1) + throw new Error("Wrong input string for conversion"); + } + else { + let multiplier = 1; + let differencePosition = timeString.indexOf("+"); + let differenceString = ""; + if (differencePosition === -1) { + differencePosition = timeString.indexOf("-"); + multiplier = -1; + } + if (differencePosition !== -1) { + differenceString = timeString.substring(differencePosition + 1); + timeString = timeString.substring(0, differencePosition); + if ((differenceString.length !== 2) && (differenceString.length !== 4)) + throw new Error("Wrong input string for conversion"); + let number = parseInt(differenceString.substring(0, 2), 10); + if (isNaN(number.valueOf())) + throw new Error("Wrong input string for conversion"); + hourDifference = multiplier * number; + if (differenceString.length === 4) { + number = parseInt(differenceString.substring(2, 4), 10); + if (isNaN(number.valueOf())) + throw new Error("Wrong input string for conversion"); + minuteDifference = multiplier * number; + } + } + } + let fractionPointPosition = timeString.indexOf("."); + if (fractionPointPosition === -1) + fractionPointPosition = timeString.indexOf(","); + if (fractionPointPosition !== -1) { + const fractionPartCheck = new Number(`0${timeString.substring(fractionPointPosition)}`); + if (isNaN(fractionPartCheck.valueOf())) + throw new Error("Wrong input string for conversion"); + fractionPart = fractionPartCheck.valueOf(); + dateTimeString = timeString.substring(0, fractionPointPosition); + } + else + dateTimeString = timeString; + switch (true) { + case (dateTimeString.length === 8): + parser = /(\d{4})(\d{2})(\d{2})/ig; + if (fractionPointPosition !== -1) + throw new Error("Wrong input string for conversion"); + break; + case (dateTimeString.length === 10): + parser = /(\d{4})(\d{2})(\d{2})(\d{2})/ig; + if (fractionPointPosition !== -1) { + let fractionResult = 60 * fractionPart; + this.minute = Math.floor(fractionResult); + fractionResult = 60 * (fractionResult - this.minute); + this.second = Math.floor(fractionResult); + fractionResult = 1000 * (fractionResult - this.second); + this.millisecond = Math.floor(fractionResult); + } + break; + case (dateTimeString.length === 12): + parser = /(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig; + if (fractionPointPosition !== -1) { + let fractionResult = 60 * fractionPart; + this.second = Math.floor(fractionResult); + fractionResult = 1000 * (fractionResult - this.second); + this.millisecond = Math.floor(fractionResult); + } + break; + case (dateTimeString.length === 14): + parser = /(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig; + if (fractionPointPosition !== -1) { + const fractionResult = 1000 * fractionPart; + this.millisecond = Math.floor(fractionResult); + } + break; + default: + throw new Error("Wrong input string for conversion"); + } + const parserArray = parser.exec(dateTimeString); + if (parserArray === null) + throw new Error("Wrong input string for conversion"); + for (let j = 1; j < parserArray.length; j++) { + switch (j) { + case 1: + this.year = parseInt(parserArray[j], 10); + break; + case 2: + this.month = parseInt(parserArray[j], 10); + break; + case 3: + this.day = parseInt(parserArray[j], 10); + break; + case 4: + this.hour = parseInt(parserArray[j], 10) + hourDifference; + break; + case 5: + this.minute = parseInt(parserArray[j], 10) + minuteDifference; + break; + case 6: + this.second = parseInt(parserArray[j], 10); + break; + default: + throw new Error("Wrong input string for conversion"); + } + } + if (isUTC === false) { + const tempDate = new Date(this.year, this.month, this.day, this.hour, this.minute, this.second, this.millisecond); + this.year = tempDate.getUTCFullYear(); + this.month = tempDate.getUTCMonth(); + this.day = tempDate.getUTCDay(); + this.hour = tempDate.getUTCHours(); + this.minute = tempDate.getUTCMinutes(); + this.second = tempDate.getUTCSeconds(); + this.millisecond = tempDate.getUTCMilliseconds(); + } + } + toString(encoding = "iso") { + if (encoding === "iso") { + const outputArray = []; + outputArray.push(pvutils.padNumber(this.year, 4)); + outputArray.push(pvutils.padNumber(this.month, 2)); + outputArray.push(pvutils.padNumber(this.day, 2)); + outputArray.push(pvutils.padNumber(this.hour, 2)); + outputArray.push(pvutils.padNumber(this.minute, 2)); + outputArray.push(pvutils.padNumber(this.second, 2)); + if (this.millisecond !== 0) { + outputArray.push("."); + outputArray.push(pvutils.padNumber(this.millisecond, 3)); + } + outputArray.push("Z"); + return outputArray.join(""); + } + return super.toString(encoding); + } + toJSON() { + return { + ...super.toJSON(), + millisecond: this.millisecond, + }; + } +} +_a$5 = GeneralizedTime; +(() => { + typeStore.GeneralizedTime = _a$5; +})(); +GeneralizedTime.NAME = "GeneralizedTime"; + +var _a$4; +class DATE extends Utf8String { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 31; + } +} +_a$4 = DATE; +(() => { + typeStore.DATE = _a$4; +})(); +DATE.NAME = "DATE"; + +var _a$3; +class TimeOfDay extends Utf8String { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 32; + } +} +_a$3 = TimeOfDay; +(() => { + typeStore.TimeOfDay = _a$3; +})(); +TimeOfDay.NAME = "TimeOfDay"; + +var _a$2; +class DateTime extends Utf8String { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 33; + } +} +_a$2 = DateTime; +(() => { + typeStore.DateTime = _a$2; +})(); +DateTime.NAME = "DateTime"; + +var _a$1; +class Duration extends Utf8String { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 34; + } +} +_a$1 = Duration; +(() => { + typeStore.Duration = _a$1; +})(); +Duration.NAME = "Duration"; + +var _a; +class TIME extends Utf8String { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 14; + } +} +_a = TIME; +(() => { + typeStore.TIME = _a; +})(); +TIME.NAME = "TIME"; + +class Any { + constructor({ name = EMPTY_STRING, optional = false, } = {}) { + this.name = name; + this.optional = optional; + } +} + +class Choice extends Any { + constructor({ value = [], ...parameters } = {}) { + super(parameters); + this.value = value; + } +} + +class Repeated extends Any { + constructor({ value = new Any(), local = false, ...parameters } = {}) { + super(parameters); + this.value = value; + this.local = local; + } +} + +class RawData { + constructor({ data = EMPTY_VIEW } = {}) { + this.dataView = pvtsutils.BufferSourceConverter.toUint8Array(data); + } + get data() { + return this.dataView.slice().buffer; + } + set data(value) { + this.dataView = pvtsutils.BufferSourceConverter.toUint8Array(value); + } + fromBER(inputBuffer, inputOffset, inputLength) { + const endLength = inputOffset + inputLength; + this.dataView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer).subarray(inputOffset, endLength); + return endLength; + } + toBER(sizeOnly) { + return this.dataView.slice().buffer; + } +} + +function compareSchema(root, inputData, inputSchema) { + if (inputSchema instanceof Choice) { + for (let j = 0; j < inputSchema.value.length; j++) { + const result = compareSchema(root, inputData, inputSchema.value[j]); + if (result.verified) { + return { + verified: true, + result: root + }; + } + } + { + const _result = { + verified: false, + result: { + error: "Wrong values for Choice type" + }, + }; + if (inputSchema.hasOwnProperty(NAME)) + _result.name = inputSchema.name; + return _result; + } + } + if (inputSchema instanceof Any) { + if (inputSchema.hasOwnProperty(NAME)) + root[inputSchema.name] = inputData; + return { + verified: true, + result: root + }; + } + if ((root instanceof Object) === false) { + return { + verified: false, + result: { error: "Wrong root object" } + }; + } + if ((inputData instanceof Object) === false) { + return { + verified: false, + result: { error: "Wrong ASN.1 data" } + }; + } + if ((inputSchema instanceof Object) === false) { + return { + verified: false, + result: { error: "Wrong ASN.1 schema" } + }; + } + if ((ID_BLOCK in inputSchema) === false) { + return { + verified: false, + result: { error: "Wrong ASN.1 schema" } + }; + } + if ((FROM_BER in inputSchema.idBlock) === false) { + return { + verified: false, + result: { error: "Wrong ASN.1 schema" } + }; + } + if ((TO_BER in inputSchema.idBlock) === false) { + return { + verified: false, + result: { error: "Wrong ASN.1 schema" } + }; + } + const encodedId = inputSchema.idBlock.toBER(false); + if (encodedId.byteLength === 0) { + return { + verified: false, + result: { error: "Error encoding idBlock for ASN.1 schema" } + }; + } + const decodedOffset = inputSchema.idBlock.fromBER(encodedId, 0, encodedId.byteLength); + if (decodedOffset === -1) { + return { + verified: false, + result: { error: "Error decoding idBlock for ASN.1 schema" } + }; + } + if (inputSchema.idBlock.hasOwnProperty(TAG_CLASS) === false) { + return { + verified: false, + result: { error: "Wrong ASN.1 schema" } + }; + } + if (inputSchema.idBlock.tagClass !== inputData.idBlock.tagClass) { + return { + verified: false, + result: root + }; + } + if (inputSchema.idBlock.hasOwnProperty(TAG_NUMBER) === false) { + return { + verified: false, + result: { error: "Wrong ASN.1 schema" } + }; + } + if (inputSchema.idBlock.tagNumber !== inputData.idBlock.tagNumber) { + return { + verified: false, + result: root + }; + } + if (inputSchema.idBlock.hasOwnProperty(IS_CONSTRUCTED) === false) { + return { + verified: false, + result: { error: "Wrong ASN.1 schema" } + }; + } + if (inputSchema.idBlock.isConstructed !== inputData.idBlock.isConstructed) { + return { + verified: false, + result: root + }; + } + if (!(IS_HEX_ONLY in inputSchema.idBlock)) { + return { + verified: false, + result: { error: "Wrong ASN.1 schema" } + }; + } + if (inputSchema.idBlock.isHexOnly !== inputData.idBlock.isHexOnly) { + return { + verified: false, + result: root + }; + } + if (inputSchema.idBlock.isHexOnly) { + if ((VALUE_HEX_VIEW in inputSchema.idBlock) === false) { + return { + verified: false, + result: { error: "Wrong ASN.1 schema" } + }; + } + const schemaView = inputSchema.idBlock.valueHexView; + const asn1View = inputData.idBlock.valueHexView; + if (schemaView.length !== asn1View.length) { + return { + verified: false, + result: root + }; + } + for (let i = 0; i < schemaView.length; i++) { + if (schemaView[i] !== asn1View[1]) { + return { + verified: false, + result: root + }; + } + } + } + if (inputSchema.name) { + inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING); + if (inputSchema.name) + root[inputSchema.name] = inputData; + } + if (inputSchema instanceof typeStore.Constructed) { + let admission = 0; + let result = { + verified: false, + result: { + error: "Unknown error", + } + }; + let maxLength = inputSchema.valueBlock.value.length; + if (maxLength > 0) { + if (inputSchema.valueBlock.value[0] instanceof Repeated) { + maxLength = inputData.valueBlock.value.length; + } + } + if (maxLength === 0) { + return { + verified: true, + result: root + }; + } + if ((inputData.valueBlock.value.length === 0) && + (inputSchema.valueBlock.value.length !== 0)) { + let _optional = true; + for (let i = 0; i < inputSchema.valueBlock.value.length; i++) + _optional = _optional && (inputSchema.valueBlock.value[i].optional || false); + if (_optional) { + return { + verified: true, + result: root + }; + } + if (inputSchema.name) { + inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING); + if (inputSchema.name) + delete root[inputSchema.name]; + } + root.error = "Inconsistent object length"; + return { + verified: false, + result: root + }; + } + for (let i = 0; i < maxLength; i++) { + if ((i - admission) >= inputData.valueBlock.value.length) { + if (inputSchema.valueBlock.value[i].optional === false) { + const _result = { + verified: false, + result: root + }; + root.error = "Inconsistent length between ASN.1 data and schema"; + if (inputSchema.name) { + inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING); + if (inputSchema.name) { + delete root[inputSchema.name]; + _result.name = inputSchema.name; + } + } + return _result; + } + } + else { + if (inputSchema.valueBlock.value[0] instanceof Repeated) { + result = compareSchema(root, inputData.valueBlock.value[i], inputSchema.valueBlock.value[0].value); + if (result.verified === false) { + if (inputSchema.valueBlock.value[0].optional) + admission++; + else { + if (inputSchema.name) { + inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING); + if (inputSchema.name) + delete root[inputSchema.name]; + } + return result; + } + } + if ((NAME in inputSchema.valueBlock.value[0]) && (inputSchema.valueBlock.value[0].name.length > 0)) { + let arrayRoot = {}; + if ((LOCAL in inputSchema.valueBlock.value[0]) && (inputSchema.valueBlock.value[0].local)) + arrayRoot = inputData; + else + arrayRoot = root; + if (typeof arrayRoot[inputSchema.valueBlock.value[0].name] === "undefined") + arrayRoot[inputSchema.valueBlock.value[0].name] = []; + arrayRoot[inputSchema.valueBlock.value[0].name].push(inputData.valueBlock.value[i]); + } + } + else { + result = compareSchema(root, inputData.valueBlock.value[i - admission], inputSchema.valueBlock.value[i]); + if (result.verified === false) { + if (inputSchema.valueBlock.value[i].optional) + admission++; + else { + if (inputSchema.name) { + inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING); + if (inputSchema.name) + delete root[inputSchema.name]; + } + return result; + } + } + } + } + } + if (result.verified === false) { + const _result = { + verified: false, + result: root + }; + if (inputSchema.name) { + inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING); + if (inputSchema.name) { + delete root[inputSchema.name]; + _result.name = inputSchema.name; + } + } + return _result; + } + return { + verified: true, + result: root + }; + } + if (inputSchema.primitiveSchema && + (VALUE_HEX_VIEW in inputData.valueBlock)) { + const asn1 = localFromBER(inputData.valueBlock.valueHexView); + if (asn1.offset === -1) { + const _result = { + verified: false, + result: asn1.result + }; + if (inputSchema.name) { + inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING); + if (inputSchema.name) { + delete root[inputSchema.name]; + _result.name = inputSchema.name; + } + } + return _result; + } + return compareSchema(root, asn1.result, inputSchema.primitiveSchema); + } + return { + verified: true, + result: root + }; +} +function verifySchema(inputBuffer, inputSchema) { + if ((inputSchema instanceof Object) === false) { + return { + verified: false, + result: { error: "Wrong ASN.1 schema type" } + }; + } + const asn1 = localFromBER(pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer)); + if (asn1.offset === -1) { + return { + verified: false, + result: asn1.result + }; + } + return compareSchema(asn1.result, asn1.result, inputSchema); +} + +export { Any, BaseBlock, BaseStringBlock, BitString, BmpString, Boolean, CharacterString, Choice, Constructed, DATE, DateTime, Duration, EndOfContent, Enumerated, GeneralString, GeneralizedTime, GraphicString, HexBlock, IA5String, Integer, Null, NumericString, ObjectIdentifier, OctetString, Primitive, PrintableString, RawData, RelativeObjectIdentifier, Repeated, Sequence, Set, TIME, TeletexString, TimeOfDay, UTCTime, UniversalString, Utf8String, ValueBlock, VideotexString, ViewWriter, VisibleString, compareSchema, fromBER, verifySchema }; diff --git a/gun-server/node_modules/asn1js/build/index.js b/gun-server/node_modules/asn1js/build/index.js new file mode 100644 index 0000000..531086e --- /dev/null +++ b/gun-server/node_modules/asn1js/build/index.js @@ -0,0 +1,3196 @@ +/*! + * Copyright (c) 2014, GMO GlobalSign + * Copyright (c) 2015-2022, Peculiar Ventures + * All rights reserved. + * + * Author 2014-2019, Yury Strozhevsky + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * * Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var pvtsutils = require('pvtsutils'); +var pvutils = require('pvutils'); + +function _interopNamespace(e) { + if (e && e.__esModule) return e; + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n["default"] = e; + return Object.freeze(n); +} + +var pvtsutils__namespace = /*#__PURE__*/_interopNamespace(pvtsutils); +var pvutils__namespace = /*#__PURE__*/_interopNamespace(pvutils); + +function assertBigInt() { + if (typeof BigInt === "undefined") { + throw new Error("BigInt is not defined. Your environment doesn't implement BigInt."); + } +} +function concat(buffers) { + let outputLength = 0; + let prevLength = 0; + for (let i = 0; i < buffers.length; i++) { + const buffer = buffers[i]; + outputLength += buffer.byteLength; + } + const retView = new Uint8Array(outputLength); + for (let i = 0; i < buffers.length; i++) { + const buffer = buffers[i]; + retView.set(new Uint8Array(buffer), prevLength); + prevLength += buffer.byteLength; + } + return retView.buffer; +} +function checkBufferParams(baseBlock, inputBuffer, inputOffset, inputLength) { + if (!(inputBuffer instanceof Uint8Array)) { + baseBlock.error = "Wrong parameter: inputBuffer must be 'Uint8Array'"; + return false; + } + if (!inputBuffer.byteLength) { + baseBlock.error = "Wrong parameter: inputBuffer has zero length"; + return false; + } + if (inputOffset < 0) { + baseBlock.error = "Wrong parameter: inputOffset less than zero"; + return false; + } + if (inputLength < 0) { + baseBlock.error = "Wrong parameter: inputLength less than zero"; + return false; + } + if ((inputBuffer.byteLength - inputOffset - inputLength) < 0) { + baseBlock.error = "End of input reached before message was fully decoded (inconsistent offset and length values)"; + return false; + } + return true; +} + +class ViewWriter { + constructor() { + this.items = []; + } + write(buf) { + this.items.push(buf); + } + final() { + return concat(this.items); + } +} + +const powers2 = [new Uint8Array([1])]; +const digitsString = "0123456789"; +const NAME = "name"; +const VALUE_HEX_VIEW = "valueHexView"; +const IS_HEX_ONLY = "isHexOnly"; +const ID_BLOCK = "idBlock"; +const TAG_CLASS = "tagClass"; +const TAG_NUMBER = "tagNumber"; +const IS_CONSTRUCTED = "isConstructed"; +const FROM_BER = "fromBER"; +const TO_BER = "toBER"; +const LOCAL = "local"; +const EMPTY_STRING = ""; +const EMPTY_BUFFER = new ArrayBuffer(0); +const EMPTY_VIEW = new Uint8Array(0); +const END_OF_CONTENT_NAME = "EndOfContent"; +const OCTET_STRING_NAME = "OCTET STRING"; +const BIT_STRING_NAME = "BIT STRING"; + +function HexBlock(BaseClass) { + var _a; + return _a = class Some extends BaseClass { + constructor(...args) { + var _a; + super(...args); + const params = args[0] || {}; + this.isHexOnly = (_a = params.isHexOnly) !== null && _a !== void 0 ? _a : false; + this.valueHexView = params.valueHex ? pvtsutils__namespace.BufferSourceConverter.toUint8Array(params.valueHex) : EMPTY_VIEW; + } + get valueHex() { + return this.valueHexView.slice().buffer; + } + set valueHex(value) { + this.valueHexView = new Uint8Array(value); + } + fromBER(inputBuffer, inputOffset, inputLength) { + const view = inputBuffer instanceof ArrayBuffer ? new Uint8Array(inputBuffer) : inputBuffer; + if (!checkBufferParams(this, view, inputOffset, inputLength)) { + return -1; + } + const endLength = inputOffset + inputLength; + this.valueHexView = view.subarray(inputOffset, endLength); + if (!this.valueHexView.length) { + this.warnings.push("Zero buffer length"); + return inputOffset; + } + this.blockLength = inputLength; + return endLength; + } + toBER(sizeOnly = false) { + if (!this.isHexOnly) { + this.error = "Flag 'isHexOnly' is not set, abort"; + return EMPTY_BUFFER; + } + if (sizeOnly) { + return new ArrayBuffer(this.valueHexView.byteLength); + } + return (this.valueHexView.byteLength === this.valueHexView.buffer.byteLength) + ? this.valueHexView.buffer + : this.valueHexView.slice().buffer; + } + toJSON() { + return { + ...super.toJSON(), + isHexOnly: this.isHexOnly, + valueHex: pvtsutils__namespace.Convert.ToHex(this.valueHexView), + }; + } + }, + _a.NAME = "hexBlock", + _a; +} + +class LocalBaseBlock { + constructor({ blockLength = 0, error = EMPTY_STRING, warnings = [], valueBeforeDecode = EMPTY_VIEW, } = {}) { + this.blockLength = blockLength; + this.error = error; + this.warnings = warnings; + this.valueBeforeDecodeView = pvtsutils__namespace.BufferSourceConverter.toUint8Array(valueBeforeDecode); + } + static blockName() { + return this.NAME; + } + get valueBeforeDecode() { + return this.valueBeforeDecodeView.slice().buffer; + } + set valueBeforeDecode(value) { + this.valueBeforeDecodeView = new Uint8Array(value); + } + toJSON() { + return { + blockName: this.constructor.NAME, + blockLength: this.blockLength, + error: this.error, + warnings: this.warnings, + valueBeforeDecode: pvtsutils__namespace.Convert.ToHex(this.valueBeforeDecodeView), + }; + } +} +LocalBaseBlock.NAME = "baseBlock"; + +class ValueBlock extends LocalBaseBlock { + fromBER(inputBuffer, inputOffset, inputLength) { + throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'"); + } + toBER(sizeOnly, writer) { + throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'"); + } +} +ValueBlock.NAME = "valueBlock"; + +class LocalIdentificationBlock extends HexBlock(LocalBaseBlock) { + constructor({ idBlock = {}, } = {}) { + var _a, _b, _c, _d; + super(); + if (idBlock) { + this.isHexOnly = (_a = idBlock.isHexOnly) !== null && _a !== void 0 ? _a : false; + this.valueHexView = idBlock.valueHex ? pvtsutils__namespace.BufferSourceConverter.toUint8Array(idBlock.valueHex) : EMPTY_VIEW; + this.tagClass = (_b = idBlock.tagClass) !== null && _b !== void 0 ? _b : -1; + this.tagNumber = (_c = idBlock.tagNumber) !== null && _c !== void 0 ? _c : -1; + this.isConstructed = (_d = idBlock.isConstructed) !== null && _d !== void 0 ? _d : false; + } + else { + this.tagClass = -1; + this.tagNumber = -1; + this.isConstructed = false; + } + } + toBER(sizeOnly = false) { + let firstOctet = 0; + switch (this.tagClass) { + case 1: + firstOctet |= 0x00; + break; + case 2: + firstOctet |= 0x40; + break; + case 3: + firstOctet |= 0x80; + break; + case 4: + firstOctet |= 0xC0; + break; + default: + this.error = "Unknown tag class"; + return EMPTY_BUFFER; + } + if (this.isConstructed) + firstOctet |= 0x20; + if (this.tagNumber < 31 && !this.isHexOnly) { + const retView = new Uint8Array(1); + if (!sizeOnly) { + let number = this.tagNumber; + number &= 0x1F; + firstOctet |= number; + retView[0] = firstOctet; + } + return retView.buffer; + } + if (!this.isHexOnly) { + const encodedBuf = pvutils__namespace.utilToBase(this.tagNumber, 7); + const encodedView = new Uint8Array(encodedBuf); + const size = encodedBuf.byteLength; + const retView = new Uint8Array(size + 1); + retView[0] = (firstOctet | 0x1F); + if (!sizeOnly) { + for (let i = 0; i < (size - 1); i++) + retView[i + 1] = encodedView[i] | 0x80; + retView[size] = encodedView[size - 1]; + } + return retView.buffer; + } + const retView = new Uint8Array(this.valueHexView.byteLength + 1); + retView[0] = (firstOctet | 0x1F); + if (!sizeOnly) { + const curView = this.valueHexView; + for (let i = 0; i < (curView.length - 1); i++) + retView[i + 1] = curView[i] | 0x80; + retView[this.valueHexView.byteLength] = curView[curView.length - 1]; + } + return retView.buffer; + } + fromBER(inputBuffer, inputOffset, inputLength) { + const inputView = pvtsutils__namespace.BufferSourceConverter.toUint8Array(inputBuffer); + if (!checkBufferParams(this, inputView, inputOffset, inputLength)) { + return -1; + } + const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength); + if (intBuffer.length === 0) { + this.error = "Zero buffer length"; + return -1; + } + const tagClassMask = intBuffer[0] & 0xC0; + switch (tagClassMask) { + case 0x00: + this.tagClass = (1); + break; + case 0x40: + this.tagClass = (2); + break; + case 0x80: + this.tagClass = (3); + break; + case 0xC0: + this.tagClass = (4); + break; + default: + this.error = "Unknown tag class"; + return -1; + } + this.isConstructed = (intBuffer[0] & 0x20) === 0x20; + this.isHexOnly = false; + const tagNumberMask = intBuffer[0] & 0x1F; + if (tagNumberMask !== 0x1F) { + this.tagNumber = (tagNumberMask); + this.blockLength = 1; + } + else { + let count = 1; + let intTagNumberBuffer = this.valueHexView = new Uint8Array(255); + let tagNumberBufferMaxLength = 255; + while (intBuffer[count] & 0x80) { + intTagNumberBuffer[count - 1] = intBuffer[count] & 0x7F; + count++; + if (count >= intBuffer.length) { + this.error = "End of input reached before message was fully decoded"; + return -1; + } + if (count === tagNumberBufferMaxLength) { + tagNumberBufferMaxLength += 255; + const tempBufferView = new Uint8Array(tagNumberBufferMaxLength); + for (let i = 0; i < intTagNumberBuffer.length; i++) + tempBufferView[i] = intTagNumberBuffer[i]; + intTagNumberBuffer = this.valueHexView = new Uint8Array(tagNumberBufferMaxLength); + } + } + this.blockLength = (count + 1); + intTagNumberBuffer[count - 1] = intBuffer[count] & 0x7F; + const tempBufferView = new Uint8Array(count); + for (let i = 0; i < count; i++) + tempBufferView[i] = intTagNumberBuffer[i]; + intTagNumberBuffer = this.valueHexView = new Uint8Array(count); + intTagNumberBuffer.set(tempBufferView); + if (this.blockLength <= 9) + this.tagNumber = pvutils__namespace.utilFromBase(intTagNumberBuffer, 7); + else { + this.isHexOnly = true; + this.warnings.push("Tag too long, represented as hex-coded"); + } + } + if (((this.tagClass === 1)) && + (this.isConstructed)) { + switch (this.tagNumber) { + case 1: + case 2: + case 5: + case 6: + case 9: + case 13: + case 14: + case 23: + case 24: + case 31: + case 32: + case 33: + case 34: + this.error = "Constructed encoding used for primitive type"; + return -1; + } + } + return (inputOffset + this.blockLength); + } + toJSON() { + return { + ...super.toJSON(), + tagClass: this.tagClass, + tagNumber: this.tagNumber, + isConstructed: this.isConstructed, + }; + } +} +LocalIdentificationBlock.NAME = "identificationBlock"; + +class LocalLengthBlock extends LocalBaseBlock { + constructor({ lenBlock = {}, } = {}) { + var _a, _b, _c; + super(); + this.isIndefiniteForm = (_a = lenBlock.isIndefiniteForm) !== null && _a !== void 0 ? _a : false; + this.longFormUsed = (_b = lenBlock.longFormUsed) !== null && _b !== void 0 ? _b : false; + this.length = (_c = lenBlock.length) !== null && _c !== void 0 ? _c : 0; + } + fromBER(inputBuffer, inputOffset, inputLength) { + const view = pvtsutils__namespace.BufferSourceConverter.toUint8Array(inputBuffer); + if (!checkBufferParams(this, view, inputOffset, inputLength)) { + return -1; + } + const intBuffer = view.subarray(inputOffset, inputOffset + inputLength); + if (intBuffer.length === 0) { + this.error = "Zero buffer length"; + return -1; + } + if (intBuffer[0] === 0xFF) { + this.error = "Length block 0xFF is reserved by standard"; + return -1; + } + this.isIndefiniteForm = intBuffer[0] === 0x80; + if (this.isIndefiniteForm) { + this.blockLength = 1; + return (inputOffset + this.blockLength); + } + this.longFormUsed = !!(intBuffer[0] & 0x80); + if (this.longFormUsed === false) { + this.length = (intBuffer[0]); + this.blockLength = 1; + return (inputOffset + this.blockLength); + } + const count = intBuffer[0] & 0x7F; + if (count > 8) { + this.error = "Too big integer"; + return -1; + } + if ((count + 1) > intBuffer.length) { + this.error = "End of input reached before message was fully decoded"; + return -1; + } + const lenOffset = inputOffset + 1; + const lengthBufferView = view.subarray(lenOffset, lenOffset + count); + if (lengthBufferView[count - 1] === 0x00) + this.warnings.push("Needlessly long encoded length"); + this.length = pvutils__namespace.utilFromBase(lengthBufferView, 8); + if (this.longFormUsed && (this.length <= 127)) + this.warnings.push("Unnecessary usage of long length form"); + this.blockLength = count + 1; + return (inputOffset + this.blockLength); + } + toBER(sizeOnly = false) { + let retBuf; + let retView; + if (this.length > 127) + this.longFormUsed = true; + if (this.isIndefiniteForm) { + retBuf = new ArrayBuffer(1); + if (sizeOnly === false) { + retView = new Uint8Array(retBuf); + retView[0] = 0x80; + } + return retBuf; + } + if (this.longFormUsed) { + const encodedBuf = pvutils__namespace.utilToBase(this.length, 8); + if (encodedBuf.byteLength > 127) { + this.error = "Too big length"; + return (EMPTY_BUFFER); + } + retBuf = new ArrayBuffer(encodedBuf.byteLength + 1); + if (sizeOnly) + return retBuf; + const encodedView = new Uint8Array(encodedBuf); + retView = new Uint8Array(retBuf); + retView[0] = encodedBuf.byteLength | 0x80; + for (let i = 0; i < encodedBuf.byteLength; i++) + retView[i + 1] = encodedView[i]; + return retBuf; + } + retBuf = new ArrayBuffer(1); + if (sizeOnly === false) { + retView = new Uint8Array(retBuf); + retView[0] = this.length; + } + return retBuf; + } + toJSON() { + return { + ...super.toJSON(), + isIndefiniteForm: this.isIndefiniteForm, + longFormUsed: this.longFormUsed, + length: this.length, + }; + } +} +LocalLengthBlock.NAME = "lengthBlock"; + +const typeStore = {}; + +class BaseBlock extends LocalBaseBlock { + constructor({ name = EMPTY_STRING, optional = false, primitiveSchema, ...parameters } = {}, valueBlockType) { + super(parameters); + this.name = name; + this.optional = optional; + if (primitiveSchema) { + this.primitiveSchema = primitiveSchema; + } + this.idBlock = new LocalIdentificationBlock(parameters); + this.lenBlock = new LocalLengthBlock(parameters); + this.valueBlock = valueBlockType ? new valueBlockType(parameters) : new ValueBlock(parameters); + } + fromBER(inputBuffer, inputOffset, inputLength) { + const resultOffset = this.valueBlock.fromBER(inputBuffer, inputOffset, (this.lenBlock.isIndefiniteForm) ? inputLength : this.lenBlock.length); + if (resultOffset === -1) { + this.error = this.valueBlock.error; + return resultOffset; + } + if (!this.idBlock.error.length) + this.blockLength += this.idBlock.blockLength; + if (!this.lenBlock.error.length) + this.blockLength += this.lenBlock.blockLength; + if (!this.valueBlock.error.length) + this.blockLength += this.valueBlock.blockLength; + return resultOffset; + } + toBER(sizeOnly, writer) { + const _writer = writer || new ViewWriter(); + if (!writer) { + prepareIndefiniteForm(this); + } + const idBlockBuf = this.idBlock.toBER(sizeOnly); + _writer.write(idBlockBuf); + if (this.lenBlock.isIndefiniteForm) { + _writer.write(new Uint8Array([0x80]).buffer); + this.valueBlock.toBER(sizeOnly, _writer); + _writer.write(new ArrayBuffer(2)); + } + else { + const valueBlockBuf = this.valueBlock.toBER(sizeOnly); + this.lenBlock.length = valueBlockBuf.byteLength; + const lenBlockBuf = this.lenBlock.toBER(sizeOnly); + _writer.write(lenBlockBuf); + _writer.write(valueBlockBuf); + } + if (!writer) { + return _writer.final(); + } + return EMPTY_BUFFER; + } + toJSON() { + const object = { + ...super.toJSON(), + idBlock: this.idBlock.toJSON(), + lenBlock: this.lenBlock.toJSON(), + valueBlock: this.valueBlock.toJSON(), + name: this.name, + optional: this.optional, + }; + if (this.primitiveSchema) + object.primitiveSchema = this.primitiveSchema.toJSON(); + return object; + } + toString(encoding = "ascii") { + if (encoding === "ascii") { + return this.onAsciiEncoding(); + } + return pvtsutils__namespace.Convert.ToHex(this.toBER()); + } + onAsciiEncoding() { + return `${this.constructor.NAME} : ${pvtsutils__namespace.Convert.ToHex(this.valueBlock.valueBeforeDecodeView)}`; + } + isEqual(other) { + if (this === other) { + return true; + } + if (!(other instanceof this.constructor)) { + return false; + } + const thisRaw = this.toBER(); + const otherRaw = other.toBER(); + return pvutils__namespace.isEqualBuffer(thisRaw, otherRaw); + } +} +BaseBlock.NAME = "BaseBlock"; +function prepareIndefiniteForm(baseBlock) { + if (baseBlock instanceof typeStore.Constructed) { + for (const value of baseBlock.valueBlock.value) { + if (prepareIndefiniteForm(value)) { + baseBlock.lenBlock.isIndefiniteForm = true; + } + } + } + return !!baseBlock.lenBlock.isIndefiniteForm; +} + +class BaseStringBlock extends BaseBlock { + constructor({ value = EMPTY_STRING, ...parameters } = {}, stringValueBlockType) { + super(parameters, stringValueBlockType); + if (value) { + this.fromString(value); + } + } + getValue() { + return this.valueBlock.value; + } + setValue(value) { + this.valueBlock.value = value; + } + fromBER(inputBuffer, inputOffset, inputLength) { + const resultOffset = this.valueBlock.fromBER(inputBuffer, inputOffset, (this.lenBlock.isIndefiniteForm) ? inputLength : this.lenBlock.length); + if (resultOffset === -1) { + this.error = this.valueBlock.error; + return resultOffset; + } + this.fromBuffer(this.valueBlock.valueHexView); + if (!this.idBlock.error.length) + this.blockLength += this.idBlock.blockLength; + if (!this.lenBlock.error.length) + this.blockLength += this.lenBlock.blockLength; + if (!this.valueBlock.error.length) + this.blockLength += this.valueBlock.blockLength; + return resultOffset; + } + onAsciiEncoding() { + return `${this.constructor.NAME} : '${this.valueBlock.value}'`; + } +} +BaseStringBlock.NAME = "BaseStringBlock"; + +class LocalPrimitiveValueBlock extends HexBlock(ValueBlock) { + constructor({ isHexOnly = true, ...parameters } = {}) { + super(parameters); + this.isHexOnly = isHexOnly; + } +} +LocalPrimitiveValueBlock.NAME = "PrimitiveValueBlock"; + +var _a$w; +class Primitive extends BaseBlock { + constructor(parameters = {}) { + super(parameters, LocalPrimitiveValueBlock); + this.idBlock.isConstructed = false; + } +} +_a$w = Primitive; +(() => { + typeStore.Primitive = _a$w; +})(); +Primitive.NAME = "PRIMITIVE"; + +function localChangeType(inputObject, newType) { + if (inputObject instanceof newType) { + return inputObject; + } + const newObject = new newType(); + newObject.idBlock = inputObject.idBlock; + newObject.lenBlock = inputObject.lenBlock; + newObject.warnings = inputObject.warnings; + newObject.valueBeforeDecodeView = inputObject.valueBeforeDecodeView; + return newObject; +} +function localFromBER(inputBuffer, inputOffset = 0, inputLength = inputBuffer.length) { + const incomingOffset = inputOffset; + let returnObject = new BaseBlock({}, ValueBlock); + const baseBlock = new LocalBaseBlock(); + if (!checkBufferParams(baseBlock, inputBuffer, inputOffset, inputLength)) { + returnObject.error = baseBlock.error; + return { + offset: -1, + result: returnObject + }; + } + const intBuffer = inputBuffer.subarray(inputOffset, inputOffset + inputLength); + if (!intBuffer.length) { + returnObject.error = "Zero buffer length"; + return { + offset: -1, + result: returnObject + }; + } + let resultOffset = returnObject.idBlock.fromBER(inputBuffer, inputOffset, inputLength); + if (returnObject.idBlock.warnings.length) { + returnObject.warnings.concat(returnObject.idBlock.warnings); + } + if (resultOffset === -1) { + returnObject.error = returnObject.idBlock.error; + return { + offset: -1, + result: returnObject + }; + } + inputOffset = resultOffset; + inputLength -= returnObject.idBlock.blockLength; + resultOffset = returnObject.lenBlock.fromBER(inputBuffer, inputOffset, inputLength); + if (returnObject.lenBlock.warnings.length) { + returnObject.warnings.concat(returnObject.lenBlock.warnings); + } + if (resultOffset === -1) { + returnObject.error = returnObject.lenBlock.error; + return { + offset: -1, + result: returnObject + }; + } + inputOffset = resultOffset; + inputLength -= returnObject.lenBlock.blockLength; + if (!returnObject.idBlock.isConstructed && + returnObject.lenBlock.isIndefiniteForm) { + returnObject.error = "Indefinite length form used for primitive encoding form"; + return { + offset: -1, + result: returnObject + }; + } + let newASN1Type = BaseBlock; + switch (returnObject.idBlock.tagClass) { + case 1: + if ((returnObject.idBlock.tagNumber >= 37) && + (returnObject.idBlock.isHexOnly === false)) { + returnObject.error = "UNIVERSAL 37 and upper tags are reserved by ASN.1 standard"; + return { + offset: -1, + result: returnObject + }; + } + switch (returnObject.idBlock.tagNumber) { + case 0: + if ((returnObject.idBlock.isConstructed) && + (returnObject.lenBlock.length > 0)) { + returnObject.error = "Type [UNIVERSAL 0] is reserved"; + return { + offset: -1, + result: returnObject + }; + } + newASN1Type = typeStore.EndOfContent; + break; + case 1: + newASN1Type = typeStore.Boolean; + break; + case 2: + newASN1Type = typeStore.Integer; + break; + case 3: + newASN1Type = typeStore.BitString; + break; + case 4: + newASN1Type = typeStore.OctetString; + break; + case 5: + newASN1Type = typeStore.Null; + break; + case 6: + newASN1Type = typeStore.ObjectIdentifier; + break; + case 10: + newASN1Type = typeStore.Enumerated; + break; + case 12: + newASN1Type = typeStore.Utf8String; + break; + case 13: + newASN1Type = typeStore.RelativeObjectIdentifier; + break; + case 14: + newASN1Type = typeStore.TIME; + break; + case 15: + returnObject.error = "[UNIVERSAL 15] is reserved by ASN.1 standard"; + return { + offset: -1, + result: returnObject + }; + case 16: + newASN1Type = typeStore.Sequence; + break; + case 17: + newASN1Type = typeStore.Set; + break; + case 18: + newASN1Type = typeStore.NumericString; + break; + case 19: + newASN1Type = typeStore.PrintableString; + break; + case 20: + newASN1Type = typeStore.TeletexString; + break; + case 21: + newASN1Type = typeStore.VideotexString; + break; + case 22: + newASN1Type = typeStore.IA5String; + break; + case 23: + newASN1Type = typeStore.UTCTime; + break; + case 24: + newASN1Type = typeStore.GeneralizedTime; + break; + case 25: + newASN1Type = typeStore.GraphicString; + break; + case 26: + newASN1Type = typeStore.VisibleString; + break; + case 27: + newASN1Type = typeStore.GeneralString; + break; + case 28: + newASN1Type = typeStore.UniversalString; + break; + case 29: + newASN1Type = typeStore.CharacterString; + break; + case 30: + newASN1Type = typeStore.BmpString; + break; + case 31: + newASN1Type = typeStore.DATE; + break; + case 32: + newASN1Type = typeStore.TimeOfDay; + break; + case 33: + newASN1Type = typeStore.DateTime; + break; + case 34: + newASN1Type = typeStore.Duration; + break; + default: { + const newObject = returnObject.idBlock.isConstructed + ? new typeStore.Constructed() + : new typeStore.Primitive(); + newObject.idBlock = returnObject.idBlock; + newObject.lenBlock = returnObject.lenBlock; + newObject.warnings = returnObject.warnings; + returnObject = newObject; + } + } + break; + case 2: + case 3: + case 4: + default: { + newASN1Type = returnObject.idBlock.isConstructed + ? typeStore.Constructed + : typeStore.Primitive; + } + } + returnObject = localChangeType(returnObject, newASN1Type); + resultOffset = returnObject.fromBER(inputBuffer, inputOffset, returnObject.lenBlock.isIndefiniteForm ? inputLength : returnObject.lenBlock.length); + returnObject.valueBeforeDecodeView = inputBuffer.subarray(incomingOffset, incomingOffset + returnObject.blockLength); + return { + offset: resultOffset, + result: returnObject + }; +} +function fromBER(inputBuffer) { + if (!inputBuffer.byteLength) { + const result = new BaseBlock({}, ValueBlock); + result.error = "Input buffer has zero length"; + return { + offset: -1, + result + }; + } + return localFromBER(pvtsutils__namespace.BufferSourceConverter.toUint8Array(inputBuffer).slice(), 0, inputBuffer.byteLength); +} + +function checkLen(indefiniteLength, length) { + if (indefiniteLength) { + return 1; + } + return length; +} +class LocalConstructedValueBlock extends ValueBlock { + constructor({ value = [], isIndefiniteForm = false, ...parameters } = {}) { + super(parameters); + this.value = value; + this.isIndefiniteForm = isIndefiniteForm; + } + fromBER(inputBuffer, inputOffset, inputLength) { + const view = pvtsutils__namespace.BufferSourceConverter.toUint8Array(inputBuffer); + if (!checkBufferParams(this, view, inputOffset, inputLength)) { + return -1; + } + this.valueBeforeDecodeView = view.subarray(inputOffset, inputOffset + inputLength); + if (this.valueBeforeDecodeView.length === 0) { + this.warnings.push("Zero buffer length"); + return inputOffset; + } + let currentOffset = inputOffset; + while (checkLen(this.isIndefiniteForm, inputLength) > 0) { + const returnObject = localFromBER(view, currentOffset, inputLength); + if (returnObject.offset === -1) { + this.error = returnObject.result.error; + this.warnings.concat(returnObject.result.warnings); + return -1; + } + currentOffset = returnObject.offset; + this.blockLength += returnObject.result.blockLength; + inputLength -= returnObject.result.blockLength; + this.value.push(returnObject.result); + if (this.isIndefiniteForm && returnObject.result.constructor.NAME === END_OF_CONTENT_NAME) { + break; + } + } + if (this.isIndefiniteForm) { + if (this.value[this.value.length - 1].constructor.NAME === END_OF_CONTENT_NAME) { + this.value.pop(); + } + else { + this.warnings.push("No EndOfContent block encoded"); + } + } + return currentOffset; + } + toBER(sizeOnly, writer) { + const _writer = writer || new ViewWriter(); + for (let i = 0; i < this.value.length; i++) { + this.value[i].toBER(sizeOnly, _writer); + } + if (!writer) { + return _writer.final(); + } + return EMPTY_BUFFER; + } + toJSON() { + const object = { + ...super.toJSON(), + isIndefiniteForm: this.isIndefiniteForm, + value: [], + }; + for (const value of this.value) { + object.value.push(value.toJSON()); + } + return object; + } +} +LocalConstructedValueBlock.NAME = "ConstructedValueBlock"; + +var _a$v; +class Constructed extends BaseBlock { + constructor(parameters = {}) { + super(parameters, LocalConstructedValueBlock); + this.idBlock.isConstructed = true; + } + fromBER(inputBuffer, inputOffset, inputLength) { + this.valueBlock.isIndefiniteForm = this.lenBlock.isIndefiniteForm; + const resultOffset = this.valueBlock.fromBER(inputBuffer, inputOffset, (this.lenBlock.isIndefiniteForm) ? inputLength : this.lenBlock.length); + if (resultOffset === -1) { + this.error = this.valueBlock.error; + return resultOffset; + } + if (!this.idBlock.error.length) + this.blockLength += this.idBlock.blockLength; + if (!this.lenBlock.error.length) + this.blockLength += this.lenBlock.blockLength; + if (!this.valueBlock.error.length) + this.blockLength += this.valueBlock.blockLength; + return resultOffset; + } + onAsciiEncoding() { + const values = []; + for (const value of this.valueBlock.value) { + values.push(value.toString("ascii").split("\n").map(o => ` ${o}`).join("\n")); + } + const blockName = this.idBlock.tagClass === 3 + ? `[${this.idBlock.tagNumber}]` + : this.constructor.NAME; + return values.length + ? `${blockName} :\n${values.join("\n")}` + : `${blockName} :`; + } +} +_a$v = Constructed; +(() => { + typeStore.Constructed = _a$v; +})(); +Constructed.NAME = "CONSTRUCTED"; + +class LocalEndOfContentValueBlock extends ValueBlock { + fromBER(inputBuffer, inputOffset, inputLength) { + return inputOffset; + } + toBER(sizeOnly) { + return EMPTY_BUFFER; + } +} +LocalEndOfContentValueBlock.override = "EndOfContentValueBlock"; + +var _a$u; +class EndOfContent extends BaseBlock { + constructor(parameters = {}) { + super(parameters, LocalEndOfContentValueBlock); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 0; + } +} +_a$u = EndOfContent; +(() => { + typeStore.EndOfContent = _a$u; +})(); +EndOfContent.NAME = END_OF_CONTENT_NAME; + +var _a$t; +class Null extends BaseBlock { + constructor(parameters = {}) { + super(parameters, ValueBlock); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 5; + } + fromBER(inputBuffer, inputOffset, inputLength) { + if (this.lenBlock.length > 0) + this.warnings.push("Non-zero length of value block for Null type"); + if (!this.idBlock.error.length) + this.blockLength += this.idBlock.blockLength; + if (!this.lenBlock.error.length) + this.blockLength += this.lenBlock.blockLength; + this.blockLength += inputLength; + if ((inputOffset + inputLength) > inputBuffer.byteLength) { + this.error = "End of input reached before message was fully decoded (inconsistent offset and length values)"; + return -1; + } + return (inputOffset + inputLength); + } + toBER(sizeOnly, writer) { + const retBuf = new ArrayBuffer(2); + if (!sizeOnly) { + const retView = new Uint8Array(retBuf); + retView[0] = 0x05; + retView[1] = 0x00; + } + if (writer) { + writer.write(retBuf); + } + return retBuf; + } + onAsciiEncoding() { + return `${this.constructor.NAME}`; + } +} +_a$t = Null; +(() => { + typeStore.Null = _a$t; +})(); +Null.NAME = "NULL"; + +class LocalBooleanValueBlock extends HexBlock(ValueBlock) { + constructor({ value, ...parameters } = {}) { + super(parameters); + if (parameters.valueHex) { + this.valueHexView = pvtsutils__namespace.BufferSourceConverter.toUint8Array(parameters.valueHex); + } + else { + this.valueHexView = new Uint8Array(1); + } + if (value) { + this.value = value; + } + } + get value() { + for (const octet of this.valueHexView) { + if (octet > 0) { + return true; + } + } + return false; + } + set value(value) { + this.valueHexView[0] = value ? 0xFF : 0x00; + } + fromBER(inputBuffer, inputOffset, inputLength) { + const inputView = pvtsutils__namespace.BufferSourceConverter.toUint8Array(inputBuffer); + if (!checkBufferParams(this, inputView, inputOffset, inputLength)) { + return -1; + } + this.valueHexView = inputView.subarray(inputOffset, inputOffset + inputLength); + if (inputLength > 1) + this.warnings.push("Boolean value encoded in more then 1 octet"); + this.isHexOnly = true; + pvutils__namespace.utilDecodeTC.call(this); + this.blockLength = inputLength; + return (inputOffset + inputLength); + } + toBER() { + return this.valueHexView.slice(); + } + toJSON() { + return { + ...super.toJSON(), + value: this.value, + }; + } +} +LocalBooleanValueBlock.NAME = "BooleanValueBlock"; + +var _a$s; +class Boolean extends BaseBlock { + constructor(parameters = {}) { + super(parameters, LocalBooleanValueBlock); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 1; + } + getValue() { + return this.valueBlock.value; + } + setValue(value) { + this.valueBlock.value = value; + } + onAsciiEncoding() { + return `${this.constructor.NAME} : ${this.getValue}`; + } +} +_a$s = Boolean; +(() => { + typeStore.Boolean = _a$s; +})(); +Boolean.NAME = "BOOLEAN"; + +class LocalOctetStringValueBlock extends HexBlock(LocalConstructedValueBlock) { + constructor({ isConstructed = false, ...parameters } = {}) { + super(parameters); + this.isConstructed = isConstructed; + } + fromBER(inputBuffer, inputOffset, inputLength) { + let resultOffset = 0; + if (this.isConstructed) { + this.isHexOnly = false; + resultOffset = LocalConstructedValueBlock.prototype.fromBER.call(this, inputBuffer, inputOffset, inputLength); + if (resultOffset === -1) + return resultOffset; + for (let i = 0; i < this.value.length; i++) { + const currentBlockName = this.value[i].constructor.NAME; + if (currentBlockName === END_OF_CONTENT_NAME) { + if (this.isIndefiniteForm) + break; + else { + this.error = "EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only"; + return -1; + } + } + if (currentBlockName !== OCTET_STRING_NAME) { + this.error = "OCTET STRING may consists of OCTET STRINGs only"; + return -1; + } + } + } + else { + this.isHexOnly = true; + resultOffset = super.fromBER(inputBuffer, inputOffset, inputLength); + this.blockLength = inputLength; + } + return resultOffset; + } + toBER(sizeOnly, writer) { + if (this.isConstructed) + return LocalConstructedValueBlock.prototype.toBER.call(this, sizeOnly, writer); + return sizeOnly + ? new ArrayBuffer(this.valueHexView.byteLength) + : this.valueHexView.slice().buffer; + } + toJSON() { + return { + ...super.toJSON(), + isConstructed: this.isConstructed, + }; + } +} +LocalOctetStringValueBlock.NAME = "OctetStringValueBlock"; + +var _a$r; +class OctetString extends BaseBlock { + constructor({ idBlock = {}, lenBlock = {}, ...parameters } = {}) { + var _b, _c; + (_b = parameters.isConstructed) !== null && _b !== void 0 ? _b : (parameters.isConstructed = !!((_c = parameters.value) === null || _c === void 0 ? void 0 : _c.length)); + super({ + idBlock: { + isConstructed: parameters.isConstructed, + ...idBlock, + }, + lenBlock: { + ...lenBlock, + isIndefiniteForm: !!parameters.isIndefiniteForm, + }, + ...parameters, + }, LocalOctetStringValueBlock); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 4; + } + fromBER(inputBuffer, inputOffset, inputLength) { + this.valueBlock.isConstructed = this.idBlock.isConstructed; + this.valueBlock.isIndefiniteForm = this.lenBlock.isIndefiniteForm; + if (inputLength === 0) { + if (this.idBlock.error.length === 0) + this.blockLength += this.idBlock.blockLength; + if (this.lenBlock.error.length === 0) + this.blockLength += this.lenBlock.blockLength; + return inputOffset; + } + if (!this.valueBlock.isConstructed) { + const view = inputBuffer instanceof ArrayBuffer ? new Uint8Array(inputBuffer) : inputBuffer; + const buf = view.subarray(inputOffset, inputOffset + inputLength); + try { + if (buf.byteLength) { + const asn = localFromBER(buf, 0, buf.byteLength); + if (asn.offset !== -1 && asn.offset === inputLength) { + this.valueBlock.value = [asn.result]; + } + } + } + catch (e) { + } + } + return super.fromBER(inputBuffer, inputOffset, inputLength); + } + onAsciiEncoding() { + if (this.valueBlock.isConstructed || (this.valueBlock.value && this.valueBlock.value.length)) { + return Constructed.prototype.onAsciiEncoding.call(this); + } + return `${this.constructor.NAME} : ${pvtsutils__namespace.Convert.ToHex(this.valueBlock.valueHexView)}`; + } + getValue() { + if (!this.idBlock.isConstructed) { + return this.valueBlock.valueHexView.slice().buffer; + } + const array = []; + for (const content of this.valueBlock.value) { + if (content instanceof OctetString) { + array.push(content.valueBlock.valueHexView); + } + } + return pvtsutils__namespace.BufferSourceConverter.concat(array); + } +} +_a$r = OctetString; +(() => { + typeStore.OctetString = _a$r; +})(); +OctetString.NAME = OCTET_STRING_NAME; + +class LocalBitStringValueBlock extends HexBlock(LocalConstructedValueBlock) { + constructor({ unusedBits = 0, isConstructed = false, ...parameters } = {}) { + super(parameters); + this.unusedBits = unusedBits; + this.isConstructed = isConstructed; + this.blockLength = this.valueHexView.byteLength; + } + fromBER(inputBuffer, inputOffset, inputLength) { + if (!inputLength) { + return inputOffset; + } + let resultOffset = -1; + if (this.isConstructed) { + resultOffset = LocalConstructedValueBlock.prototype.fromBER.call(this, inputBuffer, inputOffset, inputLength); + if (resultOffset === -1) + return resultOffset; + for (const value of this.value) { + const currentBlockName = value.constructor.NAME; + if (currentBlockName === END_OF_CONTENT_NAME) { + if (this.isIndefiniteForm) + break; + else { + this.error = "EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only"; + return -1; + } + } + if (currentBlockName !== BIT_STRING_NAME) { + this.error = "BIT STRING may consists of BIT STRINGs only"; + return -1; + } + const valueBlock = value.valueBlock; + if ((this.unusedBits > 0) && (valueBlock.unusedBits > 0)) { + this.error = "Using of \"unused bits\" inside constructive BIT STRING allowed for least one only"; + return -1; + } + this.unusedBits = valueBlock.unusedBits; + } + return resultOffset; + } + const inputView = pvtsutils__namespace.BufferSourceConverter.toUint8Array(inputBuffer); + if (!checkBufferParams(this, inputView, inputOffset, inputLength)) { + return -1; + } + const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength); + this.unusedBits = intBuffer[0]; + if (this.unusedBits > 7) { + this.error = "Unused bits for BitString must be in range 0-7"; + return -1; + } + if (!this.unusedBits) { + const buf = intBuffer.subarray(1); + try { + if (buf.byteLength) { + const asn = localFromBER(buf, 0, buf.byteLength); + if (asn.offset !== -1 && asn.offset === (inputLength - 1)) { + this.value = [asn.result]; + } + } + } + catch (e) { + } + } + this.valueHexView = intBuffer.subarray(1); + this.blockLength = intBuffer.length; + return (inputOffset + inputLength); + } + toBER(sizeOnly, writer) { + if (this.isConstructed) { + return LocalConstructedValueBlock.prototype.toBER.call(this, sizeOnly, writer); + } + if (sizeOnly) { + return new ArrayBuffer(this.valueHexView.byteLength + 1); + } + if (!this.valueHexView.byteLength) { + return EMPTY_BUFFER; + } + const retView = new Uint8Array(this.valueHexView.length + 1); + retView[0] = this.unusedBits; + retView.set(this.valueHexView, 1); + return retView.buffer; + } + toJSON() { + return { + ...super.toJSON(), + unusedBits: this.unusedBits, + isConstructed: this.isConstructed, + }; + } +} +LocalBitStringValueBlock.NAME = "BitStringValueBlock"; + +var _a$q; +class BitString extends BaseBlock { + constructor({ idBlock = {}, lenBlock = {}, ...parameters } = {}) { + var _b, _c; + (_b = parameters.isConstructed) !== null && _b !== void 0 ? _b : (parameters.isConstructed = !!((_c = parameters.value) === null || _c === void 0 ? void 0 : _c.length)); + super({ + idBlock: { + isConstructed: parameters.isConstructed, + ...idBlock, + }, + lenBlock: { + ...lenBlock, + isIndefiniteForm: !!parameters.isIndefiniteForm, + }, + ...parameters, + }, LocalBitStringValueBlock); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 3; + } + fromBER(inputBuffer, inputOffset, inputLength) { + this.valueBlock.isConstructed = this.idBlock.isConstructed; + this.valueBlock.isIndefiniteForm = this.lenBlock.isIndefiniteForm; + return super.fromBER(inputBuffer, inputOffset, inputLength); + } + onAsciiEncoding() { + if (this.valueBlock.isConstructed || (this.valueBlock.value && this.valueBlock.value.length)) { + return Constructed.prototype.onAsciiEncoding.call(this); + } + else { + const bits = []; + const valueHex = this.valueBlock.valueHexView; + for (const byte of valueHex) { + bits.push(byte.toString(2).padStart(8, "0")); + } + const bitsStr = bits.join(""); + return `${this.constructor.NAME} : ${bitsStr.substring(0, bitsStr.length - this.valueBlock.unusedBits)}`; + } + } +} +_a$q = BitString; +(() => { + typeStore.BitString = _a$q; +})(); +BitString.NAME = BIT_STRING_NAME; + +var _a$p; +function viewAdd(first, second) { + const c = new Uint8Array([0]); + const firstView = new Uint8Array(first); + const secondView = new Uint8Array(second); + let firstViewCopy = firstView.slice(0); + const firstViewCopyLength = firstViewCopy.length - 1; + const secondViewCopy = secondView.slice(0); + const secondViewCopyLength = secondViewCopy.length - 1; + let value = 0; + const max = (secondViewCopyLength < firstViewCopyLength) ? firstViewCopyLength : secondViewCopyLength; + let counter = 0; + for (let i = max; i >= 0; i--, counter++) { + switch (true) { + case (counter < secondViewCopy.length): + value = firstViewCopy[firstViewCopyLength - counter] + secondViewCopy[secondViewCopyLength - counter] + c[0]; + break; + default: + value = firstViewCopy[firstViewCopyLength - counter] + c[0]; + } + c[0] = value / 10; + switch (true) { + case (counter >= firstViewCopy.length): + firstViewCopy = pvutils__namespace.utilConcatView(new Uint8Array([value % 10]), firstViewCopy); + break; + default: + firstViewCopy[firstViewCopyLength - counter] = value % 10; + } + } + if (c[0] > 0) + firstViewCopy = pvutils__namespace.utilConcatView(c, firstViewCopy); + return firstViewCopy; +} +function power2(n) { + if (n >= powers2.length) { + for (let p = powers2.length; p <= n; p++) { + const c = new Uint8Array([0]); + let digits = (powers2[p - 1]).slice(0); + for (let i = (digits.length - 1); i >= 0; i--) { + const newValue = new Uint8Array([(digits[i] << 1) + c[0]]); + c[0] = newValue[0] / 10; + digits[i] = newValue[0] % 10; + } + if (c[0] > 0) + digits = pvutils__namespace.utilConcatView(c, digits); + powers2.push(digits); + } + } + return powers2[n]; +} +function viewSub(first, second) { + let b = 0; + const firstView = new Uint8Array(first); + const secondView = new Uint8Array(second); + const firstViewCopy = firstView.slice(0); + const firstViewCopyLength = firstViewCopy.length - 1; + const secondViewCopy = secondView.slice(0); + const secondViewCopyLength = secondViewCopy.length - 1; + let value; + let counter = 0; + for (let i = secondViewCopyLength; i >= 0; i--, counter++) { + value = firstViewCopy[firstViewCopyLength - counter] - secondViewCopy[secondViewCopyLength - counter] - b; + switch (true) { + case (value < 0): + b = 1; + firstViewCopy[firstViewCopyLength - counter] = value + 10; + break; + default: + b = 0; + firstViewCopy[firstViewCopyLength - counter] = value; + } + } + if (b > 0) { + for (let i = (firstViewCopyLength - secondViewCopyLength + 1); i >= 0; i--, counter++) { + value = firstViewCopy[firstViewCopyLength - counter] - b; + if (value < 0) { + b = 1; + firstViewCopy[firstViewCopyLength - counter] = value + 10; + } + else { + b = 0; + firstViewCopy[firstViewCopyLength - counter] = value; + break; + } + } + } + return firstViewCopy.slice(); +} +class LocalIntegerValueBlock extends HexBlock(ValueBlock) { + constructor({ value, ...parameters } = {}) { + super(parameters); + this._valueDec = 0; + if (parameters.valueHex) { + this.setValueHex(); + } + if (value !== undefined) { + this.valueDec = value; + } + } + setValueHex() { + if (this.valueHexView.length >= 4) { + this.warnings.push("Too big Integer for decoding, hex only"); + this.isHexOnly = true; + this._valueDec = 0; + } + else { + this.isHexOnly = false; + if (this.valueHexView.length > 0) { + this._valueDec = pvutils__namespace.utilDecodeTC.call(this); + } + } + } + set valueDec(v) { + this._valueDec = v; + this.isHexOnly = false; + this.valueHexView = new Uint8Array(pvutils__namespace.utilEncodeTC(v)); + } + get valueDec() { + return this._valueDec; + } + fromDER(inputBuffer, inputOffset, inputLength, expectedLength = 0) { + const offset = this.fromBER(inputBuffer, inputOffset, inputLength); + if (offset === -1) + return offset; + const view = this.valueHexView; + if ((view[0] === 0x00) && ((view[1] & 0x80) !== 0)) { + this.valueHexView = view.subarray(1); + } + else { + if (expectedLength !== 0) { + if (view.length < expectedLength) { + if ((expectedLength - view.length) > 1) + expectedLength = view.length + 1; + this.valueHexView = view.subarray(expectedLength - view.length); + } + } + } + return offset; + } + toDER(sizeOnly = false) { + const view = this.valueHexView; + switch (true) { + case ((view[0] & 0x80) !== 0): + { + const updatedView = new Uint8Array(this.valueHexView.length + 1); + updatedView[0] = 0x00; + updatedView.set(view, 1); + this.valueHexView = updatedView; + } + break; + case ((view[0] === 0x00) && ((view[1] & 0x80) === 0)): + { + this.valueHexView = this.valueHexView.subarray(1); + } + break; + } + return this.toBER(sizeOnly); + } + fromBER(inputBuffer, inputOffset, inputLength) { + const resultOffset = super.fromBER(inputBuffer, inputOffset, inputLength); + if (resultOffset === -1) { + return resultOffset; + } + this.setValueHex(); + return resultOffset; + } + toBER(sizeOnly) { + return sizeOnly + ? new ArrayBuffer(this.valueHexView.length) + : this.valueHexView.slice().buffer; + } + toJSON() { + return { + ...super.toJSON(), + valueDec: this.valueDec, + }; + } + toString() { + const firstBit = (this.valueHexView.length * 8) - 1; + let digits = new Uint8Array((this.valueHexView.length * 8) / 3); + let bitNumber = 0; + let currentByte; + const asn1View = this.valueHexView; + let result = ""; + let flag = false; + for (let byteNumber = (asn1View.byteLength - 1); byteNumber >= 0; byteNumber--) { + currentByte = asn1View[byteNumber]; + for (let i = 0; i < 8; i++) { + if ((currentByte & 1) === 1) { + switch (bitNumber) { + case firstBit: + digits = viewSub(power2(bitNumber), digits); + result = "-"; + break; + default: + digits = viewAdd(digits, power2(bitNumber)); + } + } + bitNumber++; + currentByte >>= 1; + } + } + for (let i = 0; i < digits.length; i++) { + if (digits[i]) + flag = true; + if (flag) + result += digitsString.charAt(digits[i]); + } + if (flag === false) + result += digitsString.charAt(0); + return result; + } +} +_a$p = LocalIntegerValueBlock; +LocalIntegerValueBlock.NAME = "IntegerValueBlock"; +(() => { + Object.defineProperty(_a$p.prototype, "valueHex", { + set: function (v) { + this.valueHexView = new Uint8Array(v); + this.setValueHex(); + }, + get: function () { + return this.valueHexView.slice().buffer; + }, + }); +})(); + +var _a$o; +class Integer extends BaseBlock { + constructor(parameters = {}) { + super(parameters, LocalIntegerValueBlock); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 2; + } + toBigInt() { + assertBigInt(); + return BigInt(this.valueBlock.toString()); + } + static fromBigInt(value) { + assertBigInt(); + const bigIntValue = BigInt(value); + const writer = new ViewWriter(); + const hex = bigIntValue.toString(16).replace(/^-/, ""); + const view = new Uint8Array(pvtsutils__namespace.Convert.FromHex(hex)); + if (bigIntValue < 0) { + const first = new Uint8Array(view.length + (view[0] & 0x80 ? 1 : 0)); + first[0] |= 0x80; + const firstInt = BigInt(`0x${pvtsutils__namespace.Convert.ToHex(first)}`); + const secondInt = firstInt + bigIntValue; + const second = pvtsutils__namespace.BufferSourceConverter.toUint8Array(pvtsutils__namespace.Convert.FromHex(secondInt.toString(16))); + second[0] |= 0x80; + writer.write(second); + } + else { + if (view[0] & 0x80) { + writer.write(new Uint8Array([0])); + } + writer.write(view); + } + const res = new Integer({ + valueHex: writer.final(), + }); + return res; + } + convertToDER() { + const integer = new Integer({ valueHex: this.valueBlock.valueHexView }); + integer.valueBlock.toDER(); + return integer; + } + convertFromDER() { + return new Integer({ + valueHex: this.valueBlock.valueHexView[0] === 0 + ? this.valueBlock.valueHexView.subarray(1) + : this.valueBlock.valueHexView, + }); + } + onAsciiEncoding() { + return `${this.constructor.NAME} : ${this.valueBlock.toString()}`; + } +} +_a$o = Integer; +(() => { + typeStore.Integer = _a$o; +})(); +Integer.NAME = "INTEGER"; + +var _a$n; +class Enumerated extends Integer { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 10; + } +} +_a$n = Enumerated; +(() => { + typeStore.Enumerated = _a$n; +})(); +Enumerated.NAME = "ENUMERATED"; + +class LocalSidValueBlock extends HexBlock(ValueBlock) { + constructor({ valueDec = -1, isFirstSid = false, ...parameters } = {}) { + super(parameters); + this.valueDec = valueDec; + this.isFirstSid = isFirstSid; + } + fromBER(inputBuffer, inputOffset, inputLength) { + if (!inputLength) { + return inputOffset; + } + const inputView = pvtsutils__namespace.BufferSourceConverter.toUint8Array(inputBuffer); + if (!checkBufferParams(this, inputView, inputOffset, inputLength)) { + return -1; + } + const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength); + this.valueHexView = new Uint8Array(inputLength); + for (let i = 0; i < inputLength; i++) { + this.valueHexView[i] = intBuffer[i] & 0x7F; + this.blockLength++; + if ((intBuffer[i] & 0x80) === 0x00) + break; + } + const tempView = new Uint8Array(this.blockLength); + for (let i = 0; i < this.blockLength; i++) { + tempView[i] = this.valueHexView[i]; + } + this.valueHexView = tempView; + if ((intBuffer[this.blockLength - 1] & 0x80) !== 0x00) { + this.error = "End of input reached before message was fully decoded"; + return -1; + } + if (this.valueHexView[0] === 0x00) + this.warnings.push("Needlessly long format of SID encoding"); + if (this.blockLength <= 8) + this.valueDec = pvutils__namespace.utilFromBase(this.valueHexView, 7); + else { + this.isHexOnly = true; + this.warnings.push("Too big SID for decoding, hex only"); + } + return (inputOffset + this.blockLength); + } + set valueBigInt(value) { + assertBigInt(); + let bits = BigInt(value).toString(2); + while (bits.length % 7) { + bits = "0" + bits; + } + const bytes = new Uint8Array(bits.length / 7); + for (let i = 0; i < bytes.length; i++) { + bytes[i] = parseInt(bits.slice(i * 7, i * 7 + 7), 2) + (i + 1 < bytes.length ? 0x80 : 0); + } + this.fromBER(bytes.buffer, 0, bytes.length); + } + toBER(sizeOnly) { + if (this.isHexOnly) { + if (sizeOnly) + return (new ArrayBuffer(this.valueHexView.byteLength)); + const curView = this.valueHexView; + const retView = new Uint8Array(this.blockLength); + for (let i = 0; i < (this.blockLength - 1); i++) + retView[i] = curView[i] | 0x80; + retView[this.blockLength - 1] = curView[this.blockLength - 1]; + return retView.buffer; + } + const encodedBuf = pvutils__namespace.utilToBase(this.valueDec, 7); + if (encodedBuf.byteLength === 0) { + this.error = "Error during encoding SID value"; + return EMPTY_BUFFER; + } + const retView = new Uint8Array(encodedBuf.byteLength); + if (!sizeOnly) { + const encodedView = new Uint8Array(encodedBuf); + const len = encodedBuf.byteLength - 1; + for (let i = 0; i < len; i++) + retView[i] = encodedView[i] | 0x80; + retView[len] = encodedView[len]; + } + return retView; + } + toString() { + let result = ""; + if (this.isHexOnly) + result = pvtsutils__namespace.Convert.ToHex(this.valueHexView); + else { + if (this.isFirstSid) { + let sidValue = this.valueDec; + if (this.valueDec <= 39) + result = "0."; + else { + if (this.valueDec <= 79) { + result = "1."; + sidValue -= 40; + } + else { + result = "2."; + sidValue -= 80; + } + } + result += sidValue.toString(); + } + else + result = this.valueDec.toString(); + } + return result; + } + toJSON() { + return { + ...super.toJSON(), + valueDec: this.valueDec, + isFirstSid: this.isFirstSid, + }; + } +} +LocalSidValueBlock.NAME = "sidBlock"; + +class LocalObjectIdentifierValueBlock extends ValueBlock { + constructor({ value = EMPTY_STRING, ...parameters } = {}) { + super(parameters); + this.value = []; + if (value) { + this.fromString(value); + } + } + fromBER(inputBuffer, inputOffset, inputLength) { + let resultOffset = inputOffset; + while (inputLength > 0) { + const sidBlock = new LocalSidValueBlock(); + resultOffset = sidBlock.fromBER(inputBuffer, resultOffset, inputLength); + if (resultOffset === -1) { + this.blockLength = 0; + this.error = sidBlock.error; + return resultOffset; + } + if (this.value.length === 0) + sidBlock.isFirstSid = true; + this.blockLength += sidBlock.blockLength; + inputLength -= sidBlock.blockLength; + this.value.push(sidBlock); + } + return resultOffset; + } + toBER(sizeOnly) { + const retBuffers = []; + for (let i = 0; i < this.value.length; i++) { + const valueBuf = this.value[i].toBER(sizeOnly); + if (valueBuf.byteLength === 0) { + this.error = this.value[i].error; + return EMPTY_BUFFER; + } + retBuffers.push(valueBuf); + } + return concat(retBuffers); + } + fromString(string) { + this.value = []; + let pos1 = 0; + let pos2 = 0; + let sid = ""; + let flag = false; + do { + pos2 = string.indexOf(".", pos1); + if (pos2 === -1) + sid = string.substring(pos1); + else + sid = string.substring(pos1, pos2); + pos1 = pos2 + 1; + if (flag) { + const sidBlock = this.value[0]; + let plus = 0; + switch (sidBlock.valueDec) { + case 0: + break; + case 1: + plus = 40; + break; + case 2: + plus = 80; + break; + default: + this.value = []; + return; + } + const parsedSID = parseInt(sid, 10); + if (isNaN(parsedSID)) + return; + sidBlock.valueDec = parsedSID + plus; + flag = false; + } + else { + const sidBlock = new LocalSidValueBlock(); + if (sid > Number.MAX_SAFE_INTEGER) { + assertBigInt(); + const sidValue = BigInt(sid); + sidBlock.valueBigInt = sidValue; + } + else { + sidBlock.valueDec = parseInt(sid, 10); + if (isNaN(sidBlock.valueDec)) + return; + } + if (!this.value.length) { + sidBlock.isFirstSid = true; + flag = true; + } + this.value.push(sidBlock); + } + } while (pos2 !== -1); + } + toString() { + let result = ""; + let isHexOnly = false; + for (let i = 0; i < this.value.length; i++) { + isHexOnly = this.value[i].isHexOnly; + let sidStr = this.value[i].toString(); + if (i !== 0) + result = `${result}.`; + if (isHexOnly) { + sidStr = `{${sidStr}}`; + if (this.value[i].isFirstSid) + result = `2.{${sidStr} - 80}`; + else + result += sidStr; + } + else + result += sidStr; + } + return result; + } + toJSON() { + const object = { + ...super.toJSON(), + value: this.toString(), + sidArray: [], + }; + for (let i = 0; i < this.value.length; i++) { + object.sidArray.push(this.value[i].toJSON()); + } + return object; + } +} +LocalObjectIdentifierValueBlock.NAME = "ObjectIdentifierValueBlock"; + +var _a$m; +class ObjectIdentifier extends BaseBlock { + constructor(parameters = {}) { + super(parameters, LocalObjectIdentifierValueBlock); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 6; + } + getValue() { + return this.valueBlock.toString(); + } + setValue(value) { + this.valueBlock.fromString(value); + } + onAsciiEncoding() { + return `${this.constructor.NAME} : ${this.valueBlock.toString() || "empty"}`; + } + toJSON() { + return { + ...super.toJSON(), + value: this.getValue(), + }; + } +} +_a$m = ObjectIdentifier; +(() => { + typeStore.ObjectIdentifier = _a$m; +})(); +ObjectIdentifier.NAME = "OBJECT IDENTIFIER"; + +class LocalRelativeSidValueBlock extends HexBlock(LocalBaseBlock) { + constructor({ valueDec = 0, ...parameters } = {}) { + super(parameters); + this.valueDec = valueDec; + } + fromBER(inputBuffer, inputOffset, inputLength) { + if (inputLength === 0) + return inputOffset; + const inputView = pvtsutils__namespace.BufferSourceConverter.toUint8Array(inputBuffer); + if (!checkBufferParams(this, inputView, inputOffset, inputLength)) + return -1; + const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength); + this.valueHexView = new Uint8Array(inputLength); + for (let i = 0; i < inputLength; i++) { + this.valueHexView[i] = intBuffer[i] & 0x7F; + this.blockLength++; + if ((intBuffer[i] & 0x80) === 0x00) + break; + } + const tempView = new Uint8Array(this.blockLength); + for (let i = 0; i < this.blockLength; i++) + tempView[i] = this.valueHexView[i]; + this.valueHexView = tempView; + if ((intBuffer[this.blockLength - 1] & 0x80) !== 0x00) { + this.error = "End of input reached before message was fully decoded"; + return -1; + } + if (this.valueHexView[0] === 0x00) + this.warnings.push("Needlessly long format of SID encoding"); + if (this.blockLength <= 8) + this.valueDec = pvutils__namespace.utilFromBase(this.valueHexView, 7); + else { + this.isHexOnly = true; + this.warnings.push("Too big SID for decoding, hex only"); + } + return (inputOffset + this.blockLength); + } + toBER(sizeOnly) { + if (this.isHexOnly) { + if (sizeOnly) + return (new ArrayBuffer(this.valueHexView.byteLength)); + const curView = this.valueHexView; + const retView = new Uint8Array(this.blockLength); + for (let i = 0; i < (this.blockLength - 1); i++) + retView[i] = curView[i] | 0x80; + retView[this.blockLength - 1] = curView[this.blockLength - 1]; + return retView.buffer; + } + const encodedBuf = pvutils__namespace.utilToBase(this.valueDec, 7); + if (encodedBuf.byteLength === 0) { + this.error = "Error during encoding SID value"; + return EMPTY_BUFFER; + } + const retView = new Uint8Array(encodedBuf.byteLength); + if (!sizeOnly) { + const encodedView = new Uint8Array(encodedBuf); + const len = encodedBuf.byteLength - 1; + for (let i = 0; i < len; i++) + retView[i] = encodedView[i] | 0x80; + retView[len] = encodedView[len]; + } + return retView.buffer; + } + toString() { + let result = ""; + if (this.isHexOnly) + result = pvtsutils__namespace.Convert.ToHex(this.valueHexView); + else { + result = this.valueDec.toString(); + } + return result; + } + toJSON() { + return { + ...super.toJSON(), + valueDec: this.valueDec, + }; + } +} +LocalRelativeSidValueBlock.NAME = "relativeSidBlock"; + +class LocalRelativeObjectIdentifierValueBlock extends ValueBlock { + constructor({ value = EMPTY_STRING, ...parameters } = {}) { + super(parameters); + this.value = []; + if (value) { + this.fromString(value); + } + } + fromBER(inputBuffer, inputOffset, inputLength) { + let resultOffset = inputOffset; + while (inputLength > 0) { + const sidBlock = new LocalRelativeSidValueBlock(); + resultOffset = sidBlock.fromBER(inputBuffer, resultOffset, inputLength); + if (resultOffset === -1) { + this.blockLength = 0; + this.error = sidBlock.error; + return resultOffset; + } + this.blockLength += sidBlock.blockLength; + inputLength -= sidBlock.blockLength; + this.value.push(sidBlock); + } + return resultOffset; + } + toBER(sizeOnly, writer) { + const retBuffers = []; + for (let i = 0; i < this.value.length; i++) { + const valueBuf = this.value[i].toBER(sizeOnly); + if (valueBuf.byteLength === 0) { + this.error = this.value[i].error; + return EMPTY_BUFFER; + } + retBuffers.push(valueBuf); + } + return concat(retBuffers); + } + fromString(string) { + this.value = []; + let pos1 = 0; + let pos2 = 0; + let sid = ""; + do { + pos2 = string.indexOf(".", pos1); + if (pos2 === -1) + sid = string.substring(pos1); + else + sid = string.substring(pos1, pos2); + pos1 = pos2 + 1; + const sidBlock = new LocalRelativeSidValueBlock(); + sidBlock.valueDec = parseInt(sid, 10); + if (isNaN(sidBlock.valueDec)) + return true; + this.value.push(sidBlock); + } while (pos2 !== -1); + return true; + } + toString() { + let result = ""; + let isHexOnly = false; + for (let i = 0; i < this.value.length; i++) { + isHexOnly = this.value[i].isHexOnly; + let sidStr = this.value[i].toString(); + if (i !== 0) + result = `${result}.`; + if (isHexOnly) { + sidStr = `{${sidStr}}`; + result += sidStr; + } + else + result += sidStr; + } + return result; + } + toJSON() { + const object = { + ...super.toJSON(), + value: this.toString(), + sidArray: [], + }; + for (let i = 0; i < this.value.length; i++) + object.sidArray.push(this.value[i].toJSON()); + return object; + } +} +LocalRelativeObjectIdentifierValueBlock.NAME = "RelativeObjectIdentifierValueBlock"; + +var _a$l; +class RelativeObjectIdentifier extends BaseBlock { + constructor(parameters = {}) { + super(parameters, LocalRelativeObjectIdentifierValueBlock); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 13; + } + getValue() { + return this.valueBlock.toString(); + } + setValue(value) { + this.valueBlock.fromString(value); + } + onAsciiEncoding() { + return `${this.constructor.NAME} : ${this.valueBlock.toString() || "empty"}`; + } + toJSON() { + return { + ...super.toJSON(), + value: this.getValue(), + }; + } +} +_a$l = RelativeObjectIdentifier; +(() => { + typeStore.RelativeObjectIdentifier = _a$l; +})(); +RelativeObjectIdentifier.NAME = "RelativeObjectIdentifier"; + +var _a$k; +class Sequence extends Constructed { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 16; + } +} +_a$k = Sequence; +(() => { + typeStore.Sequence = _a$k; +})(); +Sequence.NAME = "SEQUENCE"; + +var _a$j; +class Set extends Constructed { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 17; + } +} +_a$j = Set; +(() => { + typeStore.Set = _a$j; +})(); +Set.NAME = "SET"; + +class LocalStringValueBlock extends HexBlock(ValueBlock) { + constructor({ ...parameters } = {}) { + super(parameters); + this.isHexOnly = true; + this.value = EMPTY_STRING; + } + toJSON() { + return { + ...super.toJSON(), + value: this.value, + }; + } +} +LocalStringValueBlock.NAME = "StringValueBlock"; + +class LocalSimpleStringValueBlock extends LocalStringValueBlock { +} +LocalSimpleStringValueBlock.NAME = "SimpleStringValueBlock"; + +class LocalSimpleStringBlock extends BaseStringBlock { + constructor({ ...parameters } = {}) { + super(parameters, LocalSimpleStringValueBlock); + } + fromBuffer(inputBuffer) { + this.valueBlock.value = String.fromCharCode.apply(null, pvtsutils__namespace.BufferSourceConverter.toUint8Array(inputBuffer)); + } + fromString(inputString) { + const strLen = inputString.length; + const view = this.valueBlock.valueHexView = new Uint8Array(strLen); + for (let i = 0; i < strLen; i++) + view[i] = inputString.charCodeAt(i); + this.valueBlock.value = inputString; + } +} +LocalSimpleStringBlock.NAME = "SIMPLE STRING"; + +class LocalUtf8StringValueBlock extends LocalSimpleStringBlock { + fromBuffer(inputBuffer) { + this.valueBlock.valueHexView = pvtsutils__namespace.BufferSourceConverter.toUint8Array(inputBuffer); + try { + this.valueBlock.value = pvtsutils__namespace.Convert.ToUtf8String(inputBuffer); + } + catch (ex) { + this.warnings.push(`Error during "decodeURIComponent": ${ex}, using raw string`); + this.valueBlock.value = pvtsutils__namespace.Convert.ToBinary(inputBuffer); + } + } + fromString(inputString) { + this.valueBlock.valueHexView = new Uint8Array(pvtsutils__namespace.Convert.FromUtf8String(inputString)); + this.valueBlock.value = inputString; + } +} +LocalUtf8StringValueBlock.NAME = "Utf8StringValueBlock"; + +var _a$i; +class Utf8String extends LocalUtf8StringValueBlock { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 12; + } +} +_a$i = Utf8String; +(() => { + typeStore.Utf8String = _a$i; +})(); +Utf8String.NAME = "UTF8String"; + +class LocalBmpStringValueBlock extends LocalSimpleStringBlock { + fromBuffer(inputBuffer) { + this.valueBlock.value = pvtsutils__namespace.Convert.ToUtf16String(inputBuffer); + this.valueBlock.valueHexView = pvtsutils__namespace.BufferSourceConverter.toUint8Array(inputBuffer); + } + fromString(inputString) { + this.valueBlock.value = inputString; + this.valueBlock.valueHexView = new Uint8Array(pvtsutils__namespace.Convert.FromUtf16String(inputString)); + } +} +LocalBmpStringValueBlock.NAME = "BmpStringValueBlock"; + +var _a$h; +class BmpString extends LocalBmpStringValueBlock { + constructor({ ...parameters } = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 30; + } +} +_a$h = BmpString; +(() => { + typeStore.BmpString = _a$h; +})(); +BmpString.NAME = "BMPString"; + +class LocalUniversalStringValueBlock extends LocalSimpleStringBlock { + fromBuffer(inputBuffer) { + const copyBuffer = ArrayBuffer.isView(inputBuffer) ? inputBuffer.slice().buffer : inputBuffer.slice(0); + const valueView = new Uint8Array(copyBuffer); + for (let i = 0; i < valueView.length; i += 4) { + valueView[i] = valueView[i + 3]; + valueView[i + 1] = valueView[i + 2]; + valueView[i + 2] = 0x00; + valueView[i + 3] = 0x00; + } + this.valueBlock.value = String.fromCharCode.apply(null, new Uint32Array(copyBuffer)); + } + fromString(inputString) { + const strLength = inputString.length; + const valueHexView = this.valueBlock.valueHexView = new Uint8Array(strLength * 4); + for (let i = 0; i < strLength; i++) { + const codeBuf = pvutils__namespace.utilToBase(inputString.charCodeAt(i), 8); + const codeView = new Uint8Array(codeBuf); + if (codeView.length > 4) + continue; + const dif = 4 - codeView.length; + for (let j = (codeView.length - 1); j >= 0; j--) + valueHexView[i * 4 + j + dif] = codeView[j]; + } + this.valueBlock.value = inputString; + } +} +LocalUniversalStringValueBlock.NAME = "UniversalStringValueBlock"; + +var _a$g; +class UniversalString extends LocalUniversalStringValueBlock { + constructor({ ...parameters } = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 28; + } +} +_a$g = UniversalString; +(() => { + typeStore.UniversalString = _a$g; +})(); +UniversalString.NAME = "UniversalString"; + +var _a$f; +class NumericString extends LocalSimpleStringBlock { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 18; + } +} +_a$f = NumericString; +(() => { + typeStore.NumericString = _a$f; +})(); +NumericString.NAME = "NumericString"; + +var _a$e; +class PrintableString extends LocalSimpleStringBlock { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 19; + } +} +_a$e = PrintableString; +(() => { + typeStore.PrintableString = _a$e; +})(); +PrintableString.NAME = "PrintableString"; + +var _a$d; +class TeletexString extends LocalSimpleStringBlock { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 20; + } +} +_a$d = TeletexString; +(() => { + typeStore.TeletexString = _a$d; +})(); +TeletexString.NAME = "TeletexString"; + +var _a$c; +class VideotexString extends LocalSimpleStringBlock { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 21; + } +} +_a$c = VideotexString; +(() => { + typeStore.VideotexString = _a$c; +})(); +VideotexString.NAME = "VideotexString"; + +var _a$b; +class IA5String extends LocalSimpleStringBlock { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 22; + } +} +_a$b = IA5String; +(() => { + typeStore.IA5String = _a$b; +})(); +IA5String.NAME = "IA5String"; + +var _a$a; +class GraphicString extends LocalSimpleStringBlock { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 25; + } +} +_a$a = GraphicString; +(() => { + typeStore.GraphicString = _a$a; +})(); +GraphicString.NAME = "GraphicString"; + +var _a$9; +class VisibleString extends LocalSimpleStringBlock { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 26; + } +} +_a$9 = VisibleString; +(() => { + typeStore.VisibleString = _a$9; +})(); +VisibleString.NAME = "VisibleString"; + +var _a$8; +class GeneralString extends LocalSimpleStringBlock { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 27; + } +} +_a$8 = GeneralString; +(() => { + typeStore.GeneralString = _a$8; +})(); +GeneralString.NAME = "GeneralString"; + +var _a$7; +class CharacterString extends LocalSimpleStringBlock { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 29; + } +} +_a$7 = CharacterString; +(() => { + typeStore.CharacterString = _a$7; +})(); +CharacterString.NAME = "CharacterString"; + +var _a$6; +class UTCTime extends VisibleString { + constructor({ value, valueDate, ...parameters } = {}) { + super(parameters); + this.year = 0; + this.month = 0; + this.day = 0; + this.hour = 0; + this.minute = 0; + this.second = 0; + if (value) { + this.fromString(value); + this.valueBlock.valueHexView = new Uint8Array(value.length); + for (let i = 0; i < value.length; i++) + this.valueBlock.valueHexView[i] = value.charCodeAt(i); + } + if (valueDate) { + this.fromDate(valueDate); + this.valueBlock.valueHexView = new Uint8Array(this.toBuffer()); + } + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 23; + } + fromBuffer(inputBuffer) { + this.fromString(String.fromCharCode.apply(null, pvtsutils__namespace.BufferSourceConverter.toUint8Array(inputBuffer))); + } + toBuffer() { + const str = this.toString(); + const buffer = new ArrayBuffer(str.length); + const view = new Uint8Array(buffer); + for (let i = 0; i < str.length; i++) + view[i] = str.charCodeAt(i); + return buffer; + } + fromDate(inputDate) { + this.year = inputDate.getUTCFullYear(); + this.month = inputDate.getUTCMonth() + 1; + this.day = inputDate.getUTCDate(); + this.hour = inputDate.getUTCHours(); + this.minute = inputDate.getUTCMinutes(); + this.second = inputDate.getUTCSeconds(); + } + toDate() { + return (new Date(Date.UTC(this.year, this.month - 1, this.day, this.hour, this.minute, this.second))); + } + fromString(inputString) { + const parser = /(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig; + const parserArray = parser.exec(inputString); + if (parserArray === null) { + this.error = "Wrong input string for conversion"; + return; + } + const year = parseInt(parserArray[1], 10); + if (year >= 50) + this.year = 1900 + year; + else + this.year = 2000 + year; + this.month = parseInt(parserArray[2], 10); + this.day = parseInt(parserArray[3], 10); + this.hour = parseInt(parserArray[4], 10); + this.minute = parseInt(parserArray[5], 10); + this.second = parseInt(parserArray[6], 10); + } + toString(encoding = "iso") { + if (encoding === "iso") { + const outputArray = new Array(7); + outputArray[0] = pvutils__namespace.padNumber(((this.year < 2000) ? (this.year - 1900) : (this.year - 2000)), 2); + outputArray[1] = pvutils__namespace.padNumber(this.month, 2); + outputArray[2] = pvutils__namespace.padNumber(this.day, 2); + outputArray[3] = pvutils__namespace.padNumber(this.hour, 2); + outputArray[4] = pvutils__namespace.padNumber(this.minute, 2); + outputArray[5] = pvutils__namespace.padNumber(this.second, 2); + outputArray[6] = "Z"; + return outputArray.join(""); + } + return super.toString(encoding); + } + onAsciiEncoding() { + return `${this.constructor.NAME} : ${this.toDate().toISOString()}`; + } + toJSON() { + return { + ...super.toJSON(), + year: this.year, + month: this.month, + day: this.day, + hour: this.hour, + minute: this.minute, + second: this.second, + }; + } +} +_a$6 = UTCTime; +(() => { + typeStore.UTCTime = _a$6; +})(); +UTCTime.NAME = "UTCTime"; + +var _a$5; +class GeneralizedTime extends UTCTime { + constructor(parameters = {}) { + var _b; + super(parameters); + (_b = this.millisecond) !== null && _b !== void 0 ? _b : (this.millisecond = 0); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 24; + } + fromDate(inputDate) { + super.fromDate(inputDate); + this.millisecond = inputDate.getUTCMilliseconds(); + } + toDate() { + return (new Date(Date.UTC(this.year, this.month - 1, this.day, this.hour, this.minute, this.second, this.millisecond))); + } + fromString(inputString) { + let isUTC = false; + let timeString = ""; + let dateTimeString = ""; + let fractionPart = 0; + let parser; + let hourDifference = 0; + let minuteDifference = 0; + if (inputString[inputString.length - 1] === "Z") { + timeString = inputString.substring(0, inputString.length - 1); + isUTC = true; + } + else { + const number = new Number(inputString[inputString.length - 1]); + if (isNaN(number.valueOf())) + throw new Error("Wrong input string for conversion"); + timeString = inputString; + } + if (isUTC) { + if (timeString.indexOf("+") !== -1) + throw new Error("Wrong input string for conversion"); + if (timeString.indexOf("-") !== -1) + throw new Error("Wrong input string for conversion"); + } + else { + let multiplier = 1; + let differencePosition = timeString.indexOf("+"); + let differenceString = ""; + if (differencePosition === -1) { + differencePosition = timeString.indexOf("-"); + multiplier = -1; + } + if (differencePosition !== -1) { + differenceString = timeString.substring(differencePosition + 1); + timeString = timeString.substring(0, differencePosition); + if ((differenceString.length !== 2) && (differenceString.length !== 4)) + throw new Error("Wrong input string for conversion"); + let number = parseInt(differenceString.substring(0, 2), 10); + if (isNaN(number.valueOf())) + throw new Error("Wrong input string for conversion"); + hourDifference = multiplier * number; + if (differenceString.length === 4) { + number = parseInt(differenceString.substring(2, 4), 10); + if (isNaN(number.valueOf())) + throw new Error("Wrong input string for conversion"); + minuteDifference = multiplier * number; + } + } + } + let fractionPointPosition = timeString.indexOf("."); + if (fractionPointPosition === -1) + fractionPointPosition = timeString.indexOf(","); + if (fractionPointPosition !== -1) { + const fractionPartCheck = new Number(`0${timeString.substring(fractionPointPosition)}`); + if (isNaN(fractionPartCheck.valueOf())) + throw new Error("Wrong input string for conversion"); + fractionPart = fractionPartCheck.valueOf(); + dateTimeString = timeString.substring(0, fractionPointPosition); + } + else + dateTimeString = timeString; + switch (true) { + case (dateTimeString.length === 8): + parser = /(\d{4})(\d{2})(\d{2})/ig; + if (fractionPointPosition !== -1) + throw new Error("Wrong input string for conversion"); + break; + case (dateTimeString.length === 10): + parser = /(\d{4})(\d{2})(\d{2})(\d{2})/ig; + if (fractionPointPosition !== -1) { + let fractionResult = 60 * fractionPart; + this.minute = Math.floor(fractionResult); + fractionResult = 60 * (fractionResult - this.minute); + this.second = Math.floor(fractionResult); + fractionResult = 1000 * (fractionResult - this.second); + this.millisecond = Math.floor(fractionResult); + } + break; + case (dateTimeString.length === 12): + parser = /(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig; + if (fractionPointPosition !== -1) { + let fractionResult = 60 * fractionPart; + this.second = Math.floor(fractionResult); + fractionResult = 1000 * (fractionResult - this.second); + this.millisecond = Math.floor(fractionResult); + } + break; + case (dateTimeString.length === 14): + parser = /(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig; + if (fractionPointPosition !== -1) { + const fractionResult = 1000 * fractionPart; + this.millisecond = Math.floor(fractionResult); + } + break; + default: + throw new Error("Wrong input string for conversion"); + } + const parserArray = parser.exec(dateTimeString); + if (parserArray === null) + throw new Error("Wrong input string for conversion"); + for (let j = 1; j < parserArray.length; j++) { + switch (j) { + case 1: + this.year = parseInt(parserArray[j], 10); + break; + case 2: + this.month = parseInt(parserArray[j], 10); + break; + case 3: + this.day = parseInt(parserArray[j], 10); + break; + case 4: + this.hour = parseInt(parserArray[j], 10) + hourDifference; + break; + case 5: + this.minute = parseInt(parserArray[j], 10) + minuteDifference; + break; + case 6: + this.second = parseInt(parserArray[j], 10); + break; + default: + throw new Error("Wrong input string for conversion"); + } + } + if (isUTC === false) { + const tempDate = new Date(this.year, this.month, this.day, this.hour, this.minute, this.second, this.millisecond); + this.year = tempDate.getUTCFullYear(); + this.month = tempDate.getUTCMonth(); + this.day = tempDate.getUTCDay(); + this.hour = tempDate.getUTCHours(); + this.minute = tempDate.getUTCMinutes(); + this.second = tempDate.getUTCSeconds(); + this.millisecond = tempDate.getUTCMilliseconds(); + } + } + toString(encoding = "iso") { + if (encoding === "iso") { + const outputArray = []; + outputArray.push(pvutils__namespace.padNumber(this.year, 4)); + outputArray.push(pvutils__namespace.padNumber(this.month, 2)); + outputArray.push(pvutils__namespace.padNumber(this.day, 2)); + outputArray.push(pvutils__namespace.padNumber(this.hour, 2)); + outputArray.push(pvutils__namespace.padNumber(this.minute, 2)); + outputArray.push(pvutils__namespace.padNumber(this.second, 2)); + if (this.millisecond !== 0) { + outputArray.push("."); + outputArray.push(pvutils__namespace.padNumber(this.millisecond, 3)); + } + outputArray.push("Z"); + return outputArray.join(""); + } + return super.toString(encoding); + } + toJSON() { + return { + ...super.toJSON(), + millisecond: this.millisecond, + }; + } +} +_a$5 = GeneralizedTime; +(() => { + typeStore.GeneralizedTime = _a$5; +})(); +GeneralizedTime.NAME = "GeneralizedTime"; + +var _a$4; +class DATE extends Utf8String { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 31; + } +} +_a$4 = DATE; +(() => { + typeStore.DATE = _a$4; +})(); +DATE.NAME = "DATE"; + +var _a$3; +class TimeOfDay extends Utf8String { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 32; + } +} +_a$3 = TimeOfDay; +(() => { + typeStore.TimeOfDay = _a$3; +})(); +TimeOfDay.NAME = "TimeOfDay"; + +var _a$2; +class DateTime extends Utf8String { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 33; + } +} +_a$2 = DateTime; +(() => { + typeStore.DateTime = _a$2; +})(); +DateTime.NAME = "DateTime"; + +var _a$1; +class Duration extends Utf8String { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 34; + } +} +_a$1 = Duration; +(() => { + typeStore.Duration = _a$1; +})(); +Duration.NAME = "Duration"; + +var _a; +class TIME extends Utf8String { + constructor(parameters = {}) { + super(parameters); + this.idBlock.tagClass = 1; + this.idBlock.tagNumber = 14; + } +} +_a = TIME; +(() => { + typeStore.TIME = _a; +})(); +TIME.NAME = "TIME"; + +class Any { + constructor({ name = EMPTY_STRING, optional = false, } = {}) { + this.name = name; + this.optional = optional; + } +} + +class Choice extends Any { + constructor({ value = [], ...parameters } = {}) { + super(parameters); + this.value = value; + } +} + +class Repeated extends Any { + constructor({ value = new Any(), local = false, ...parameters } = {}) { + super(parameters); + this.value = value; + this.local = local; + } +} + +class RawData { + constructor({ data = EMPTY_VIEW } = {}) { + this.dataView = pvtsutils__namespace.BufferSourceConverter.toUint8Array(data); + } + get data() { + return this.dataView.slice().buffer; + } + set data(value) { + this.dataView = pvtsutils__namespace.BufferSourceConverter.toUint8Array(value); + } + fromBER(inputBuffer, inputOffset, inputLength) { + const endLength = inputOffset + inputLength; + this.dataView = pvtsutils__namespace.BufferSourceConverter.toUint8Array(inputBuffer).subarray(inputOffset, endLength); + return endLength; + } + toBER(sizeOnly) { + return this.dataView.slice().buffer; + } +} + +function compareSchema(root, inputData, inputSchema) { + if (inputSchema instanceof Choice) { + for (let j = 0; j < inputSchema.value.length; j++) { + const result = compareSchema(root, inputData, inputSchema.value[j]); + if (result.verified) { + return { + verified: true, + result: root + }; + } + } + { + const _result = { + verified: false, + result: { + error: "Wrong values for Choice type" + }, + }; + if (inputSchema.hasOwnProperty(NAME)) + _result.name = inputSchema.name; + return _result; + } + } + if (inputSchema instanceof Any) { + if (inputSchema.hasOwnProperty(NAME)) + root[inputSchema.name] = inputData; + return { + verified: true, + result: root + }; + } + if ((root instanceof Object) === false) { + return { + verified: false, + result: { error: "Wrong root object" } + }; + } + if ((inputData instanceof Object) === false) { + return { + verified: false, + result: { error: "Wrong ASN.1 data" } + }; + } + if ((inputSchema instanceof Object) === false) { + return { + verified: false, + result: { error: "Wrong ASN.1 schema" } + }; + } + if ((ID_BLOCK in inputSchema) === false) { + return { + verified: false, + result: { error: "Wrong ASN.1 schema" } + }; + } + if ((FROM_BER in inputSchema.idBlock) === false) { + return { + verified: false, + result: { error: "Wrong ASN.1 schema" } + }; + } + if ((TO_BER in inputSchema.idBlock) === false) { + return { + verified: false, + result: { error: "Wrong ASN.1 schema" } + }; + } + const encodedId = inputSchema.idBlock.toBER(false); + if (encodedId.byteLength === 0) { + return { + verified: false, + result: { error: "Error encoding idBlock for ASN.1 schema" } + }; + } + const decodedOffset = inputSchema.idBlock.fromBER(encodedId, 0, encodedId.byteLength); + if (decodedOffset === -1) { + return { + verified: false, + result: { error: "Error decoding idBlock for ASN.1 schema" } + }; + } + if (inputSchema.idBlock.hasOwnProperty(TAG_CLASS) === false) { + return { + verified: false, + result: { error: "Wrong ASN.1 schema" } + }; + } + if (inputSchema.idBlock.tagClass !== inputData.idBlock.tagClass) { + return { + verified: false, + result: root + }; + } + if (inputSchema.idBlock.hasOwnProperty(TAG_NUMBER) === false) { + return { + verified: false, + result: { error: "Wrong ASN.1 schema" } + }; + } + if (inputSchema.idBlock.tagNumber !== inputData.idBlock.tagNumber) { + return { + verified: false, + result: root + }; + } + if (inputSchema.idBlock.hasOwnProperty(IS_CONSTRUCTED) === false) { + return { + verified: false, + result: { error: "Wrong ASN.1 schema" } + }; + } + if (inputSchema.idBlock.isConstructed !== inputData.idBlock.isConstructed) { + return { + verified: false, + result: root + }; + } + if (!(IS_HEX_ONLY in inputSchema.idBlock)) { + return { + verified: false, + result: { error: "Wrong ASN.1 schema" } + }; + } + if (inputSchema.idBlock.isHexOnly !== inputData.idBlock.isHexOnly) { + return { + verified: false, + result: root + }; + } + if (inputSchema.idBlock.isHexOnly) { + if ((VALUE_HEX_VIEW in inputSchema.idBlock) === false) { + return { + verified: false, + result: { error: "Wrong ASN.1 schema" } + }; + } + const schemaView = inputSchema.idBlock.valueHexView; + const asn1View = inputData.idBlock.valueHexView; + if (schemaView.length !== asn1View.length) { + return { + verified: false, + result: root + }; + } + for (let i = 0; i < schemaView.length; i++) { + if (schemaView[i] !== asn1View[1]) { + return { + verified: false, + result: root + }; + } + } + } + if (inputSchema.name) { + inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING); + if (inputSchema.name) + root[inputSchema.name] = inputData; + } + if (inputSchema instanceof typeStore.Constructed) { + let admission = 0; + let result = { + verified: false, + result: { + error: "Unknown error", + } + }; + let maxLength = inputSchema.valueBlock.value.length; + if (maxLength > 0) { + if (inputSchema.valueBlock.value[0] instanceof Repeated) { + maxLength = inputData.valueBlock.value.length; + } + } + if (maxLength === 0) { + return { + verified: true, + result: root + }; + } + if ((inputData.valueBlock.value.length === 0) && + (inputSchema.valueBlock.value.length !== 0)) { + let _optional = true; + for (let i = 0; i < inputSchema.valueBlock.value.length; i++) + _optional = _optional && (inputSchema.valueBlock.value[i].optional || false); + if (_optional) { + return { + verified: true, + result: root + }; + } + if (inputSchema.name) { + inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING); + if (inputSchema.name) + delete root[inputSchema.name]; + } + root.error = "Inconsistent object length"; + return { + verified: false, + result: root + }; + } + for (let i = 0; i < maxLength; i++) { + if ((i - admission) >= inputData.valueBlock.value.length) { + if (inputSchema.valueBlock.value[i].optional === false) { + const _result = { + verified: false, + result: root + }; + root.error = "Inconsistent length between ASN.1 data and schema"; + if (inputSchema.name) { + inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING); + if (inputSchema.name) { + delete root[inputSchema.name]; + _result.name = inputSchema.name; + } + } + return _result; + } + } + else { + if (inputSchema.valueBlock.value[0] instanceof Repeated) { + result = compareSchema(root, inputData.valueBlock.value[i], inputSchema.valueBlock.value[0].value); + if (result.verified === false) { + if (inputSchema.valueBlock.value[0].optional) + admission++; + else { + if (inputSchema.name) { + inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING); + if (inputSchema.name) + delete root[inputSchema.name]; + } + return result; + } + } + if ((NAME in inputSchema.valueBlock.value[0]) && (inputSchema.valueBlock.value[0].name.length > 0)) { + let arrayRoot = {}; + if ((LOCAL in inputSchema.valueBlock.value[0]) && (inputSchema.valueBlock.value[0].local)) + arrayRoot = inputData; + else + arrayRoot = root; + if (typeof arrayRoot[inputSchema.valueBlock.value[0].name] === "undefined") + arrayRoot[inputSchema.valueBlock.value[0].name] = []; + arrayRoot[inputSchema.valueBlock.value[0].name].push(inputData.valueBlock.value[i]); + } + } + else { + result = compareSchema(root, inputData.valueBlock.value[i - admission], inputSchema.valueBlock.value[i]); + if (result.verified === false) { + if (inputSchema.valueBlock.value[i].optional) + admission++; + else { + if (inputSchema.name) { + inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING); + if (inputSchema.name) + delete root[inputSchema.name]; + } + return result; + } + } + } + } + } + if (result.verified === false) { + const _result = { + verified: false, + result: root + }; + if (inputSchema.name) { + inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING); + if (inputSchema.name) { + delete root[inputSchema.name]; + _result.name = inputSchema.name; + } + } + return _result; + } + return { + verified: true, + result: root + }; + } + if (inputSchema.primitiveSchema && + (VALUE_HEX_VIEW in inputData.valueBlock)) { + const asn1 = localFromBER(inputData.valueBlock.valueHexView); + if (asn1.offset === -1) { + const _result = { + verified: false, + result: asn1.result + }; + if (inputSchema.name) { + inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING); + if (inputSchema.name) { + delete root[inputSchema.name]; + _result.name = inputSchema.name; + } + } + return _result; + } + return compareSchema(root, asn1.result, inputSchema.primitiveSchema); + } + return { + verified: true, + result: root + }; +} +function verifySchema(inputBuffer, inputSchema) { + if ((inputSchema instanceof Object) === false) { + return { + verified: false, + result: { error: "Wrong ASN.1 schema type" } + }; + } + const asn1 = localFromBER(pvtsutils__namespace.BufferSourceConverter.toUint8Array(inputBuffer)); + if (asn1.offset === -1) { + return { + verified: false, + result: asn1.result + }; + } + return compareSchema(asn1.result, asn1.result, inputSchema); +} + +exports.Any = Any; +exports.BaseBlock = BaseBlock; +exports.BaseStringBlock = BaseStringBlock; +exports.BitString = BitString; +exports.BmpString = BmpString; +exports.Boolean = Boolean; +exports.CharacterString = CharacterString; +exports.Choice = Choice; +exports.Constructed = Constructed; +exports.DATE = DATE; +exports.DateTime = DateTime; +exports.Duration = Duration; +exports.EndOfContent = EndOfContent; +exports.Enumerated = Enumerated; +exports.GeneralString = GeneralString; +exports.GeneralizedTime = GeneralizedTime; +exports.GraphicString = GraphicString; +exports.HexBlock = HexBlock; +exports.IA5String = IA5String; +exports.Integer = Integer; +exports.Null = Null; +exports.NumericString = NumericString; +exports.ObjectIdentifier = ObjectIdentifier; +exports.OctetString = OctetString; +exports.Primitive = Primitive; +exports.PrintableString = PrintableString; +exports.RawData = RawData; +exports.RelativeObjectIdentifier = RelativeObjectIdentifier; +exports.Repeated = Repeated; +exports.Sequence = Sequence; +exports.Set = Set; +exports.TIME = TIME; +exports.TeletexString = TeletexString; +exports.TimeOfDay = TimeOfDay; +exports.UTCTime = UTCTime; +exports.UniversalString = UniversalString; +exports.Utf8String = Utf8String; +exports.ValueBlock = ValueBlock; +exports.VideotexString = VideotexString; +exports.ViewWriter = ViewWriter; +exports.VisibleString = VisibleString; +exports.compareSchema = compareSchema; +exports.fromBER = fromBER; +exports.verifySchema = verifySchema; diff --git a/gun-server/node_modules/asn1js/package.json b/gun-server/node_modules/asn1js/package.json new file mode 100644 index 0000000..d072033 --- /dev/null +++ b/gun-server/node_modules/asn1js/package.json @@ -0,0 +1,77 @@ +{ + "author": { + "email": "yury@strozhevsky.com", + "name": "Yury Strozhevsky" + }, + "contributors": [ + { + "email": "rmh@unmitigatedrisk.com", + "name": "Ryan Hurst" + } + ], + "engines": { + "node": ">=12.0.0" + }, + "devDependencies": { + "@types/mocha": "^9.1.1", + "@types/node": "^17.0.32", + "@typescript-eslint/eslint-plugin": "^5.23.0", + "@typescript-eslint/parser": "^5.23.0", + "asn1-test-suite": "^1.0.2", + "eslint": "^8.15.0", + "eslint-plugin-deprecation": "^1.3.2", + "mocha": "^10.0.0", + "nyc": "^15.1.0", + "rollup": "^2.72.1", + "rollup-plugin-dts": "^4.2.1", + "rollup-plugin-node-resolve": "^5.2.0", + "rollup-plugin-typescript2": "^0.31.2", + "ts-node": "^10.7.0", + "typescript": "^4.6.4" + }, + "repository": { + "type": "git", + "url": "git://github.com/PeculiarVentures/asn1.js.git" + }, + "dependencies": { + "pvtsutils": "^1.3.2", + "pvutils": "^1.1.3", + "tslib": "^2.4.0" + }, + "description": "asn1js is a pure JavaScript library implementing this standard. ASN.1 is the basis of all X.509 related data structures and numerous other protocols used on the web", + "keywords": [ + "asn1", + "parser", + "asn.1", + "ber", + "der", + "sequence", + "set", + "bitstring", + "octetstring", + "utctime", + "utf8string", + "bmpstring", + "universalstring", + "generalizedtime" + ], + "main": "build/index.js", + "module": "build/index.es.js", + "types": "build/index.d.ts", + "name": "asn1js", + "files": [ + "build", + "LICENSE", + "README.md" + ], + "scripts": { + "build": "rollup -c", + "test": "mocha", + "prepublishOnly": "npm run build", + "lint": "eslint . --ext .ts", + "lint:fix": "eslint --fix . --ext .ts", + "coverage": "nyc npm test" + }, + "version": "3.0.5", + "license": "BSD-3-Clause" +} diff --git a/gun-server/node_modules/body-parser/HISTORY.md b/gun-server/node_modules/body-parser/HISTORY.md new file mode 100644 index 0000000..b892491 --- /dev/null +++ b/gun-server/node_modules/body-parser/HISTORY.md @@ -0,0 +1,665 @@ +1.20.2 / 2023-02-21 +=================== + + * Fix strict json error message on Node.js 19+ + * deps: content-type@~1.0.5 + - perf: skip value escaping when unnecessary + * deps: raw-body@2.5.2 + +1.20.1 / 2022-10-06 +=================== + + * deps: qs@6.11.0 + * perf: remove unnecessary object clone + +1.20.0 / 2022-04-02 +=================== + + * Fix error message for json parse whitespace in `strict` + * Fix internal error when inflated body exceeds limit + * Prevent loss of async hooks context + * Prevent hanging when request already read + * deps: depd@2.0.0 + - Replace internal `eval` usage with `Function` constructor + - Use instance methods on `process` to check for listeners + * deps: http-errors@2.0.0 + - deps: depd@2.0.0 + - deps: statuses@2.0.1 + * deps: on-finished@2.4.1 + * deps: qs@6.10.3 + * deps: raw-body@2.5.1 + - deps: http-errors@2.0.0 + +1.19.2 / 2022-02-15 +=================== + + * deps: bytes@3.1.2 + * deps: qs@6.9.7 + * Fix handling of `__proto__` keys + * deps: raw-body@2.4.3 + - deps: bytes@3.1.2 + +1.19.1 / 2021-12-10 +=================== + + * deps: bytes@3.1.1 + * deps: http-errors@1.8.1 + - deps: inherits@2.0.4 + - deps: toidentifier@1.0.1 + - deps: setprototypeof@1.2.0 + * deps: qs@6.9.6 + * deps: raw-body@2.4.2 + - deps: bytes@3.1.1 + - deps: http-errors@1.8.1 + * deps: safe-buffer@5.2.1 + * deps: type-is@~1.6.18 + +1.19.0 / 2019-04-25 +=================== + + * deps: bytes@3.1.0 + - Add petabyte (`pb`) support + * deps: http-errors@1.7.2 + - Set constructor name when possible + - deps: setprototypeof@1.1.1 + - deps: statuses@'>= 1.5.0 < 2' + * deps: iconv-lite@0.4.24 + - Added encoding MIK + * deps: qs@6.7.0 + - Fix parsing array brackets after index + * deps: raw-body@2.4.0 + - deps: bytes@3.1.0 + - deps: http-errors@1.7.2 + - deps: iconv-lite@0.4.24 + * deps: type-is@~1.6.17 + - deps: mime-types@~2.1.24 + - perf: prevent internal `throw` on invalid type + +1.18.3 / 2018-05-14 +=================== + + * Fix stack trace for strict json parse error + * deps: depd@~1.1.2 + - perf: remove argument reassignment + * deps: http-errors@~1.6.3 + - deps: depd@~1.1.2 + - deps: setprototypeof@1.1.0 + - deps: statuses@'>= 1.3.1 < 2' + * deps: iconv-lite@0.4.23 + - Fix loading encoding with year appended + - Fix deprecation warnings on Node.js 10+ + * deps: qs@6.5.2 + * deps: raw-body@2.3.3 + - deps: http-errors@1.6.3 + - deps: iconv-lite@0.4.23 + * deps: type-is@~1.6.16 + - deps: mime-types@~2.1.18 + +1.18.2 / 2017-09-22 +=================== + + * deps: debug@2.6.9 + * perf: remove argument reassignment + +1.18.1 / 2017-09-12 +=================== + + * deps: content-type@~1.0.4 + - perf: remove argument reassignment + - perf: skip parameter parsing when no parameters + * deps: iconv-lite@0.4.19 + - Fix ISO-8859-1 regression + - Update Windows-1255 + * deps: qs@6.5.1 + - Fix parsing & compacting very deep objects + * deps: raw-body@2.3.2 + - deps: iconv-lite@0.4.19 + +1.18.0 / 2017-09-08 +=================== + + * Fix JSON strict violation error to match native parse error + * Include the `body` property on verify errors + * Include the `type` property on all generated errors + * Use `http-errors` to set status code on errors + * deps: bytes@3.0.0 + * deps: debug@2.6.8 + * deps: depd@~1.1.1 + - Remove unnecessary `Buffer` loading + * deps: http-errors@~1.6.2 + - deps: depd@1.1.1 + * deps: iconv-lite@0.4.18 + - Add support for React Native + - Add a warning if not loaded as utf-8 + - Fix CESU-8 decoding in Node.js 8 + - Improve speed of ISO-8859-1 encoding + * deps: qs@6.5.0 + * deps: raw-body@2.3.1 + - Use `http-errors` for standard emitted errors + - deps: bytes@3.0.0 + - deps: iconv-lite@0.4.18 + - perf: skip buffer decoding on overage chunk + * perf: prevent internal `throw` when missing charset + +1.17.2 / 2017-05-17 +=================== + + * deps: debug@2.6.7 + - Fix `DEBUG_MAX_ARRAY_LENGTH` + - deps: ms@2.0.0 + * deps: type-is@~1.6.15 + - deps: mime-types@~2.1.15 + +1.17.1 / 2017-03-06 +=================== + + * deps: qs@6.4.0 + - Fix regression parsing keys starting with `[` + +1.17.0 / 2017-03-01 +=================== + + * deps: http-errors@~1.6.1 + - Make `message` property enumerable for `HttpError`s + - deps: setprototypeof@1.0.3 + * deps: qs@6.3.1 + - Fix compacting nested arrays + +1.16.1 / 2017-02-10 +=================== + + * deps: debug@2.6.1 + - Fix deprecation messages in WebStorm and other editors + - Undeprecate `DEBUG_FD` set to `1` or `2` + +1.16.0 / 2017-01-17 +=================== + + * deps: debug@2.6.0 + - Allow colors in workers + - Deprecated `DEBUG_FD` environment variable + - Fix error when running under React Native + - Use same color for same namespace + - deps: ms@0.7.2 + * deps: http-errors@~1.5.1 + - deps: inherits@2.0.3 + - deps: setprototypeof@1.0.2 + - deps: statuses@'>= 1.3.1 < 2' + * deps: iconv-lite@0.4.15 + - Added encoding MS-31J + - Added encoding MS-932 + - Added encoding MS-936 + - Added encoding MS-949 + - Added encoding MS-950 + - Fix GBK/GB18030 handling of Euro character + * deps: qs@6.2.1 + - Fix array parsing from skipping empty values + * deps: raw-body@~2.2.0 + - deps: iconv-lite@0.4.15 + * deps: type-is@~1.6.14 + - deps: mime-types@~2.1.13 + +1.15.2 / 2016-06-19 +=================== + + * deps: bytes@2.4.0 + * deps: content-type@~1.0.2 + - perf: enable strict mode + * deps: http-errors@~1.5.0 + - Use `setprototypeof` module to replace `__proto__` setting + - deps: statuses@'>= 1.3.0 < 2' + - perf: enable strict mode + * deps: qs@6.2.0 + * deps: raw-body@~2.1.7 + - deps: bytes@2.4.0 + - perf: remove double-cleanup on happy path + * deps: type-is@~1.6.13 + - deps: mime-types@~2.1.11 + +1.15.1 / 2016-05-05 +=================== + + * deps: bytes@2.3.0 + - Drop partial bytes on all parsed units + - Fix parsing byte string that looks like hex + * deps: raw-body@~2.1.6 + - deps: bytes@2.3.0 + * deps: type-is@~1.6.12 + - deps: mime-types@~2.1.10 + +1.15.0 / 2016-02-10 +=================== + + * deps: http-errors@~1.4.0 + - Add `HttpError` export, for `err instanceof createError.HttpError` + - deps: inherits@2.0.1 + - deps: statuses@'>= 1.2.1 < 2' + * deps: qs@6.1.0 + * deps: type-is@~1.6.11 + - deps: mime-types@~2.1.9 + +1.14.2 / 2015-12-16 +=================== + + * deps: bytes@2.2.0 + * deps: iconv-lite@0.4.13 + * deps: qs@5.2.0 + * deps: raw-body@~2.1.5 + - deps: bytes@2.2.0 + - deps: iconv-lite@0.4.13 + * deps: type-is@~1.6.10 + - deps: mime-types@~2.1.8 + +1.14.1 / 2015-09-27 +=================== + + * Fix issue where invalid charset results in 400 when `verify` used + * deps: iconv-lite@0.4.12 + - Fix CESU-8 decoding in Node.js 4.x + * deps: raw-body@~2.1.4 + - Fix masking critical errors from `iconv-lite` + - deps: iconv-lite@0.4.12 + * deps: type-is@~1.6.9 + - deps: mime-types@~2.1.7 + +1.14.0 / 2015-09-16 +=================== + + * Fix JSON strict parse error to match syntax errors + * Provide static `require` analysis in `urlencoded` parser + * deps: depd@~1.1.0 + - Support web browser loading + * deps: qs@5.1.0 + * deps: raw-body@~2.1.3 + - Fix sync callback when attaching data listener causes sync read + * deps: type-is@~1.6.8 + - Fix type error when given invalid type to match against + - deps: mime-types@~2.1.6 + +1.13.3 / 2015-07-31 +=================== + + * deps: type-is@~1.6.6 + - deps: mime-types@~2.1.4 + +1.13.2 / 2015-07-05 +=================== + + * deps: iconv-lite@0.4.11 + * deps: qs@4.0.0 + - Fix dropping parameters like `hasOwnProperty` + - Fix user-visible incompatibilities from 3.1.0 + - Fix various parsing edge cases + * deps: raw-body@~2.1.2 + - Fix error stack traces to skip `makeError` + - deps: iconv-lite@0.4.11 + * deps: type-is@~1.6.4 + - deps: mime-types@~2.1.2 + - perf: enable strict mode + - perf: remove argument reassignment + +1.13.1 / 2015-06-16 +=================== + + * deps: qs@2.4.2 + - Downgraded from 3.1.0 because of user-visible incompatibilities + +1.13.0 / 2015-06-14 +=================== + + * Add `statusCode` property on `Error`s, in addition to `status` + * Change `type` default to `application/json` for JSON parser + * Change `type` default to `application/x-www-form-urlencoded` for urlencoded parser + * Provide static `require` analysis + * Use the `http-errors` module to generate errors + * deps: bytes@2.1.0 + - Slight optimizations + * deps: iconv-lite@0.4.10 + - The encoding UTF-16 without BOM now defaults to UTF-16LE when detection fails + - Leading BOM is now removed when decoding + * deps: on-finished@~2.3.0 + - Add defined behavior for HTTP `CONNECT` requests + - Add defined behavior for HTTP `Upgrade` requests + - deps: ee-first@1.1.1 + * deps: qs@3.1.0 + - Fix dropping parameters like `hasOwnProperty` + - Fix various parsing edge cases + - Parsed object now has `null` prototype + * deps: raw-body@~2.1.1 + - Use `unpipe` module for unpiping requests + - deps: iconv-lite@0.4.10 + * deps: type-is@~1.6.3 + - deps: mime-types@~2.1.1 + - perf: reduce try block size + - perf: remove bitwise operations + * perf: enable strict mode + * perf: remove argument reassignment + * perf: remove delete call + +1.12.4 / 2015-05-10 +=================== + + * deps: debug@~2.2.0 + * deps: qs@2.4.2 + - Fix allowing parameters like `constructor` + * deps: on-finished@~2.2.1 + * deps: raw-body@~2.0.1 + - Fix a false-positive when unpiping in Node.js 0.8 + - deps: bytes@2.0.1 + * deps: type-is@~1.6.2 + - deps: mime-types@~2.0.11 + +1.12.3 / 2015-04-15 +=================== + + * Slight efficiency improvement when not debugging + * deps: depd@~1.0.1 + * deps: iconv-lite@0.4.8 + - Add encoding alias UNICODE-1-1-UTF-7 + * deps: raw-body@1.3.4 + - Fix hanging callback if request aborts during read + - deps: iconv-lite@0.4.8 + +1.12.2 / 2015-03-16 +=================== + + * deps: qs@2.4.1 + - Fix error when parameter `hasOwnProperty` is present + +1.12.1 / 2015-03-15 +=================== + + * deps: debug@~2.1.3 + - Fix high intensity foreground color for bold + - deps: ms@0.7.0 + * deps: type-is@~1.6.1 + - deps: mime-types@~2.0.10 + +1.12.0 / 2015-02-13 +=================== + + * add `debug` messages + * accept a function for the `type` option + * use `content-type` to parse `Content-Type` headers + * deps: iconv-lite@0.4.7 + - Gracefully support enumerables on `Object.prototype` + * deps: raw-body@1.3.3 + - deps: iconv-lite@0.4.7 + * deps: type-is@~1.6.0 + - fix argument reassignment + - fix false-positives in `hasBody` `Transfer-Encoding` check + - support wildcard for both type and subtype (`*/*`) + - deps: mime-types@~2.0.9 + +1.11.0 / 2015-01-30 +=================== + + * make internal `extended: true` depth limit infinity + * deps: type-is@~1.5.6 + - deps: mime-types@~2.0.8 + +1.10.2 / 2015-01-20 +=================== + + * deps: iconv-lite@0.4.6 + - Fix rare aliases of single-byte encodings + * deps: raw-body@1.3.2 + - deps: iconv-lite@0.4.6 + +1.10.1 / 2015-01-01 +=================== + + * deps: on-finished@~2.2.0 + * deps: type-is@~1.5.5 + - deps: mime-types@~2.0.7 + +1.10.0 / 2014-12-02 +=================== + + * make internal `extended: true` array limit dynamic + +1.9.3 / 2014-11-21 +================== + + * deps: iconv-lite@0.4.5 + - Fix Windows-31J and X-SJIS encoding support + * deps: qs@2.3.3 + - Fix `arrayLimit` behavior + * deps: raw-body@1.3.1 + - deps: iconv-lite@0.4.5 + * deps: type-is@~1.5.3 + - deps: mime-types@~2.0.3 + +1.9.2 / 2014-10-27 +================== + + * deps: qs@2.3.2 + - Fix parsing of mixed objects and values + +1.9.1 / 2014-10-22 +================== + + * deps: on-finished@~2.1.1 + - Fix handling of pipelined requests + * deps: qs@2.3.0 + - Fix parsing of mixed implicit and explicit arrays + * deps: type-is@~1.5.2 + - deps: mime-types@~2.0.2 + +1.9.0 / 2014-09-24 +================== + + * include the charset in "unsupported charset" error message + * include the encoding in "unsupported content encoding" error message + * deps: depd@~1.0.0 + +1.8.4 / 2014-09-23 +================== + + * fix content encoding to be case-insensitive + +1.8.3 / 2014-09-19 +================== + + * deps: qs@2.2.4 + - Fix issue with object keys starting with numbers truncated + +1.8.2 / 2014-09-15 +================== + + * deps: depd@0.4.5 + +1.8.1 / 2014-09-07 +================== + + * deps: media-typer@0.3.0 + * deps: type-is@~1.5.1 + +1.8.0 / 2014-09-05 +================== + + * make empty-body-handling consistent between chunked requests + - empty `json` produces `{}` + - empty `raw` produces `new Buffer(0)` + - empty `text` produces `''` + - empty `urlencoded` produces `{}` + * deps: qs@2.2.3 + - Fix issue where first empty value in array is discarded + * deps: type-is@~1.5.0 + - fix `hasbody` to be true for `content-length: 0` + +1.7.0 / 2014-09-01 +================== + + * add `parameterLimit` option to `urlencoded` parser + * change `urlencoded` extended array limit to 100 + * respond with 413 when over `parameterLimit` in `urlencoded` + +1.6.7 / 2014-08-29 +================== + + * deps: qs@2.2.2 + - Remove unnecessary cloning + +1.6.6 / 2014-08-27 +================== + + * deps: qs@2.2.0 + - Array parsing fix + - Performance improvements + +1.6.5 / 2014-08-16 +================== + + * deps: on-finished@2.1.0 + +1.6.4 / 2014-08-14 +================== + + * deps: qs@1.2.2 + +1.6.3 / 2014-08-10 +================== + + * deps: qs@1.2.1 + +1.6.2 / 2014-08-07 +================== + + * deps: qs@1.2.0 + - Fix parsing array of objects + +1.6.1 / 2014-08-06 +================== + + * deps: qs@1.1.0 + - Accept urlencoded square brackets + - Accept empty values in implicit array notation + +1.6.0 / 2014-08-05 +================== + + * deps: qs@1.0.2 + - Complete rewrite + - Limits array length to 20 + - Limits object depth to 5 + - Limits parameters to 1,000 + +1.5.2 / 2014-07-27 +================== + + * deps: depd@0.4.4 + - Work-around v8 generating empty stack traces + +1.5.1 / 2014-07-26 +================== + + * deps: depd@0.4.3 + - Fix exception when global `Error.stackTraceLimit` is too low + +1.5.0 / 2014-07-20 +================== + + * deps: depd@0.4.2 + - Add `TRACE_DEPRECATION` environment variable + - Remove non-standard grey color from color output + - Support `--no-deprecation` argument + - Support `--trace-deprecation` argument + * deps: iconv-lite@0.4.4 + - Added encoding UTF-7 + * deps: raw-body@1.3.0 + - deps: iconv-lite@0.4.4 + - Added encoding UTF-7 + - Fix `Cannot switch to old mode now` error on Node.js 0.10+ + * deps: type-is@~1.3.2 + +1.4.3 / 2014-06-19 +================== + + * deps: type-is@1.3.1 + - fix global variable leak + +1.4.2 / 2014-06-19 +================== + + * deps: type-is@1.3.0 + - improve type parsing + +1.4.1 / 2014-06-19 +================== + + * fix urlencoded extended deprecation message + +1.4.0 / 2014-06-19 +================== + + * add `text` parser + * add `raw` parser + * check accepted charset in content-type (accepts utf-8) + * check accepted encoding in content-encoding (accepts identity) + * deprecate `bodyParser()` middleware; use `.json()` and `.urlencoded()` as needed + * deprecate `urlencoded()` without provided `extended` option + * lazy-load urlencoded parsers + * parsers split into files for reduced mem usage + * support gzip and deflate bodies + - set `inflate: false` to turn off + * deps: raw-body@1.2.2 + - Support all encodings from `iconv-lite` + +1.3.1 / 2014-06-11 +================== + + * deps: type-is@1.2.1 + - Switch dependency from mime to mime-types@1.0.0 + +1.3.0 / 2014-05-31 +================== + + * add `extended` option to urlencoded parser + +1.2.2 / 2014-05-27 +================== + + * deps: raw-body@1.1.6 + - assert stream encoding on node.js 0.8 + - assert stream encoding on node.js < 0.10.6 + - deps: bytes@1 + +1.2.1 / 2014-05-26 +================== + + * invoke `next(err)` after request fully read + - prevents hung responses and socket hang ups + +1.2.0 / 2014-05-11 +================== + + * add `verify` option + * deps: type-is@1.2.0 + - support suffix matching + +1.1.2 / 2014-05-11 +================== + + * improve json parser speed + +1.1.1 / 2014-05-11 +================== + + * fix repeated limit parsing with every request + +1.1.0 / 2014-05-10 +================== + + * add `type` option + * deps: pin for safety and consistency + +1.0.2 / 2014-04-14 +================== + + * use `type-is` module + +1.0.1 / 2014-03-20 +================== + + * lower default limits to 100kb diff --git a/gun-server/node_modules/body-parser/LICENSE b/gun-server/node_modules/body-parser/LICENSE new file mode 100644 index 0000000..386b7b6 --- /dev/null +++ b/gun-server/node_modules/body-parser/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2014-2015 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/gun-server/node_modules/body-parser/README.md b/gun-server/node_modules/body-parser/README.md new file mode 100644 index 0000000..38553bf --- /dev/null +++ b/gun-server/node_modules/body-parser/README.md @@ -0,0 +1,465 @@ +# body-parser + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Build Status][ci-image]][ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Node.js body parsing middleware. + +Parse incoming request bodies in a middleware before your handlers, available +under the `req.body` property. + +**Note** As `req.body`'s shape is based on user-controlled input, all +properties and values in this object are untrusted and should be validated +before trusting. For example, `req.body.foo.toString()` may fail in multiple +ways, for example the `foo` property may not be there or may not be a string, +and `toString` may not be a function and instead a string or other user input. + +[Learn about the anatomy of an HTTP transaction in Node.js](https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/). + +_This does not handle multipart bodies_, due to their complex and typically +large nature. For multipart bodies, you may be interested in the following +modules: + + * [busboy](https://www.npmjs.org/package/busboy#readme) and + [connect-busboy](https://www.npmjs.org/package/connect-busboy#readme) + * [multiparty](https://www.npmjs.org/package/multiparty#readme) and + [connect-multiparty](https://www.npmjs.org/package/connect-multiparty#readme) + * [formidable](https://www.npmjs.org/package/formidable#readme) + * [multer](https://www.npmjs.org/package/multer#readme) + +This module provides the following parsers: + + * [JSON body parser](#bodyparserjsonoptions) + * [Raw body parser](#bodyparserrawoptions) + * [Text body parser](#bodyparsertextoptions) + * [URL-encoded form body parser](#bodyparserurlencodedoptions) + +Other body parsers you might be interested in: + +- [body](https://www.npmjs.org/package/body#readme) +- [co-body](https://www.npmjs.org/package/co-body#readme) + +## Installation + +```sh +$ npm install body-parser +``` + +## API + +```js +var bodyParser = require('body-parser') +``` + +The `bodyParser` object exposes various factories to create middlewares. All +middlewares will populate the `req.body` property with the parsed body when +the `Content-Type` request header matches the `type` option, or an empty +object (`{}`) if there was no body to parse, the `Content-Type` was not matched, +or an error occurred. + +The various errors returned by this module are described in the +[errors section](#errors). + +### bodyParser.json([options]) + +Returns middleware that only parses `json` and only looks at requests where +the `Content-Type` header matches the `type` option. This parser accepts any +Unicode encoding of the body and supports automatic inflation of `gzip` and +`deflate` encodings. + +A new `body` object containing the parsed data is populated on the `request` +object after the middleware (i.e. `req.body`). + +#### Options + +The `json` function takes an optional `options` object that may contain any of +the following keys: + +##### inflate + +When set to `true`, then deflated (compressed) bodies will be inflated; when +`false`, deflated bodies are rejected. Defaults to `true`. + +##### limit + +Controls the maximum request body size. If this is a number, then the value +specifies the number of bytes; if it is a string, the value is passed to the +[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults +to `'100kb'`. + +##### reviver + +The `reviver` option is passed directly to `JSON.parse` as the second +argument. You can find more information on this argument +[in the MDN documentation about JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Example.3A_Using_the_reviver_parameter). + +##### strict + +When set to `true`, will only accept arrays and objects; when `false` will +accept anything `JSON.parse` accepts. Defaults to `true`. + +##### type + +The `type` option is used to determine what media type the middleware will +parse. This option can be a string, array of strings, or a function. If not a +function, `type` option is passed directly to the +[type-is](https://www.npmjs.org/package/type-is#readme) library and this can +be an extension name (like `json`), a mime type (like `application/json`), or +a mime type with a wildcard (like `*/*` or `*/json`). If a function, the `type` +option is called as `fn(req)` and the request is parsed if it returns a truthy +value. Defaults to `application/json`. + +##### verify + +The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, +where `buf` is a `Buffer` of the raw request body and `encoding` is the +encoding of the request. The parsing can be aborted by throwing an error. + +### bodyParser.raw([options]) + +Returns middleware that parses all bodies as a `Buffer` and only looks at +requests where the `Content-Type` header matches the `type` option. This +parser supports automatic inflation of `gzip` and `deflate` encodings. + +A new `body` object containing the parsed data is populated on the `request` +object after the middleware (i.e. `req.body`). This will be a `Buffer` object +of the body. + +#### Options + +The `raw` function takes an optional `options` object that may contain any of +the following keys: + +##### inflate + +When set to `true`, then deflated (compressed) bodies will be inflated; when +`false`, deflated bodies are rejected. Defaults to `true`. + +##### limit + +Controls the maximum request body size. If this is a number, then the value +specifies the number of bytes; if it is a string, the value is passed to the +[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults +to `'100kb'`. + +##### type + +The `type` option is used to determine what media type the middleware will +parse. This option can be a string, array of strings, or a function. +If not a function, `type` option is passed directly to the +[type-is](https://www.npmjs.org/package/type-is#readme) library and this +can be an extension name (like `bin`), a mime type (like +`application/octet-stream`), or a mime type with a wildcard (like `*/*` or +`application/*`). If a function, the `type` option is called as `fn(req)` +and the request is parsed if it returns a truthy value. Defaults to +`application/octet-stream`. + +##### verify + +The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, +where `buf` is a `Buffer` of the raw request body and `encoding` is the +encoding of the request. The parsing can be aborted by throwing an error. + +### bodyParser.text([options]) + +Returns middleware that parses all bodies as a string and only looks at +requests where the `Content-Type` header matches the `type` option. This +parser supports automatic inflation of `gzip` and `deflate` encodings. + +A new `body` string containing the parsed data is populated on the `request` +object after the middleware (i.e. `req.body`). This will be a string of the +body. + +#### Options + +The `text` function takes an optional `options` object that may contain any of +the following keys: + +##### defaultCharset + +Specify the default character set for the text content if the charset is not +specified in the `Content-Type` header of the request. Defaults to `utf-8`. + +##### inflate + +When set to `true`, then deflated (compressed) bodies will be inflated; when +`false`, deflated bodies are rejected. Defaults to `true`. + +##### limit + +Controls the maximum request body size. If this is a number, then the value +specifies the number of bytes; if it is a string, the value is passed to the +[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults +to `'100kb'`. + +##### type + +The `type` option is used to determine what media type the middleware will +parse. This option can be a string, array of strings, or a function. If not +a function, `type` option is passed directly to the +[type-is](https://www.npmjs.org/package/type-is#readme) library and this can +be an extension name (like `txt`), a mime type (like `text/plain`), or a mime +type with a wildcard (like `*/*` or `text/*`). If a function, the `type` +option is called as `fn(req)` and the request is parsed if it returns a +truthy value. Defaults to `text/plain`. + +##### verify + +The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, +where `buf` is a `Buffer` of the raw request body and `encoding` is the +encoding of the request. The parsing can be aborted by throwing an error. + +### bodyParser.urlencoded([options]) + +Returns middleware that only parses `urlencoded` bodies and only looks at +requests where the `Content-Type` header matches the `type` option. This +parser accepts only UTF-8 encoding of the body and supports automatic +inflation of `gzip` and `deflate` encodings. + +A new `body` object containing the parsed data is populated on the `request` +object after the middleware (i.e. `req.body`). This object will contain +key-value pairs, where the value can be a string or array (when `extended` is +`false`), or any type (when `extended` is `true`). + +#### Options + +The `urlencoded` function takes an optional `options` object that may contain +any of the following keys: + +##### extended + +The `extended` option allows to choose between parsing the URL-encoded data +with the `querystring` library (when `false`) or the `qs` library (when +`true`). The "extended" syntax allows for rich objects and arrays to be +encoded into the URL-encoded format, allowing for a JSON-like experience +with URL-encoded. For more information, please +[see the qs library](https://www.npmjs.org/package/qs#readme). + +Defaults to `true`, but using the default has been deprecated. Please +research into the difference between `qs` and `querystring` and choose the +appropriate setting. + +##### inflate + +When set to `true`, then deflated (compressed) bodies will be inflated; when +`false`, deflated bodies are rejected. Defaults to `true`. + +##### limit + +Controls the maximum request body size. If this is a number, then the value +specifies the number of bytes; if it is a string, the value is passed to the +[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults +to `'100kb'`. + +##### parameterLimit + +The `parameterLimit` option controls the maximum number of parameters that +are allowed in the URL-encoded data. If a request contains more parameters +than this value, a 413 will be returned to the client. Defaults to `1000`. + +##### type + +The `type` option is used to determine what media type the middleware will +parse. This option can be a string, array of strings, or a function. If not +a function, `type` option is passed directly to the +[type-is](https://www.npmjs.org/package/type-is#readme) library and this can +be an extension name (like `urlencoded`), a mime type (like +`application/x-www-form-urlencoded`), or a mime type with a wildcard (like +`*/x-www-form-urlencoded`). If a function, the `type` option is called as +`fn(req)` and the request is parsed if it returns a truthy value. Defaults +to `application/x-www-form-urlencoded`. + +##### verify + +The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, +where `buf` is a `Buffer` of the raw request body and `encoding` is the +encoding of the request. The parsing can be aborted by throwing an error. + +## Errors + +The middlewares provided by this module create errors using the +[`http-errors` module](https://www.npmjs.com/package/http-errors). The errors +will typically have a `status`/`statusCode` property that contains the suggested +HTTP response code, an `expose` property to determine if the `message` property +should be displayed to the client, a `type` property to determine the type of +error without matching against the `message`, and a `body` property containing +the read body, if available. + +The following are the common errors created, though any error can come through +for various reasons. + +### content encoding unsupported + +This error will occur when the request had a `Content-Encoding` header that +contained an encoding but the "inflation" option was set to `false`. The +`status` property is set to `415`, the `type` property is set to +`'encoding.unsupported'`, and the `charset` property will be set to the +encoding that is unsupported. + +### entity parse failed + +This error will occur when the request contained an entity that could not be +parsed by the middleware. The `status` property is set to `400`, the `type` +property is set to `'entity.parse.failed'`, and the `body` property is set to +the entity value that failed parsing. + +### entity verify failed + +This error will occur when the request contained an entity that could not be +failed verification by the defined `verify` option. The `status` property is +set to `403`, the `type` property is set to `'entity.verify.failed'`, and the +`body` property is set to the entity value that failed verification. + +### request aborted + +This error will occur when the request is aborted by the client before reading +the body has finished. The `received` property will be set to the number of +bytes received before the request was aborted and the `expected` property is +set to the number of expected bytes. The `status` property is set to `400` +and `type` property is set to `'request.aborted'`. + +### request entity too large + +This error will occur when the request body's size is larger than the "limit" +option. The `limit` property will be set to the byte limit and the `length` +property will be set to the request body's length. The `status` property is +set to `413` and the `type` property is set to `'entity.too.large'`. + +### request size did not match content length + +This error will occur when the request's length did not match the length from +the `Content-Length` header. This typically occurs when the request is malformed, +typically when the `Content-Length` header was calculated based on characters +instead of bytes. The `status` property is set to `400` and the `type` property +is set to `'request.size.invalid'`. + +### stream encoding should not be set + +This error will occur when something called the `req.setEncoding` method prior +to this middleware. This module operates directly on bytes only and you cannot +call `req.setEncoding` when using this module. The `status` property is set to +`500` and the `type` property is set to `'stream.encoding.set'`. + +### stream is not readable + +This error will occur when the request is no longer readable when this middleware +attempts to read it. This typically means something other than a middleware from +this module read the request body already and the middleware was also configured to +read the same request. The `status` property is set to `500` and the `type` +property is set to `'stream.not.readable'`. + +### too many parameters + +This error will occur when the content of the request exceeds the configured +`parameterLimit` for the `urlencoded` parser. The `status` property is set to +`413` and the `type` property is set to `'parameters.too.many'`. + +### unsupported charset "BOGUS" + +This error will occur when the request had a charset parameter in the +`Content-Type` header, but the `iconv-lite` module does not support it OR the +parser does not support it. The charset is contained in the message as well +as in the `charset` property. The `status` property is set to `415`, the +`type` property is set to `'charset.unsupported'`, and the `charset` property +is set to the charset that is unsupported. + +### unsupported content encoding "bogus" + +This error will occur when the request had a `Content-Encoding` header that +contained an unsupported encoding. The encoding is contained in the message +as well as in the `encoding` property. The `status` property is set to `415`, +the `type` property is set to `'encoding.unsupported'`, and the `encoding` +property is set to the encoding that is unsupported. + +## Examples + +### Express/Connect top-level generic + +This example demonstrates adding a generic JSON and URL-encoded parser as a +top-level middleware, which will parse the bodies of all incoming requests. +This is the simplest setup. + +```js +var express = require('express') +var bodyParser = require('body-parser') + +var app = express() + +// parse application/x-www-form-urlencoded +app.use(bodyParser.urlencoded({ extended: false })) + +// parse application/json +app.use(bodyParser.json()) + +app.use(function (req, res) { + res.setHeader('Content-Type', 'text/plain') + res.write('you posted:\n') + res.end(JSON.stringify(req.body, null, 2)) +}) +``` + +### Express route-specific + +This example demonstrates adding body parsers specifically to the routes that +need them. In general, this is the most recommended way to use body-parser with +Express. + +```js +var express = require('express') +var bodyParser = require('body-parser') + +var app = express() + +// create application/json parser +var jsonParser = bodyParser.json() + +// create application/x-www-form-urlencoded parser +var urlencodedParser = bodyParser.urlencoded({ extended: false }) + +// POST /login gets urlencoded bodies +app.post('/login', urlencodedParser, function (req, res) { + res.send('welcome, ' + req.body.username) +}) + +// POST /api/users gets JSON bodies +app.post('/api/users', jsonParser, function (req, res) { + // create user in req.body +}) +``` + +### Change accepted type for parsers + +All the parsers accept a `type` option which allows you to change the +`Content-Type` that the middleware will parse. + +```js +var express = require('express') +var bodyParser = require('body-parser') + +var app = express() + +// parse various different custom JSON types as JSON +app.use(bodyParser.json({ type: 'application/*+json' })) + +// parse some custom thing into a Buffer +app.use(bodyParser.raw({ type: 'application/vnd.custom-type' })) + +// parse an HTML body into a string +app.use(bodyParser.text({ type: 'text/html' })) +``` + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/expressjs/body-parser/master?label=ci +[ci-url]: https://github.com/expressjs/body-parser/actions/workflows/ci.yml +[coveralls-image]: https://badgen.net/coveralls/c/github/expressjs/body-parser/master +[coveralls-url]: https://coveralls.io/r/expressjs/body-parser?branch=master +[node-version-image]: https://badgen.net/npm/node/body-parser +[node-version-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/body-parser +[npm-url]: https://npmjs.org/package/body-parser +[npm-version-image]: https://badgen.net/npm/v/body-parser diff --git a/gun-server/node_modules/body-parser/SECURITY.md b/gun-server/node_modules/body-parser/SECURITY.md new file mode 100644 index 0000000..9694d42 --- /dev/null +++ b/gun-server/node_modules/body-parser/SECURITY.md @@ -0,0 +1,25 @@ +# Security Policies and Procedures + +## Reporting a Bug + +The Express team and community take all security bugs seriously. Thank you +for improving the security of Express. We appreciate your efforts and +responsible disclosure and will make every effort to acknowledge your +contributions. + +Report security bugs by emailing the current owner(s) of `body-parser`. This +information can be found in the npm registry using the command +`npm owner ls body-parser`. +If unsure or unable to get the information from the above, open an issue +in the [project issue tracker](https://github.com/expressjs/body-parser/issues) +asking for the current contact information. + +To ensure the timely response to your report, please ensure that the entirety +of the report is contained within the email body and not solely behind a web +link or an attachment. + +At least one owner will acknowledge your email within 48 hours, and will send a +more detailed response within 48 hours indicating the next steps in handling +your report. After the initial reply to your report, the owners will +endeavor to keep you informed of the progress towards a fix and full +announcement, and may ask for additional information or guidance. diff --git a/gun-server/node_modules/body-parser/index.js b/gun-server/node_modules/body-parser/index.js new file mode 100644 index 0000000..bb24d73 --- /dev/null +++ b/gun-server/node_modules/body-parser/index.js @@ -0,0 +1,156 @@ +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var deprecate = require('depd')('body-parser') + +/** + * Cache of loaded parsers. + * @private + */ + +var parsers = Object.create(null) + +/** + * @typedef Parsers + * @type {function} + * @property {function} json + * @property {function} raw + * @property {function} text + * @property {function} urlencoded + */ + +/** + * Module exports. + * @type {Parsers} + */ + +exports = module.exports = deprecate.function(bodyParser, + 'bodyParser: use individual json/urlencoded middlewares') + +/** + * JSON parser. + * @public + */ + +Object.defineProperty(exports, 'json', { + configurable: true, + enumerable: true, + get: createParserGetter('json') +}) + +/** + * Raw parser. + * @public + */ + +Object.defineProperty(exports, 'raw', { + configurable: true, + enumerable: true, + get: createParserGetter('raw') +}) + +/** + * Text parser. + * @public + */ + +Object.defineProperty(exports, 'text', { + configurable: true, + enumerable: true, + get: createParserGetter('text') +}) + +/** + * URL-encoded parser. + * @public + */ + +Object.defineProperty(exports, 'urlencoded', { + configurable: true, + enumerable: true, + get: createParserGetter('urlencoded') +}) + +/** + * Create a middleware to parse json and urlencoded bodies. + * + * @param {object} [options] + * @return {function} + * @deprecated + * @public + */ + +function bodyParser (options) { + // use default type for parsers + var opts = Object.create(options || null, { + type: { + configurable: true, + enumerable: true, + value: undefined, + writable: true + } + }) + + var _urlencoded = exports.urlencoded(opts) + var _json = exports.json(opts) + + return function bodyParser (req, res, next) { + _json(req, res, function (err) { + if (err) return next(err) + _urlencoded(req, res, next) + }) + } +} + +/** + * Create a getter for loading a parser. + * @private + */ + +function createParserGetter (name) { + return function get () { + return loadParser(name) + } +} + +/** + * Load a parser module. + * @private + */ + +function loadParser (parserName) { + var parser = parsers[parserName] + + if (parser !== undefined) { + return parser + } + + // this uses a switch for static require analysis + switch (parserName) { + case 'json': + parser = require('./lib/types/json') + break + case 'raw': + parser = require('./lib/types/raw') + break + case 'text': + parser = require('./lib/types/text') + break + case 'urlencoded': + parser = require('./lib/types/urlencoded') + break + } + + // store to prevent invoking require() + return (parsers[parserName] = parser) +} diff --git a/gun-server/node_modules/body-parser/lib/read.js b/gun-server/node_modules/body-parser/lib/read.js new file mode 100644 index 0000000..fce6283 --- /dev/null +++ b/gun-server/node_modules/body-parser/lib/read.js @@ -0,0 +1,205 @@ +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var createError = require('http-errors') +var destroy = require('destroy') +var getBody = require('raw-body') +var iconv = require('iconv-lite') +var onFinished = require('on-finished') +var unpipe = require('unpipe') +var zlib = require('zlib') + +/** + * Module exports. + */ + +module.exports = read + +/** + * Read a request into a buffer and parse. + * + * @param {object} req + * @param {object} res + * @param {function} next + * @param {function} parse + * @param {function} debug + * @param {object} options + * @private + */ + +function read (req, res, next, parse, debug, options) { + var length + var opts = options + var stream + + // flag as parsed + req._body = true + + // read options + var encoding = opts.encoding !== null + ? opts.encoding + : null + var verify = opts.verify + + try { + // get the content stream + stream = contentstream(req, debug, opts.inflate) + length = stream.length + stream.length = undefined + } catch (err) { + return next(err) + } + + // set raw-body options + opts.length = length + opts.encoding = verify + ? null + : encoding + + // assert charset is supported + if (opts.encoding === null && encoding !== null && !iconv.encodingExists(encoding)) { + return next(createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', { + charset: encoding.toLowerCase(), + type: 'charset.unsupported' + })) + } + + // read body + debug('read body') + getBody(stream, opts, function (error, body) { + if (error) { + var _error + + if (error.type === 'encoding.unsupported') { + // echo back charset + _error = createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', { + charset: encoding.toLowerCase(), + type: 'charset.unsupported' + }) + } else { + // set status code on error + _error = createError(400, error) + } + + // unpipe from stream and destroy + if (stream !== req) { + unpipe(req) + destroy(stream, true) + } + + // read off entire request + dump(req, function onfinished () { + next(createError(400, _error)) + }) + return + } + + // verify + if (verify) { + try { + debug('verify body') + verify(req, res, body, encoding) + } catch (err) { + next(createError(403, err, { + body: body, + type: err.type || 'entity.verify.failed' + })) + return + } + } + + // parse + var str = body + try { + debug('parse body') + str = typeof body !== 'string' && encoding !== null + ? iconv.decode(body, encoding) + : body + req.body = parse(str) + } catch (err) { + next(createError(400, err, { + body: str, + type: err.type || 'entity.parse.failed' + })) + return + } + + next() + }) +} + +/** + * Get the content stream of the request. + * + * @param {object} req + * @param {function} debug + * @param {boolean} [inflate=true] + * @return {object} + * @api private + */ + +function contentstream (req, debug, inflate) { + var encoding = (req.headers['content-encoding'] || 'identity').toLowerCase() + var length = req.headers['content-length'] + var stream + + debug('content-encoding "%s"', encoding) + + if (inflate === false && encoding !== 'identity') { + throw createError(415, 'content encoding unsupported', { + encoding: encoding, + type: 'encoding.unsupported' + }) + } + + switch (encoding) { + case 'deflate': + stream = zlib.createInflate() + debug('inflate body') + req.pipe(stream) + break + case 'gzip': + stream = zlib.createGunzip() + debug('gunzip body') + req.pipe(stream) + break + case 'identity': + stream = req + stream.length = length + break + default: + throw createError(415, 'unsupported content encoding "' + encoding + '"', { + encoding: encoding, + type: 'encoding.unsupported' + }) + } + + return stream +} + +/** + * Dump the contents of a request. + * + * @param {object} req + * @param {function} callback + * @api private + */ + +function dump (req, callback) { + if (onFinished.isFinished(req)) { + callback(null) + } else { + onFinished(req, callback) + req.resume() + } +} diff --git a/gun-server/node_modules/body-parser/lib/types/json.js b/gun-server/node_modules/body-parser/lib/types/json.js new file mode 100644 index 0000000..59f3f7e --- /dev/null +++ b/gun-server/node_modules/body-parser/lib/types/json.js @@ -0,0 +1,247 @@ +/*! + * body-parser + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var bytes = require('bytes') +var contentType = require('content-type') +var createError = require('http-errors') +var debug = require('debug')('body-parser:json') +var read = require('../read') +var typeis = require('type-is') + +/** + * Module exports. + */ + +module.exports = json + +/** + * RegExp to match the first non-space in a string. + * + * Allowed whitespace is defined in RFC 7159: + * + * ws = *( + * %x20 / ; Space + * %x09 / ; Horizontal tab + * %x0A / ; Line feed or New line + * %x0D ) ; Carriage return + */ + +var FIRST_CHAR_REGEXP = /^[\x20\x09\x0a\x0d]*([^\x20\x09\x0a\x0d])/ // eslint-disable-line no-control-regex + +var JSON_SYNTAX_CHAR = '#' +var JSON_SYNTAX_REGEXP = /#+/g + +/** + * Create a middleware to parse JSON bodies. + * + * @param {object} [options] + * @return {function} + * @public + */ + +function json (options) { + var opts = options || {} + + var limit = typeof opts.limit !== 'number' + ? bytes.parse(opts.limit || '100kb') + : opts.limit + var inflate = opts.inflate !== false + var reviver = opts.reviver + var strict = opts.strict !== false + var type = opts.type || 'application/json' + var verify = opts.verify || false + + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } + + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type + + function parse (body) { + if (body.length === 0) { + // special-case empty json body, as it's a common client-side mistake + // TODO: maybe make this configurable or part of "strict" option + return {} + } + + if (strict) { + var first = firstchar(body) + + if (first !== '{' && first !== '[') { + debug('strict violation') + throw createStrictSyntaxError(body, first) + } + } + + try { + debug('parse json') + return JSON.parse(body, reviver) + } catch (e) { + throw normalizeJsonSyntaxError(e, { + message: e.message, + stack: e.stack + }) + } + } + + return function jsonParser (req, res, next) { + if (req._body) { + debug('body already parsed') + next() + return + } + + req.body = req.body || {} + + // skip requests without bodies + if (!typeis.hasBody(req)) { + debug('skip empty body') + next() + return + } + + debug('content-type %j', req.headers['content-type']) + + // determine if request should be parsed + if (!shouldParse(req)) { + debug('skip parsing') + next() + return + } + + // assert charset per RFC 7159 sec 8.1 + var charset = getCharset(req) || 'utf-8' + if (charset.slice(0, 4) !== 'utf-') { + debug('invalid charset') + next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', { + charset: charset, + type: 'charset.unsupported' + })) + return + } + + // read + read(req, res, next, parse, debug, { + encoding: charset, + inflate: inflate, + limit: limit, + verify: verify + }) + } +} + +/** + * Create strict violation syntax error matching native error. + * + * @param {string} str + * @param {string} char + * @return {Error} + * @private + */ + +function createStrictSyntaxError (str, char) { + var index = str.indexOf(char) + var partial = '' + + if (index !== -1) { + partial = str.substring(0, index) + JSON_SYNTAX_CHAR + + for (var i = index + 1; i < str.length; i++) { + partial += JSON_SYNTAX_CHAR + } + } + + try { + JSON.parse(partial); /* istanbul ignore next */ throw new SyntaxError('strict violation') + } catch (e) { + return normalizeJsonSyntaxError(e, { + message: e.message.replace(JSON_SYNTAX_REGEXP, function (placeholder) { + return str.substring(index, index + placeholder.length) + }), + stack: e.stack + }) + } +} + +/** + * Get the first non-whitespace character in a string. + * + * @param {string} str + * @return {function} + * @private + */ + +function firstchar (str) { + var match = FIRST_CHAR_REGEXP.exec(str) + + return match + ? match[1] + : undefined +} + +/** + * Get the charset of a request. + * + * @param {object} req + * @api private + */ + +function getCharset (req) { + try { + return (contentType.parse(req).parameters.charset || '').toLowerCase() + } catch (e) { + return undefined + } +} + +/** + * Normalize a SyntaxError for JSON.parse. + * + * @param {SyntaxError} error + * @param {object} obj + * @return {SyntaxError} + */ + +function normalizeJsonSyntaxError (error, obj) { + var keys = Object.getOwnPropertyNames(error) + + for (var i = 0; i < keys.length; i++) { + var key = keys[i] + if (key !== 'stack' && key !== 'message') { + delete error[key] + } + } + + // replace stack before message for Node.js 0.10 and below + error.stack = obj.stack.replace(error.message, obj.message) + error.message = obj.message + + return error +} + +/** + * Get the simple type checker. + * + * @param {string} type + * @return {function} + */ + +function typeChecker (type) { + return function checkType (req) { + return Boolean(typeis(req, type)) + } +} diff --git a/gun-server/node_modules/body-parser/lib/types/raw.js b/gun-server/node_modules/body-parser/lib/types/raw.js new file mode 100644 index 0000000..f5d1b67 --- /dev/null +++ b/gun-server/node_modules/body-parser/lib/types/raw.js @@ -0,0 +1,101 @@ +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + */ + +var bytes = require('bytes') +var debug = require('debug')('body-parser:raw') +var read = require('../read') +var typeis = require('type-is') + +/** + * Module exports. + */ + +module.exports = raw + +/** + * Create a middleware to parse raw bodies. + * + * @param {object} [options] + * @return {function} + * @api public + */ + +function raw (options) { + var opts = options || {} + + var inflate = opts.inflate !== false + var limit = typeof opts.limit !== 'number' + ? bytes.parse(opts.limit || '100kb') + : opts.limit + var type = opts.type || 'application/octet-stream' + var verify = opts.verify || false + + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } + + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type + + function parse (buf) { + return buf + } + + return function rawParser (req, res, next) { + if (req._body) { + debug('body already parsed') + next() + return + } + + req.body = req.body || {} + + // skip requests without bodies + if (!typeis.hasBody(req)) { + debug('skip empty body') + next() + return + } + + debug('content-type %j', req.headers['content-type']) + + // determine if request should be parsed + if (!shouldParse(req)) { + debug('skip parsing') + next() + return + } + + // read + read(req, res, next, parse, debug, { + encoding: null, + inflate: inflate, + limit: limit, + verify: verify + }) + } +} + +/** + * Get the simple type checker. + * + * @param {string} type + * @return {function} + */ + +function typeChecker (type) { + return function checkType (req) { + return Boolean(typeis(req, type)) + } +} diff --git a/gun-server/node_modules/body-parser/lib/types/text.js b/gun-server/node_modules/body-parser/lib/types/text.js new file mode 100644 index 0000000..083a009 --- /dev/null +++ b/gun-server/node_modules/body-parser/lib/types/text.js @@ -0,0 +1,121 @@ +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + */ + +var bytes = require('bytes') +var contentType = require('content-type') +var debug = require('debug')('body-parser:text') +var read = require('../read') +var typeis = require('type-is') + +/** + * Module exports. + */ + +module.exports = text + +/** + * Create a middleware to parse text bodies. + * + * @param {object} [options] + * @return {function} + * @api public + */ + +function text (options) { + var opts = options || {} + + var defaultCharset = opts.defaultCharset || 'utf-8' + var inflate = opts.inflate !== false + var limit = typeof opts.limit !== 'number' + ? bytes.parse(opts.limit || '100kb') + : opts.limit + var type = opts.type || 'text/plain' + var verify = opts.verify || false + + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } + + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type + + function parse (buf) { + return buf + } + + return function textParser (req, res, next) { + if (req._body) { + debug('body already parsed') + next() + return + } + + req.body = req.body || {} + + // skip requests without bodies + if (!typeis.hasBody(req)) { + debug('skip empty body') + next() + return + } + + debug('content-type %j', req.headers['content-type']) + + // determine if request should be parsed + if (!shouldParse(req)) { + debug('skip parsing') + next() + return + } + + // get charset + var charset = getCharset(req) || defaultCharset + + // read + read(req, res, next, parse, debug, { + encoding: charset, + inflate: inflate, + limit: limit, + verify: verify + }) + } +} + +/** + * Get the charset of a request. + * + * @param {object} req + * @api private + */ + +function getCharset (req) { + try { + return (contentType.parse(req).parameters.charset || '').toLowerCase() + } catch (e) { + return undefined + } +} + +/** + * Get the simple type checker. + * + * @param {string} type + * @return {function} + */ + +function typeChecker (type) { + return function checkType (req) { + return Boolean(typeis(req, type)) + } +} diff --git a/gun-server/node_modules/body-parser/lib/types/urlencoded.js b/gun-server/node_modules/body-parser/lib/types/urlencoded.js new file mode 100644 index 0000000..b2ca8f1 --- /dev/null +++ b/gun-server/node_modules/body-parser/lib/types/urlencoded.js @@ -0,0 +1,284 @@ +/*! + * body-parser + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var bytes = require('bytes') +var contentType = require('content-type') +var createError = require('http-errors') +var debug = require('debug')('body-parser:urlencoded') +var deprecate = require('depd')('body-parser') +var read = require('../read') +var typeis = require('type-is') + +/** + * Module exports. + */ + +module.exports = urlencoded + +/** + * Cache of parser modules. + */ + +var parsers = Object.create(null) + +/** + * Create a middleware to parse urlencoded bodies. + * + * @param {object} [options] + * @return {function} + * @public + */ + +function urlencoded (options) { + var opts = options || {} + + // notice because option default will flip in next major + if (opts.extended === undefined) { + deprecate('undefined extended: provide extended option') + } + + var extended = opts.extended !== false + var inflate = opts.inflate !== false + var limit = typeof opts.limit !== 'number' + ? bytes.parse(opts.limit || '100kb') + : opts.limit + var type = opts.type || 'application/x-www-form-urlencoded' + var verify = opts.verify || false + + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } + + // create the appropriate query parser + var queryparse = extended + ? extendedparser(opts) + : simpleparser(opts) + + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type + + function parse (body) { + return body.length + ? queryparse(body) + : {} + } + + return function urlencodedParser (req, res, next) { + if (req._body) { + debug('body already parsed') + next() + return + } + + req.body = req.body || {} + + // skip requests without bodies + if (!typeis.hasBody(req)) { + debug('skip empty body') + next() + return + } + + debug('content-type %j', req.headers['content-type']) + + // determine if request should be parsed + if (!shouldParse(req)) { + debug('skip parsing') + next() + return + } + + // assert charset + var charset = getCharset(req) || 'utf-8' + if (charset !== 'utf-8') { + debug('invalid charset') + next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', { + charset: charset, + type: 'charset.unsupported' + })) + return + } + + // read + read(req, res, next, parse, debug, { + debug: debug, + encoding: charset, + inflate: inflate, + limit: limit, + verify: verify + }) + } +} + +/** + * Get the extended query parser. + * + * @param {object} options + */ + +function extendedparser (options) { + var parameterLimit = options.parameterLimit !== undefined + ? options.parameterLimit + : 1000 + var parse = parser('qs') + + if (isNaN(parameterLimit) || parameterLimit < 1) { + throw new TypeError('option parameterLimit must be a positive number') + } + + if (isFinite(parameterLimit)) { + parameterLimit = parameterLimit | 0 + } + + return function queryparse (body) { + var paramCount = parameterCount(body, parameterLimit) + + if (paramCount === undefined) { + debug('too many parameters') + throw createError(413, 'too many parameters', { + type: 'parameters.too.many' + }) + } + + var arrayLimit = Math.max(100, paramCount) + + debug('parse extended urlencoding') + return parse(body, { + allowPrototypes: true, + arrayLimit: arrayLimit, + depth: Infinity, + parameterLimit: parameterLimit + }) + } +} + +/** + * Get the charset of a request. + * + * @param {object} req + * @api private + */ + +function getCharset (req) { + try { + return (contentType.parse(req).parameters.charset || '').toLowerCase() + } catch (e) { + return undefined + } +} + +/** + * Count the number of parameters, stopping once limit reached + * + * @param {string} body + * @param {number} limit + * @api private + */ + +function parameterCount (body, limit) { + var count = 0 + var index = 0 + + while ((index = body.indexOf('&', index)) !== -1) { + count++ + index++ + + if (count === limit) { + return undefined + } + } + + return count +} + +/** + * Get parser for module name dynamically. + * + * @param {string} name + * @return {function} + * @api private + */ + +function parser (name) { + var mod = parsers[name] + + if (mod !== undefined) { + return mod.parse + } + + // this uses a switch for static require analysis + switch (name) { + case 'qs': + mod = require('qs') + break + case 'querystring': + mod = require('querystring') + break + } + + // store to prevent invoking require() + parsers[name] = mod + + return mod.parse +} + +/** + * Get the simple query parser. + * + * @param {object} options + */ + +function simpleparser (options) { + var parameterLimit = options.parameterLimit !== undefined + ? options.parameterLimit + : 1000 + var parse = parser('querystring') + + if (isNaN(parameterLimit) || parameterLimit < 1) { + throw new TypeError('option parameterLimit must be a positive number') + } + + if (isFinite(parameterLimit)) { + parameterLimit = parameterLimit | 0 + } + + return function queryparse (body) { + var paramCount = parameterCount(body, parameterLimit) + + if (paramCount === undefined) { + debug('too many parameters') + throw createError(413, 'too many parameters', { + type: 'parameters.too.many' + }) + } + + debug('parse urlencoding') + return parse(body, undefined, undefined, { maxKeys: parameterLimit }) + } +} + +/** + * Get the simple type checker. + * + * @param {string} type + * @return {function} + */ + +function typeChecker (type) { + return function checkType (req) { + return Boolean(typeis(req, type)) + } +} diff --git a/gun-server/node_modules/body-parser/package.json b/gun-server/node_modules/body-parser/package.json new file mode 100644 index 0000000..4637304 --- /dev/null +++ b/gun-server/node_modules/body-parser/package.json @@ -0,0 +1,56 @@ +{ + "name": "body-parser", + "description": "Node.js body parsing middleware", + "version": "1.20.2", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)" + ], + "license": "MIT", + "repository": "expressjs/body-parser", + "dependencies": { + "bytes": "3.1.2", + "content-type": "~1.0.5", + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "on-finished": "2.4.1", + "qs": "6.11.0", + "raw-body": "2.5.2", + "type-is": "~1.6.18", + "unpipe": "1.0.0" + }, + "devDependencies": { + "eslint": "8.34.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.27.5", + "eslint-plugin-markdown": "3.0.0", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "6.1.1", + "eslint-plugin-standard": "4.1.0", + "methods": "1.1.2", + "mocha": "10.2.0", + "nyc": "15.1.0", + "safe-buffer": "5.2.1", + "supertest": "6.3.3" + }, + "files": [ + "lib/", + "LICENSE", + "HISTORY.md", + "SECURITY.md", + "index.js" + ], + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --require test/support/env --reporter spec --check-leaks --bail test/", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + } +} diff --git a/gun-server/node_modules/bytes/History.md b/gun-server/node_modules/bytes/History.md new file mode 100644 index 0000000..d60ce0e --- /dev/null +++ b/gun-server/node_modules/bytes/History.md @@ -0,0 +1,97 @@ +3.1.2 / 2022-01-27 +================== + + * Fix return value for un-parsable strings + +3.1.1 / 2021-11-15 +================== + + * Fix "thousandsSeparator" incorrecting formatting fractional part + +3.1.0 / 2019-01-22 +================== + + * Add petabyte (`pb`) support + +3.0.0 / 2017-08-31 +================== + + * Change "kB" to "KB" in format output + * Remove support for Node.js 0.6 + * Remove support for ComponentJS + +2.5.0 / 2017-03-24 +================== + + * Add option "unit" + +2.4.0 / 2016-06-01 +================== + + * Add option "unitSeparator" + +2.3.0 / 2016-02-15 +================== + + * Drop partial bytes on all parsed units + * Fix non-finite numbers to `.format` to return `null` + * Fix parsing byte string that looks like hex + * perf: hoist regular expressions + +2.2.0 / 2015-11-13 +================== + + * add option "decimalPlaces" + * add option "fixedDecimals" + +2.1.0 / 2015-05-21 +================== + + * add `.format` export + * add `.parse` export + +2.0.2 / 2015-05-20 +================== + + * remove map recreation + * remove unnecessary object construction + +2.0.1 / 2015-05-07 +================== + + * fix browserify require + * remove node.extend dependency + +2.0.0 / 2015-04-12 +================== + + * add option "case" + * add option "thousandsSeparator" + * return "null" on invalid parse input + * support proper round-trip: bytes(bytes(num)) === num + * units no longer case sensitive when parsing + +1.0.0 / 2014-05-05 +================== + + * add negative support. fixes #6 + +0.3.0 / 2014-03-19 +================== + + * added terabyte support + +0.2.1 / 2013-04-01 +================== + + * add .component + +0.2.0 / 2012-10-28 +================== + + * bytes(200).should.eql('200b') + +0.1.0 / 2012-07-04 +================== + + * add bytes to string conversion [yields] diff --git a/gun-server/node_modules/bytes/LICENSE b/gun-server/node_modules/bytes/LICENSE new file mode 100644 index 0000000..63e95a9 --- /dev/null +++ b/gun-server/node_modules/bytes/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2012-2014 TJ Holowaychuk +Copyright (c) 2015 Jed Watson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/gun-server/node_modules/bytes/Readme.md b/gun-server/node_modules/bytes/Readme.md new file mode 100644 index 0000000..5790e23 --- /dev/null +++ b/gun-server/node_modules/bytes/Readme.md @@ -0,0 +1,152 @@ +# Bytes utility + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Build Status][ci-image]][ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Utility to parse a string bytes (ex: `1TB`) to bytes (`1099511627776`) and vice-versa. + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```bash +$ npm install bytes +``` + +## Usage + +```js +var bytes = require('bytes'); +``` + +#### bytes(number|string value, [options]): number|string|null + +Default export function. Delegates to either `bytes.format` or `bytes.parse` based on the type of `value`. + +**Arguments** + +| Name | Type | Description | +|---------|----------|--------------------| +| value | `number`|`string` | Number value to format or string value to parse | +| options | `Object` | Conversion options for `format` | + +**Returns** + +| Name | Type | Description | +|---------|------------------|-------------------------------------------------| +| results | `string`|`number`|`null` | Return null upon error. Numeric value in bytes, or string value otherwise. | + +**Example** + +```js +bytes(1024); +// output: '1KB' + +bytes('1KB'); +// output: 1024 +``` + +#### bytes.format(number value, [options]): string|null + +Format the given value in bytes into a string. If the value is negative, it is kept as such. If it is a float, it is + rounded. + +**Arguments** + +| Name | Type | Description | +|---------|----------|--------------------| +| value | `number` | Value in bytes | +| options | `Object` | Conversion options | + +**Options** + +| Property | Type | Description | +|-------------------|--------|-----------------------------------------------------------------------------------------| +| decimalPlaces | `number`|`null` | Maximum number of decimal places to include in output. Default value to `2`. | +| fixedDecimals | `boolean`|`null` | Whether to always display the maximum number of decimal places. Default value to `false` | +| thousandsSeparator | `string`|`null` | Example of values: `' '`, `','` and `'.'`... Default value to `''`. | +| unit | `string`|`null` | The unit in which the result will be returned (B/KB/MB/GB/TB). Default value to `''` (which means auto detect). | +| unitSeparator | `string`|`null` | Separator to use between number and unit. Default value to `''`. | + +**Returns** + +| Name | Type | Description | +|---------|------------------|-------------------------------------------------| +| results | `string`|`null` | Return null upon error. String value otherwise. | + +**Example** + +```js +bytes.format(1024); +// output: '1KB' + +bytes.format(1000); +// output: '1000B' + +bytes.format(1000, {thousandsSeparator: ' '}); +// output: '1 000B' + +bytes.format(1024 * 1.7, {decimalPlaces: 0}); +// output: '2KB' + +bytes.format(1024, {unitSeparator: ' '}); +// output: '1 KB' +``` + +#### bytes.parse(string|number value): number|null + +Parse the string value into an integer in bytes. If no unit is given, or `value` +is a number, it is assumed the value is in bytes. + +Supported units and abbreviations are as follows and are case-insensitive: + + * `b` for bytes + * `kb` for kilobytes + * `mb` for megabytes + * `gb` for gigabytes + * `tb` for terabytes + * `pb` for petabytes + +The units are in powers of two, not ten. This means 1kb = 1024b according to this parser. + +**Arguments** + +| Name | Type | Description | +|---------------|--------|--------------------| +| value | `string`|`number` | String to parse, or number in bytes. | + +**Returns** + +| Name | Type | Description | +|---------|-------------|-------------------------| +| results | `number`|`null` | Return null upon error. Value in bytes otherwise. | + +**Example** + +```js +bytes.parse('1KB'); +// output: 1024 + +bytes.parse('1024'); +// output: 1024 + +bytes.parse(1024); +// output: 1024 +``` + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/visionmedia/bytes.js/master?label=ci +[ci-url]: https://github.com/visionmedia/bytes.js/actions?query=workflow%3Aci +[coveralls-image]: https://badgen.net/coveralls/c/github/visionmedia/bytes.js/master +[coveralls-url]: https://coveralls.io/r/visionmedia/bytes.js?branch=master +[downloads-image]: https://badgen.net/npm/dm/bytes +[downloads-url]: https://npmjs.org/package/bytes +[npm-image]: https://badgen.net/npm/v/bytes +[npm-url]: https://npmjs.org/package/bytes diff --git a/gun-server/node_modules/bytes/index.js b/gun-server/node_modules/bytes/index.js new file mode 100644 index 0000000..6f2d0f8 --- /dev/null +++ b/gun-server/node_modules/bytes/index.js @@ -0,0 +1,170 @@ +/*! + * bytes + * Copyright(c) 2012-2014 TJ Holowaychuk + * Copyright(c) 2015 Jed Watson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +module.exports = bytes; +module.exports.format = format; +module.exports.parse = parse; + +/** + * Module variables. + * @private + */ + +var formatThousandsRegExp = /\B(?=(\d{3})+(?!\d))/g; + +var formatDecimalsRegExp = /(?:\.0*|(\.[^0]+)0+)$/; + +var map = { + b: 1, + kb: 1 << 10, + mb: 1 << 20, + gb: 1 << 30, + tb: Math.pow(1024, 4), + pb: Math.pow(1024, 5), +}; + +var parseRegExp = /^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i; + +/** + * Convert the given value in bytes into a string or parse to string to an integer in bytes. + * + * @param {string|number} value + * @param {{ + * case: [string], + * decimalPlaces: [number] + * fixedDecimals: [boolean] + * thousandsSeparator: [string] + * unitSeparator: [string] + * }} [options] bytes options. + * + * @returns {string|number|null} + */ + +function bytes(value, options) { + if (typeof value === 'string') { + return parse(value); + } + + if (typeof value === 'number') { + return format(value, options); + } + + return null; +} + +/** + * Format the given value in bytes into a string. + * + * If the value is negative, it is kept as such. If it is a float, + * it is rounded. + * + * @param {number} value + * @param {object} [options] + * @param {number} [options.decimalPlaces=2] + * @param {number} [options.fixedDecimals=false] + * @param {string} [options.thousandsSeparator=] + * @param {string} [options.unit=] + * @param {string} [options.unitSeparator=] + * + * @returns {string|null} + * @public + */ + +function format(value, options) { + if (!Number.isFinite(value)) { + return null; + } + + var mag = Math.abs(value); + var thousandsSeparator = (options && options.thousandsSeparator) || ''; + var unitSeparator = (options && options.unitSeparator) || ''; + var decimalPlaces = (options && options.decimalPlaces !== undefined) ? options.decimalPlaces : 2; + var fixedDecimals = Boolean(options && options.fixedDecimals); + var unit = (options && options.unit) || ''; + + if (!unit || !map[unit.toLowerCase()]) { + if (mag >= map.pb) { + unit = 'PB'; + } else if (mag >= map.tb) { + unit = 'TB'; + } else if (mag >= map.gb) { + unit = 'GB'; + } else if (mag >= map.mb) { + unit = 'MB'; + } else if (mag >= map.kb) { + unit = 'KB'; + } else { + unit = 'B'; + } + } + + var val = value / map[unit.toLowerCase()]; + var str = val.toFixed(decimalPlaces); + + if (!fixedDecimals) { + str = str.replace(formatDecimalsRegExp, '$1'); + } + + if (thousandsSeparator) { + str = str.split('.').map(function (s, i) { + return i === 0 + ? s.replace(formatThousandsRegExp, thousandsSeparator) + : s + }).join('.'); + } + + return str + unitSeparator + unit; +} + +/** + * Parse the string value into an integer in bytes. + * + * If no unit is given, it is assumed the value is in bytes. + * + * @param {number|string} val + * + * @returns {number|null} + * @public + */ + +function parse(val) { + if (typeof val === 'number' && !isNaN(val)) { + return val; + } + + if (typeof val !== 'string') { + return null; + } + + // Test if the string passed is valid + var results = parseRegExp.exec(val); + var floatValue; + var unit = 'b'; + + if (!results) { + // Nothing could be extracted from the given string + floatValue = parseInt(val, 10); + unit = 'b' + } else { + // Retrieve the value and the unit + floatValue = parseFloat(results[1]); + unit = results[4].toLowerCase(); + } + + if (isNaN(floatValue)) { + return null; + } + + return Math.floor(map[unit] * floatValue); +} diff --git a/gun-server/node_modules/bytes/package.json b/gun-server/node_modules/bytes/package.json new file mode 100644 index 0000000..f2b6a8b --- /dev/null +++ b/gun-server/node_modules/bytes/package.json @@ -0,0 +1,42 @@ +{ + "name": "bytes", + "description": "Utility to parse a string bytes to bytes and vice-versa", + "version": "3.1.2", + "author": "TJ Holowaychuk (http://tjholowaychuk.com)", + "contributors": [ + "Jed Watson ", + "Théo FIDRY " + ], + "license": "MIT", + "keywords": [ + "byte", + "bytes", + "utility", + "parse", + "parser", + "convert", + "converter" + ], + "repository": "visionmedia/bytes.js", + "devDependencies": { + "eslint": "7.32.0", + "eslint-plugin-markdown": "2.2.1", + "mocha": "9.2.0", + "nyc": "15.1.0" + }, + "files": [ + "History.md", + "LICENSE", + "Readme.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --check-leaks --reporter spec", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + } +} diff --git a/gun-server/node_modules/call-bind/.eslintignore b/gun-server/node_modules/call-bind/.eslintignore new file mode 100644 index 0000000..404abb2 --- /dev/null +++ b/gun-server/node_modules/call-bind/.eslintignore @@ -0,0 +1 @@ +coverage/ diff --git a/gun-server/node_modules/call-bind/.eslintrc b/gun-server/node_modules/call-bind/.eslintrc new file mode 100644 index 0000000..dfa9a6c --- /dev/null +++ b/gun-server/node_modules/call-bind/.eslintrc @@ -0,0 +1,16 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "func-name-matching": 0, + "id-length": 0, + "new-cap": [2, { + "capIsNewExceptions": [ + "GetIntrinsic", + ], + }], + "no-magic-numbers": 0, + }, +} diff --git a/gun-server/node_modules/call-bind/.github/FUNDING.yml b/gun-server/node_modules/call-bind/.github/FUNDING.yml new file mode 100644 index 0000000..c70c2ec --- /dev/null +++ b/gun-server/node_modules/call-bind/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/call-bind +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/gun-server/node_modules/call-bind/.nycrc b/gun-server/node_modules/call-bind/.nycrc new file mode 100644 index 0000000..bdd626c --- /dev/null +++ b/gun-server/node_modules/call-bind/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/gun-server/node_modules/call-bind/CHANGELOG.md b/gun-server/node_modules/call-bind/CHANGELOG.md new file mode 100644 index 0000000..c653f70 --- /dev/null +++ b/gun-server/node_modules/call-bind/CHANGELOG.md @@ -0,0 +1,93 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.7](https://github.com/ljharb/call-bind/compare/v1.0.6...v1.0.7) - 2024-02-12 + +### Commits + +- [Refactor] use `es-define-property` [`09b76a0`](https://github.com/ljharb/call-bind/commit/09b76a01634440461d44a80c9924ec4b500f3b03) +- [Deps] update `get-intrinsic`, `set-function-length` [`ad5136d`](https://github.com/ljharb/call-bind/commit/ad5136ddda2a45c590959829ad3dce0c9f4e3590) + +## [v1.0.6](https://github.com/ljharb/call-bind/compare/v1.0.5...v1.0.6) - 2024-02-05 + +### Commits + +- [Dev Deps] update `aud`, `npmignore`, `tape` [`d564d5c`](https://github.com/ljharb/call-bind/commit/d564d5ce3e06a19df4d499c77f8d1a9da44e77aa) +- [Deps] update `get-intrinsic`, `set-function-length` [`cfc2bdc`](https://github.com/ljharb/call-bind/commit/cfc2bdca7b633df0e0e689e6b637f668f1c6792e) +- [Refactor] use `es-errors`, so things that only need those do not need `get-intrinsic` [`64cd289`](https://github.com/ljharb/call-bind/commit/64cd289ae5862c250a4ca80aa8d461047c166af5) +- [meta] add missing `engines.node` [`32a4038`](https://github.com/ljharb/call-bind/commit/32a4038857b62179f7f9b7b3df2c5260036be582) + +## [v1.0.5](https://github.com/ljharb/call-bind/compare/v1.0.4...v1.0.5) - 2023-10-19 + +### Commits + +- [Fix] throw an error on non-functions as early as possible [`f262408`](https://github.com/ljharb/call-bind/commit/f262408f822c840fbc268080f3ad7c429611066d) +- [Deps] update `set-function-length` [`3fff271`](https://github.com/ljharb/call-bind/commit/3fff27145a1e3a76a5b74f1d7c3c43d0fa3b9871) + +## [v1.0.4](https://github.com/ljharb/call-bind/compare/v1.0.3...v1.0.4) - 2023-10-19 + +## [v1.0.3](https://github.com/ljharb/call-bind/compare/v1.0.2...v1.0.3) - 2023-10-19 + +### Commits + +- [actions] reuse common workflows [`a994df6`](https://github.com/ljharb/call-bind/commit/a994df69f401f4bf735a4ccd77029b85d1549453) +- [meta] use `npmignore` to autogenerate an npmignore file [`eef3ef2`](https://github.com/ljharb/call-bind/commit/eef3ef21e1f002790837fedb8af2679c761fbdf5) +- [readme] flesh out content [`1845ccf`](https://github.com/ljharb/call-bind/commit/1845ccfd9976a607884cfc7157c93192cc16cf22) +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`5b47d53`](https://github.com/ljharb/call-bind/commit/5b47d53d2fd74af5ea0a44f1d51e503cd42f7a90) +- [Refactor] use `set-function-length` [`a0e165c`](https://github.com/ljharb/call-bind/commit/a0e165c5dc61db781cbc919b586b1c2b8da0b150) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `tape` [`9c50103`](https://github.com/ljharb/call-bind/commit/9c50103f44137279a817317cf6cc421a658f85b4) +- [meta] simplify "exports" [`019c6d0`](https://github.com/ljharb/call-bind/commit/019c6d06b0e1246ceed8e579f57e44441cbbf6d9) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `safe-publish-latest`, `tape` [`23bd718`](https://github.com/ljharb/call-bind/commit/23bd718a288d3b03042062b4ef5153b3cea83f11) +- [actions] update codecov uploader [`62552d7`](https://github.com/ljharb/call-bind/commit/62552d79cc79e05825e99aaba134ae5b37f33da5) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`ec81665`](https://github.com/ljharb/call-bind/commit/ec81665b300f87eabff597afdc8b8092adfa7afd) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest`, `tape` [`35d67fc`](https://github.com/ljharb/call-bind/commit/35d67fcea883e686650f736f61da5ddca2592de8) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`0266d8d`](https://github.com/ljharb/call-bind/commit/0266d8d2a45086a922db366d0c2932fa463662ff) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `tape` [`43a5b28`](https://github.com/ljharb/call-bind/commit/43a5b28a444e710e1bbf92adb8afb5cf7523a223) +- [Deps] update `define-data-property`, `function-bind`, `get-intrinsic` [`780eb36`](https://github.com/ljharb/call-bind/commit/780eb36552514f8cc99c70821ce698697c2726a5) +- [Dev Deps] update `aud`, `tape` [`90d50ad`](https://github.com/ljharb/call-bind/commit/90d50ad03b061e0268b3380b0065fcaec183dc05) +- [meta] use `prepublishOnly` script for npm 7+ [`44c5433`](https://github.com/ljharb/call-bind/commit/44c5433b7980e02b4870007046407cf6fc543329) +- [Deps] update `get-intrinsic` [`86bfbfc`](https://github.com/ljharb/call-bind/commit/86bfbfcf34afdc6eabc93ce3d408548d0e27d958) +- [Deps] update `get-intrinsic` [`5c53354`](https://github.com/ljharb/call-bind/commit/5c5335489be0294c18cd7a8bb6e08226ee019ff5) +- [actions] update checkout action [`4c393a8`](https://github.com/ljharb/call-bind/commit/4c393a8173b3c8e5b30d5b3297b3b94d48bf87f3) +- [Deps] update `get-intrinsic` [`4e70bde`](https://github.com/ljharb/call-bind/commit/4e70bdec0626acb11616d66250fc14565e716e91) +- [Deps] update `get-intrinsic` [`55ae803`](https://github.com/ljharb/call-bind/commit/55ae803a920bd93c369cd798c20de31f91e9fc60) + +## [v1.0.2](https://github.com/ljharb/call-bind/compare/v1.0.1...v1.0.2) - 2021-01-11 + +### Commits + +- [Fix] properly include the receiver in the bound length [`dbae7bc`](https://github.com/ljharb/call-bind/commit/dbae7bc676c079a0d33c0a43e9ef92cb7b01345d) + +## [v1.0.1](https://github.com/ljharb/call-bind/compare/v1.0.0...v1.0.1) - 2021-01-08 + +### Commits + +- [Tests] migrate tests to Github Actions [`b6db284`](https://github.com/ljharb/call-bind/commit/b6db284c36f8ccd195b88a6764fe84b7223a0da1) +- [meta] do not publish github action workflow files [`ec7fe46`](https://github.com/ljharb/call-bind/commit/ec7fe46e60cfa4764ee943d2755f5e5a366e578e) +- [Fix] preserve original function’s length when possible [`adbceaa`](https://github.com/ljharb/call-bind/commit/adbceaa3cac4b41ea78bb19d7ccdbaaf7e0bdadb) +- [Tests] gather coverage data on every job [`d69e23c`](https://github.com/ljharb/call-bind/commit/d69e23cc65f101ba1d4c19bb07fa8eb0ec624be8) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`2fd3586`](https://github.com/ljharb/call-bind/commit/2fd3586c5d47b335364c14293114c6b625ae1f71) +- [Deps] update `get-intrinsic` [`f23e931`](https://github.com/ljharb/call-bind/commit/f23e9318cc271c2add8bb38cfded85ee7baf8eee) +- [Deps] update `get-intrinsic` [`72d9f44`](https://github.com/ljharb/call-bind/commit/72d9f44e184465ba8dd3fb48260bbcff234985f2) +- [meta] fix FUNDING.yml [`e723573`](https://github.com/ljharb/call-bind/commit/e723573438c5a68dcec31fb5d96ea6b7e4a93be8) +- [eslint] ignore coverage output [`15e76d2`](https://github.com/ljharb/call-bind/commit/15e76d28a5f43e504696401e5b31ebb78ee1b532) +- [meta] add Automatic Rebase and Require Allow Edits workflows [`8fa4dab`](https://github.com/ljharb/call-bind/commit/8fa4dabb23ba3dd7bb92c9571c1241c08b56e4b6) + +## v1.0.0 - 2020-10-30 + +### Commits + +- Initial commit [`306cf98`](https://github.com/ljharb/call-bind/commit/306cf98c7ec9e7ef66b653ec152277ac1381eb50) +- Tests [`e10d0bb`](https://github.com/ljharb/call-bind/commit/e10d0bbdadc7a10ecedc9a1c035112d3e368b8df) +- Implementation [`43852ed`](https://github.com/ljharb/call-bind/commit/43852eda0f187327b7fad2423ca972149a52bd65) +- npm init [`408f860`](https://github.com/ljharb/call-bind/commit/408f860b773a2f610805fd3613d0d71bac1b6249) +- [meta] add Automatic Rebase and Require Allow Edits workflows [`fb349b2`](https://github.com/ljharb/call-bind/commit/fb349b2e48defbec8b5ec8a8395cc8f69f220b13) +- [meta] add `auto-changelog` [`c4001fc`](https://github.com/ljharb/call-bind/commit/c4001fc43031799ef908211c98d3b0fb2b60fde4) +- [meta] add "funding"; create `FUNDING.yml` [`d4d6d29`](https://github.com/ljharb/call-bind/commit/d4d6d2974a14bc2e98830468eda7fe6d6a776717) +- [Tests] add `npm run lint` [`dedfb98`](https://github.com/ljharb/call-bind/commit/dedfb98bd0ecefb08ddb9a94061bd10cde4332af) +- Only apps should have lockfiles [`54ac776`](https://github.com/ljharb/call-bind/commit/54ac77653db45a7361dc153d2f478e743f110650) +- [meta] add `safe-publish-latest` [`9ea8e43`](https://github.com/ljharb/call-bind/commit/9ea8e435b950ce9b705559cd651039f9bf40140f) diff --git a/gun-server/node_modules/call-bind/LICENSE b/gun-server/node_modules/call-bind/LICENSE new file mode 100644 index 0000000..48f05d0 --- /dev/null +++ b/gun-server/node_modules/call-bind/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/gun-server/node_modules/call-bind/README.md b/gun-server/node_modules/call-bind/README.md new file mode 100644 index 0000000..48e9047 --- /dev/null +++ b/gun-server/node_modules/call-bind/README.md @@ -0,0 +1,64 @@ +# call-bind [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Robustly `.call.bind()` a function. + +## Getting started + +```sh +npm install --save call-bind +``` + +## Usage/Examples + +```js +const assert = require('assert'); +const callBind = require('call-bind'); +const callBound = require('call-bind/callBound'); + +function f(a, b) { + assert.equal(this, 1); + assert.equal(a, 2); + assert.equal(b, 3); + assert.equal(arguments.length, 2); +} + +const fBound = callBind(f); + +const slice = callBound('Array.prototype.slice'); + +delete Function.prototype.call; +delete Function.prototype.bind; + +fBound(1, 2, 3); + +assert.deepEqual(slice([1, 2, 3, 4], 1, -1), [2, 3]); +``` + +## Tests + +Clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/call-bind +[npm-version-svg]: https://versionbadg.es/ljharb/call-bind.svg +[deps-svg]: https://david-dm.org/ljharb/call-bind.svg +[deps-url]: https://david-dm.org/ljharb/call-bind +[dev-deps-svg]: https://david-dm.org/ljharb/call-bind/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/call-bind#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/call-bind.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/call-bind.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/call-bind.svg +[downloads-url]: https://npm-stat.com/charts.html?package=call-bind +[codecov-image]: https://codecov.io/gh/ljharb/call-bind/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/call-bind/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/call-bind +[actions-url]: https://github.com/ljharb/call-bind/actions diff --git a/gun-server/node_modules/call-bind/callBound.js b/gun-server/node_modules/call-bind/callBound.js new file mode 100644 index 0000000..8374adf --- /dev/null +++ b/gun-server/node_modules/call-bind/callBound.js @@ -0,0 +1,15 @@ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); + +var callBind = require('./'); + +var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf')); + +module.exports = function callBoundIntrinsic(name, allowMissing) { + var intrinsic = GetIntrinsic(name, !!allowMissing); + if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) { + return callBind(intrinsic); + } + return intrinsic; +}; diff --git a/gun-server/node_modules/call-bind/index.js b/gun-server/node_modules/call-bind/index.js new file mode 100644 index 0000000..01c5b3d --- /dev/null +++ b/gun-server/node_modules/call-bind/index.js @@ -0,0 +1,35 @@ +'use strict'; + +var bind = require('function-bind'); +var GetIntrinsic = require('get-intrinsic'); +var setFunctionLength = require('set-function-length'); + +var $TypeError = require('es-errors/type'); +var $apply = GetIntrinsic('%Function.prototype.apply%'); +var $call = GetIntrinsic('%Function.prototype.call%'); +var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply); + +var $defineProperty = require('es-define-property'); +var $max = GetIntrinsic('%Math.max%'); + +module.exports = function callBind(originalFunction) { + if (typeof originalFunction !== 'function') { + throw new $TypeError('a function is required'); + } + var func = $reflectApply(bind, $call, arguments); + return setFunctionLength( + func, + 1 + $max(0, originalFunction.length - (arguments.length - 1)), + true + ); +}; + +var applyBind = function applyBind() { + return $reflectApply(bind, $apply, arguments); +}; + +if ($defineProperty) { + $defineProperty(module.exports, 'apply', { value: applyBind }); +} else { + module.exports.apply = applyBind; +} diff --git a/gun-server/node_modules/call-bind/package.json b/gun-server/node_modules/call-bind/package.json new file mode 100644 index 0000000..5ba88ff --- /dev/null +++ b/gun-server/node_modules/call-bind/package.json @@ -0,0 +1,95 @@ +{ + "name": "call-bind", + "version": "1.0.7", + "description": "Robustly `.call.bind()` a function", + "main": "index.js", + "exports": { + ".": "./index.js", + "./callBound": "./callBound.js", + "./package.json": "./package.json" + }, + "scripts": { + "prepack": "npmignore --auto --commentLines=auto", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "lint": "eslint --ext=.js,.mjs .", + "postlint": "evalmd README.md", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/call-bind.git" + }, + "keywords": [ + "javascript", + "ecmascript", + "es", + "js", + "callbind", + "callbound", + "call", + "bind", + "bound", + "call-bind", + "call-bound", + "function", + "es-abstract" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/call-bind/issues" + }, + "homepage": "https://github.com/ljharb/call-bind#readme", + "devDependencies": { + "@ljharb/eslint-config": "^21.1.0", + "aud": "^2.0.4", + "auto-changelog": "^2.4.0", + "es-value-fixtures": "^1.4.2", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "for-each": "^0.3.3", + "gopd": "^1.0.1", + "has-strict-mode": "^1.0.1", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "object-inspect": "^1.13.1", + "safe-publish-latest": "^2.0.0", + "tape": "^5.7.4" + }, + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "set-function-length": "^1.2.1" + }, + "testling": { + "files": "test/index.js" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/gun-server/node_modules/call-bind/test/callBound.js b/gun-server/node_modules/call-bind/test/callBound.js new file mode 100644 index 0000000..c32319d --- /dev/null +++ b/gun-server/node_modules/call-bind/test/callBound.js @@ -0,0 +1,54 @@ +'use strict'; + +var test = require('tape'); + +var callBound = require('../callBound'); + +test('callBound', function (t) { + // static primitive + t.equal(callBound('Array.length'), Array.length, 'Array.length yields itself'); + t.equal(callBound('%Array.length%'), Array.length, '%Array.length% yields itself'); + + // static non-function object + t.equal(callBound('Array.prototype'), Array.prototype, 'Array.prototype yields itself'); + t.equal(callBound('%Array.prototype%'), Array.prototype, '%Array.prototype% yields itself'); + t.equal(callBound('Array.constructor'), Array.constructor, 'Array.constructor yields itself'); + t.equal(callBound('%Array.constructor%'), Array.constructor, '%Array.constructor% yields itself'); + + // static function + t.equal(callBound('Date.parse'), Date.parse, 'Date.parse yields itself'); + t.equal(callBound('%Date.parse%'), Date.parse, '%Date.parse% yields itself'); + + // prototype primitive + t.equal(callBound('Error.prototype.message'), Error.prototype.message, 'Error.prototype.message yields itself'); + t.equal(callBound('%Error.prototype.message%'), Error.prototype.message, '%Error.prototype.message% yields itself'); + + // prototype function + t.notEqual(callBound('Object.prototype.toString'), Object.prototype.toString, 'Object.prototype.toString does not yield itself'); + t.notEqual(callBound('%Object.prototype.toString%'), Object.prototype.toString, '%Object.prototype.toString% does not yield itself'); + t.equal(callBound('Object.prototype.toString')(true), Object.prototype.toString.call(true), 'call-bound Object.prototype.toString calls into the original'); + t.equal(callBound('%Object.prototype.toString%')(true), Object.prototype.toString.call(true), 'call-bound %Object.prototype.toString% calls into the original'); + + t['throws']( + function () { callBound('does not exist'); }, + SyntaxError, + 'nonexistent intrinsic throws' + ); + t['throws']( + function () { callBound('does not exist', true); }, + SyntaxError, + 'allowMissing arg still throws for unknown intrinsic' + ); + + t.test('real but absent intrinsic', { skip: typeof WeakRef !== 'undefined' }, function (st) { + st['throws']( + function () { callBound('WeakRef'); }, + TypeError, + 'real but absent intrinsic throws' + ); + st.equal(callBound('WeakRef', true), undefined, 'allowMissing arg avoids exception'); + st.end(); + }); + + t.end(); +}); diff --git a/gun-server/node_modules/call-bind/test/index.js b/gun-server/node_modules/call-bind/test/index.js new file mode 100644 index 0000000..1fd4668 --- /dev/null +++ b/gun-server/node_modules/call-bind/test/index.js @@ -0,0 +1,80 @@ +'use strict'; + +var callBind = require('../'); +var bind = require('function-bind'); +var gOPD = require('gopd'); +var hasStrictMode = require('has-strict-mode')(); +var forEach = require('for-each'); +var inspect = require('object-inspect'); +var v = require('es-value-fixtures'); + +var test = require('tape'); + +/* + * older engines have length nonconfigurable + * in io.js v3, it is configurable except on bound functions, hence the .bind() + */ +var functionsHaveConfigurableLengths = !!( + gOPD + && Object.getOwnPropertyDescriptor + && Object.getOwnPropertyDescriptor(bind.call(function () {}), 'length').configurable +); + +test('callBind', function (t) { + forEach(v.nonFunctions, function (nonFunction) { + t['throws']( + function () { callBind(nonFunction); }, + TypeError, + inspect(nonFunction) + ' is not a function' + ); + }); + + var sentinel = { sentinel: true }; + var func = function (a, b) { + // eslint-disable-next-line no-invalid-this + return [!hasStrictMode && this === global ? undefined : this, a, b]; + }; + t.equal(func.length, 2, 'original function length is 2'); + t.deepEqual(func(), [undefined, undefined, undefined], 'unbound func with too few args'); + t.deepEqual(func(1, 2), [undefined, 1, 2], 'unbound func with right args'); + t.deepEqual(func(1, 2, 3), [undefined, 1, 2], 'unbound func with too many args'); + + var bound = callBind(func); + t.equal(bound.length, func.length + 1, 'function length is preserved', { skip: !functionsHaveConfigurableLengths }); + t.deepEqual(bound(), [undefined, undefined, undefined], 'bound func with too few args'); + t.deepEqual(bound(1, 2), [hasStrictMode ? 1 : Object(1), 2, undefined], 'bound func with right args'); + t.deepEqual(bound(1, 2, 3), [hasStrictMode ? 1 : Object(1), 2, 3], 'bound func with too many args'); + + var boundR = callBind(func, sentinel); + t.equal(boundR.length, func.length, 'function length is preserved', { skip: !functionsHaveConfigurableLengths }); + t.deepEqual(boundR(), [sentinel, undefined, undefined], 'bound func with receiver, with too few args'); + t.deepEqual(boundR(1, 2), [sentinel, 1, 2], 'bound func with receiver, with right args'); + t.deepEqual(boundR(1, 2, 3), [sentinel, 1, 2], 'bound func with receiver, with too many args'); + + var boundArg = callBind(func, sentinel, 1); + t.equal(boundArg.length, func.length - 1, 'function length is preserved', { skip: !functionsHaveConfigurableLengths }); + t.deepEqual(boundArg(), [sentinel, 1, undefined], 'bound func with receiver and arg, with too few args'); + t.deepEqual(boundArg(2), [sentinel, 1, 2], 'bound func with receiver and arg, with right arg'); + t.deepEqual(boundArg(2, 3), [sentinel, 1, 2], 'bound func with receiver and arg, with too many args'); + + t.test('callBind.apply', function (st) { + var aBound = callBind.apply(func); + st.deepEqual(aBound(sentinel), [sentinel, undefined, undefined], 'apply-bound func with no args'); + st.deepEqual(aBound(sentinel, [1], 4), [sentinel, 1, undefined], 'apply-bound func with too few args'); + st.deepEqual(aBound(sentinel, [1, 2], 4), [sentinel, 1, 2], 'apply-bound func with right args'); + + var aBoundArg = callBind.apply(func); + st.deepEqual(aBoundArg(sentinel, [1, 2, 3], 4), [sentinel, 1, 2], 'apply-bound func with too many args'); + st.deepEqual(aBoundArg(sentinel, [1, 2], 4), [sentinel, 1, 2], 'apply-bound func with right args'); + st.deepEqual(aBoundArg(sentinel, [1], 4), [sentinel, 1, undefined], 'apply-bound func with too few args'); + + var aBoundR = callBind.apply(func, sentinel); + st.deepEqual(aBoundR([1, 2, 3], 4), [sentinel, 1, 2], 'apply-bound func with receiver and too many args'); + st.deepEqual(aBoundR([1, 2], 4), [sentinel, 1, 2], 'apply-bound func with receiver and right args'); + st.deepEqual(aBoundR([1], 4), [sentinel, 1, undefined], 'apply-bound func with receiver and too few args'); + + st.end(); + }); + + t.end(); +}); diff --git a/gun-server/node_modules/content-disposition/HISTORY.md b/gun-server/node_modules/content-disposition/HISTORY.md new file mode 100644 index 0000000..488effa --- /dev/null +++ b/gun-server/node_modules/content-disposition/HISTORY.md @@ -0,0 +1,60 @@ +0.5.4 / 2021-12-10 +================== + + * deps: safe-buffer@5.2.1 + +0.5.3 / 2018-12-17 +================== + + * Use `safe-buffer` for improved Buffer API + +0.5.2 / 2016-12-08 +================== + + * Fix `parse` to accept any linear whitespace character + +0.5.1 / 2016-01-17 +================== + + * perf: enable strict mode + +0.5.0 / 2014-10-11 +================== + + * Add `parse` function + +0.4.0 / 2014-09-21 +================== + + * Expand non-Unicode `filename` to the full ISO-8859-1 charset + +0.3.0 / 2014-09-20 +================== + + * Add `fallback` option + * Add `type` option + +0.2.0 / 2014-09-19 +================== + + * Reduce ambiguity of file names with hex escape in buggy browsers + +0.1.2 / 2014-09-19 +================== + + * Fix periodic invalid Unicode filename header + +0.1.1 / 2014-09-19 +================== + + * Fix invalid characters appearing in `filename*` parameter + +0.1.0 / 2014-09-18 +================== + + * Make the `filename` argument optional + +0.0.0 / 2014-09-18 +================== + + * Initial release diff --git a/gun-server/node_modules/content-disposition/LICENSE b/gun-server/node_modules/content-disposition/LICENSE new file mode 100644 index 0000000..84441fb --- /dev/null +++ b/gun-server/node_modules/content-disposition/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014-2017 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/gun-server/node_modules/content-disposition/README.md b/gun-server/node_modules/content-disposition/README.md new file mode 100644 index 0000000..3a0bb05 --- /dev/null +++ b/gun-server/node_modules/content-disposition/README.md @@ -0,0 +1,142 @@ +# content-disposition + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][github-actions-ci-image]][github-actions-ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Create and parse HTTP `Content-Disposition` header + +## Installation + +```sh +$ npm install content-disposition +``` + +## API + +```js +var contentDisposition = require('content-disposition') +``` + +### contentDisposition(filename, options) + +Create an attachment `Content-Disposition` header value using the given file name, +if supplied. The `filename` is optional and if no file name is desired, but you +want to specify `options`, set `filename` to `undefined`. + +```js +res.setHeader('Content-Disposition', contentDisposition('∫ maths.pdf')) +``` + +**note** HTTP headers are of the ISO-8859-1 character set. If you are writing this +header through a means different from `setHeader` in Node.js, you'll want to specify +the `'binary'` encoding in Node.js. + +#### Options + +`contentDisposition` accepts these properties in the options object. + +##### fallback + +If the `filename` option is outside ISO-8859-1, then the file name is actually +stored in a supplemental field for clients that support Unicode file names and +a ISO-8859-1 version of the file name is automatically generated. + +This specifies the ISO-8859-1 file name to override the automatic generation or +disables the generation all together, defaults to `true`. + + - A string will specify the ISO-8859-1 file name to use in place of automatic + generation. + - `false` will disable including a ISO-8859-1 file name and only include the + Unicode version (unless the file name is already ISO-8859-1). + - `true` will enable automatic generation if the file name is outside ISO-8859-1. + +If the `filename` option is ISO-8859-1 and this option is specified and has a +different value, then the `filename` option is encoded in the extended field +and this set as the fallback field, even though they are both ISO-8859-1. + +##### type + +Specifies the disposition type, defaults to `"attachment"`. This can also be +`"inline"`, or any other value (all values except inline are treated like +`attachment`, but can convey additional information if both parties agree to +it). The type is normalized to lower-case. + +### contentDisposition.parse(string) + +```js +var disposition = contentDisposition.parse('attachment; filename="EURO rates.txt"; filename*=UTF-8\'\'%e2%82%ac%20rates.txt') +``` + +Parse a `Content-Disposition` header string. This automatically handles extended +("Unicode") parameters by decoding them and providing them under the standard +parameter name. This will return an object with the following properties (examples +are shown for the string `'attachment; filename="EURO rates.txt"; filename*=UTF-8\'\'%e2%82%ac%20rates.txt'`): + + - `type`: The disposition type (always lower case). Example: `'attachment'` + + - `parameters`: An object of the parameters in the disposition (name of parameter + always lower case and extended versions replace non-extended versions). Example: + `{filename: "€ rates.txt"}` + +## Examples + +### Send a file for download + +```js +var contentDisposition = require('content-disposition') +var destroy = require('destroy') +var fs = require('fs') +var http = require('http') +var onFinished = require('on-finished') + +var filePath = '/path/to/public/plans.pdf' + +http.createServer(function onRequest (req, res) { + // set headers + res.setHeader('Content-Type', 'application/pdf') + res.setHeader('Content-Disposition', contentDisposition(filePath)) + + // send file + var stream = fs.createReadStream(filePath) + stream.pipe(res) + onFinished(res, function () { + destroy(stream) + }) +}) +``` + +## Testing + +```sh +$ npm test +``` + +## References + +- [RFC 2616: Hypertext Transfer Protocol -- HTTP/1.1][rfc-2616] +- [RFC 5987: Character Set and Language Encoding for Hypertext Transfer Protocol (HTTP) Header Field Parameters][rfc-5987] +- [RFC 6266: Use of the Content-Disposition Header Field in the Hypertext Transfer Protocol (HTTP)][rfc-6266] +- [Test Cases for HTTP Content-Disposition header field (RFC 6266) and the Encodings defined in RFCs 2047, 2231 and 5987][tc-2231] + +[rfc-2616]: https://tools.ietf.org/html/rfc2616 +[rfc-5987]: https://tools.ietf.org/html/rfc5987 +[rfc-6266]: https://tools.ietf.org/html/rfc6266 +[tc-2231]: http://greenbytes.de/tech/tc2231/ + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/content-disposition.svg +[npm-url]: https://npmjs.org/package/content-disposition +[node-version-image]: https://img.shields.io/node/v/content-disposition.svg +[node-version-url]: https://nodejs.org/en/download +[coveralls-image]: https://img.shields.io/coveralls/jshttp/content-disposition.svg +[coveralls-url]: https://coveralls.io/r/jshttp/content-disposition?branch=master +[downloads-image]: https://img.shields.io/npm/dm/content-disposition.svg +[downloads-url]: https://npmjs.org/package/content-disposition +[github-actions-ci-image]: https://img.shields.io/github/workflow/status/jshttp/content-disposition/ci/master?label=ci +[github-actions-ci-url]: https://github.com/jshttp/content-disposition?query=workflow%3Aci diff --git a/gun-server/node_modules/content-disposition/index.js b/gun-server/node_modules/content-disposition/index.js new file mode 100644 index 0000000..ecec899 --- /dev/null +++ b/gun-server/node_modules/content-disposition/index.js @@ -0,0 +1,458 @@ +/*! + * content-disposition + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = contentDisposition +module.exports.parse = parse + +/** + * Module dependencies. + * @private + */ + +var basename = require('path').basename +var Buffer = require('safe-buffer').Buffer + +/** + * RegExp to match non attr-char, *after* encodeURIComponent (i.e. not including "%") + * @private + */ + +var ENCODE_URL_ATTR_CHAR_REGEXP = /[\x00-\x20"'()*,/:;<=>?@[\\\]{}\x7f]/g // eslint-disable-line no-control-regex + +/** + * RegExp to match percent encoding escape. + * @private + */ + +var HEX_ESCAPE_REGEXP = /%[0-9A-Fa-f]{2}/ +var HEX_ESCAPE_REPLACE_REGEXP = /%([0-9A-Fa-f]{2})/g + +/** + * RegExp to match non-latin1 characters. + * @private + */ + +var NON_LATIN1_REGEXP = /[^\x20-\x7e\xa0-\xff]/g + +/** + * RegExp to match quoted-pair in RFC 2616 + * + * quoted-pair = "\" CHAR + * CHAR = + * @private + */ + +var QESC_REGEXP = /\\([\u0000-\u007f])/g // eslint-disable-line no-control-regex + +/** + * RegExp to match chars that must be quoted-pair in RFC 2616 + * @private + */ + +var QUOTE_REGEXP = /([\\"])/g + +/** + * RegExp for various RFC 2616 grammar + * + * parameter = token "=" ( token | quoted-string ) + * token = 1* + * separators = "(" | ")" | "<" | ">" | "@" + * | "," | ";" | ":" | "\" | <"> + * | "/" | "[" | "]" | "?" | "=" + * | "{" | "}" | SP | HT + * quoted-string = ( <"> *(qdtext | quoted-pair ) <"> ) + * qdtext = > + * quoted-pair = "\" CHAR + * CHAR = + * TEXT = + * LWS = [CRLF] 1*( SP | HT ) + * CRLF = CR LF + * CR = + * LF = + * SP = + * HT = + * CTL = + * OCTET = + * @private + */ + +var PARAM_REGEXP = /;[\x09\x20]*([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*=[\x09\x20]*("(?:[\x20!\x23-\x5b\x5d-\x7e\x80-\xff]|\\[\x20-\x7e])*"|[!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*/g // eslint-disable-line no-control-regex +var TEXT_REGEXP = /^[\x20-\x7e\x80-\xff]+$/ +var TOKEN_REGEXP = /^[!#$%&'*+.0-9A-Z^_`a-z|~-]+$/ + +/** + * RegExp for various RFC 5987 grammar + * + * ext-value = charset "'" [ language ] "'" value-chars + * charset = "UTF-8" / "ISO-8859-1" / mime-charset + * mime-charset = 1*mime-charsetc + * mime-charsetc = ALPHA / DIGIT + * / "!" / "#" / "$" / "%" / "&" + * / "+" / "-" / "^" / "_" / "`" + * / "{" / "}" / "~" + * language = ( 2*3ALPHA [ extlang ] ) + * / 4ALPHA + * / 5*8ALPHA + * extlang = *3( "-" 3ALPHA ) + * value-chars = *( pct-encoded / attr-char ) + * pct-encoded = "%" HEXDIG HEXDIG + * attr-char = ALPHA / DIGIT + * / "!" / "#" / "$" / "&" / "+" / "-" / "." + * / "^" / "_" / "`" / "|" / "~" + * @private + */ + +var EXT_VALUE_REGEXP = /^([A-Za-z0-9!#$%&+\-^_`{}~]+)'(?:[A-Za-z]{2,3}(?:-[A-Za-z]{3}){0,3}|[A-Za-z]{4,8}|)'((?:%[0-9A-Fa-f]{2}|[A-Za-z0-9!#$&+.^_`|~-])+)$/ + +/** + * RegExp for various RFC 6266 grammar + * + * disposition-type = "inline" | "attachment" | disp-ext-type + * disp-ext-type = token + * disposition-parm = filename-parm | disp-ext-parm + * filename-parm = "filename" "=" value + * | "filename*" "=" ext-value + * disp-ext-parm = token "=" value + * | ext-token "=" ext-value + * ext-token = + * @private + */ + +var DISPOSITION_TYPE_REGEXP = /^([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*(?:$|;)/ // eslint-disable-line no-control-regex + +/** + * Create an attachment Content-Disposition header. + * + * @param {string} [filename] + * @param {object} [options] + * @param {string} [options.type=attachment] + * @param {string|boolean} [options.fallback=true] + * @return {string} + * @public + */ + +function contentDisposition (filename, options) { + var opts = options || {} + + // get type + var type = opts.type || 'attachment' + + // get parameters + var params = createparams(filename, opts.fallback) + + // format into string + return format(new ContentDisposition(type, params)) +} + +/** + * Create parameters object from filename and fallback. + * + * @param {string} [filename] + * @param {string|boolean} [fallback=true] + * @return {object} + * @private + */ + +function createparams (filename, fallback) { + if (filename === undefined) { + return + } + + var params = {} + + if (typeof filename !== 'string') { + throw new TypeError('filename must be a string') + } + + // fallback defaults to true + if (fallback === undefined) { + fallback = true + } + + if (typeof fallback !== 'string' && typeof fallback !== 'boolean') { + throw new TypeError('fallback must be a string or boolean') + } + + if (typeof fallback === 'string' && NON_LATIN1_REGEXP.test(fallback)) { + throw new TypeError('fallback must be ISO-8859-1 string') + } + + // restrict to file base name + var name = basename(filename) + + // determine if name is suitable for quoted string + var isQuotedString = TEXT_REGEXP.test(name) + + // generate fallback name + var fallbackName = typeof fallback !== 'string' + ? fallback && getlatin1(name) + : basename(fallback) + var hasFallback = typeof fallbackName === 'string' && fallbackName !== name + + // set extended filename parameter + if (hasFallback || !isQuotedString || HEX_ESCAPE_REGEXP.test(name)) { + params['filename*'] = name + } + + // set filename parameter + if (isQuotedString || hasFallback) { + params.filename = hasFallback + ? fallbackName + : name + } + + return params +} + +/** + * Format object to Content-Disposition header. + * + * @param {object} obj + * @param {string} obj.type + * @param {object} [obj.parameters] + * @return {string} + * @private + */ + +function format (obj) { + var parameters = obj.parameters + var type = obj.type + + if (!type || typeof type !== 'string' || !TOKEN_REGEXP.test(type)) { + throw new TypeError('invalid type') + } + + // start with normalized type + var string = String(type).toLowerCase() + + // append parameters + if (parameters && typeof parameters === 'object') { + var param + var params = Object.keys(parameters).sort() + + for (var i = 0; i < params.length; i++) { + param = params[i] + + var val = param.substr(-1) === '*' + ? ustring(parameters[param]) + : qstring(parameters[param]) + + string += '; ' + param + '=' + val + } + } + + return string +} + +/** + * Decode a RFC 5987 field value (gracefully). + * + * @param {string} str + * @return {string} + * @private + */ + +function decodefield (str) { + var match = EXT_VALUE_REGEXP.exec(str) + + if (!match) { + throw new TypeError('invalid extended field value') + } + + var charset = match[1].toLowerCase() + var encoded = match[2] + var value + + // to binary string + var binary = encoded.replace(HEX_ESCAPE_REPLACE_REGEXP, pdecode) + + switch (charset) { + case 'iso-8859-1': + value = getlatin1(binary) + break + case 'utf-8': + value = Buffer.from(binary, 'binary').toString('utf8') + break + default: + throw new TypeError('unsupported charset in extended field') + } + + return value +} + +/** + * Get ISO-8859-1 version of string. + * + * @param {string} val + * @return {string} + * @private + */ + +function getlatin1 (val) { + // simple Unicode -> ISO-8859-1 transformation + return String(val).replace(NON_LATIN1_REGEXP, '?') +} + +/** + * Parse Content-Disposition header string. + * + * @param {string} string + * @return {object} + * @public + */ + +function parse (string) { + if (!string || typeof string !== 'string') { + throw new TypeError('argument string is required') + } + + var match = DISPOSITION_TYPE_REGEXP.exec(string) + + if (!match) { + throw new TypeError('invalid type format') + } + + // normalize type + var index = match[0].length + var type = match[1].toLowerCase() + + var key + var names = [] + var params = {} + var value + + // calculate index to start at + index = PARAM_REGEXP.lastIndex = match[0].substr(-1) === ';' + ? index - 1 + : index + + // match parameters + while ((match = PARAM_REGEXP.exec(string))) { + if (match.index !== index) { + throw new TypeError('invalid parameter format') + } + + index += match[0].length + key = match[1].toLowerCase() + value = match[2] + + if (names.indexOf(key) !== -1) { + throw new TypeError('invalid duplicate parameter') + } + + names.push(key) + + if (key.indexOf('*') + 1 === key.length) { + // decode extended value + key = key.slice(0, -1) + value = decodefield(value) + + // overwrite existing value + params[key] = value + continue + } + + if (typeof params[key] === 'string') { + continue + } + + if (value[0] === '"') { + // remove quotes and escapes + value = value + .substr(1, value.length - 2) + .replace(QESC_REGEXP, '$1') + } + + params[key] = value + } + + if (index !== -1 && index !== string.length) { + throw new TypeError('invalid parameter format') + } + + return new ContentDisposition(type, params) +} + +/** + * Percent decode a single character. + * + * @param {string} str + * @param {string} hex + * @return {string} + * @private + */ + +function pdecode (str, hex) { + return String.fromCharCode(parseInt(hex, 16)) +} + +/** + * Percent encode a single character. + * + * @param {string} char + * @return {string} + * @private + */ + +function pencode (char) { + return '%' + String(char) + .charCodeAt(0) + .toString(16) + .toUpperCase() +} + +/** + * Quote a string for HTTP. + * + * @param {string} val + * @return {string} + * @private + */ + +function qstring (val) { + var str = String(val) + + return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"' +} + +/** + * Encode a Unicode string for HTTP (RFC 5987). + * + * @param {string} val + * @return {string} + * @private + */ + +function ustring (val) { + var str = String(val) + + // percent encode as UTF-8 + var encoded = encodeURIComponent(str) + .replace(ENCODE_URL_ATTR_CHAR_REGEXP, pencode) + + return 'UTF-8\'\'' + encoded +} + +/** + * Class for parsed Content-Disposition header for v8 optimization + * + * @public + * @param {string} type + * @param {object} parameters + * @constructor + */ + +function ContentDisposition (type, parameters) { + this.type = type + this.parameters = parameters +} diff --git a/gun-server/node_modules/content-disposition/package.json b/gun-server/node_modules/content-disposition/package.json new file mode 100644 index 0000000..43c70ce --- /dev/null +++ b/gun-server/node_modules/content-disposition/package.json @@ -0,0 +1,44 @@ +{ + "name": "content-disposition", + "description": "Create and parse Content-Disposition header", + "version": "0.5.4", + "author": "Douglas Christopher Wilson ", + "license": "MIT", + "keywords": [ + "content-disposition", + "http", + "rfc6266", + "res" + ], + "repository": "jshttp/content-disposition", + "dependencies": { + "safe-buffer": "5.2.1" + }, + "devDependencies": { + "deep-equal": "1.0.1", + "eslint": "7.32.0", + "eslint-config-standard": "13.0.1", + "eslint-plugin-import": "2.25.3", + "eslint-plugin-markdown": "2.2.1", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "5.2.0", + "eslint-plugin-standard": "4.1.0", + "istanbul": "0.4.5", + "mocha": "9.1.3" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-ci": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/" + } +} diff --git a/gun-server/node_modules/content-type/HISTORY.md b/gun-server/node_modules/content-type/HISTORY.md new file mode 100644 index 0000000..4583671 --- /dev/null +++ b/gun-server/node_modules/content-type/HISTORY.md @@ -0,0 +1,29 @@ +1.0.5 / 2023-01-29 +================== + + * perf: skip value escaping when unnecessary + +1.0.4 / 2017-09-11 +================== + + * perf: skip parameter parsing when no parameters + +1.0.3 / 2017-09-10 +================== + + * perf: remove argument reassignment + +1.0.2 / 2016-05-09 +================== + + * perf: enable strict mode + +1.0.1 / 2015-02-13 +================== + + * Improve missing `Content-Type` header error message + +1.0.0 / 2015-02-01 +================== + + * Initial implementation, derived from `media-typer@0.3.0` diff --git a/gun-server/node_modules/content-type/LICENSE b/gun-server/node_modules/content-type/LICENSE new file mode 100644 index 0000000..34b1a2d --- /dev/null +++ b/gun-server/node_modules/content-type/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2015 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/gun-server/node_modules/content-type/README.md b/gun-server/node_modules/content-type/README.md new file mode 100644 index 0000000..c1a922a --- /dev/null +++ b/gun-server/node_modules/content-type/README.md @@ -0,0 +1,94 @@ +# content-type + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][ci-image]][ci-url] +[![Coverage Status][coveralls-image]][coveralls-url] + +Create and parse HTTP Content-Type header according to RFC 7231 + +## Installation + +```sh +$ npm install content-type +``` + +## API + +```js +var contentType = require('content-type') +``` + +### contentType.parse(string) + +```js +var obj = contentType.parse('image/svg+xml; charset=utf-8') +``` + +Parse a `Content-Type` header. This will return an object with the following +properties (examples are shown for the string `'image/svg+xml; charset=utf-8'`): + + - `type`: The media type (the type and subtype, always lower case). + Example: `'image/svg+xml'` + + - `parameters`: An object of the parameters in the media type (name of parameter + always lower case). Example: `{charset: 'utf-8'}` + +Throws a `TypeError` if the string is missing or invalid. + +### contentType.parse(req) + +```js +var obj = contentType.parse(req) +``` + +Parse the `Content-Type` header from the given `req`. Short-cut for +`contentType.parse(req.headers['content-type'])`. + +Throws a `TypeError` if the `Content-Type` header is missing or invalid. + +### contentType.parse(res) + +```js +var obj = contentType.parse(res) +``` + +Parse the `Content-Type` header set on the given `res`. Short-cut for +`contentType.parse(res.getHeader('content-type'))`. + +Throws a `TypeError` if the `Content-Type` header is missing or invalid. + +### contentType.format(obj) + +```js +var str = contentType.format({ + type: 'image/svg+xml', + parameters: { charset: 'utf-8' } +}) +``` + +Format an object into a `Content-Type` header. This will return a string of the +content type for the given object with the following properties (examples are +shown that produce the string `'image/svg+xml; charset=utf-8'`): + + - `type`: The media type (will be lower-cased). Example: `'image/svg+xml'` + + - `parameters`: An object of the parameters in the media type (name of the + parameter will be lower-cased). Example: `{charset: 'utf-8'}` + +Throws a `TypeError` if the object contains an invalid type or parameter names. + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/jshttp/content-type/master?label=ci +[ci-url]: https://github.com/jshttp/content-type/actions/workflows/ci.yml +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/content-type/master +[coveralls-url]: https://coveralls.io/r/jshttp/content-type?branch=master +[node-image]: https://badgen.net/npm/node/content-type +[node-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/content-type +[npm-url]: https://npmjs.org/package/content-type +[npm-version-image]: https://badgen.net/npm/v/content-type diff --git a/gun-server/node_modules/content-type/index.js b/gun-server/node_modules/content-type/index.js new file mode 100644 index 0000000..41840e7 --- /dev/null +++ b/gun-server/node_modules/content-type/index.js @@ -0,0 +1,225 @@ +/*! + * content-type + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1 + * + * parameter = token "=" ( token / quoted-string ) + * token = 1*tchar + * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" + * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" + * / DIGIT / ALPHA + * ; any VCHAR, except delimiters + * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE + * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text + * obs-text = %x80-FF + * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + */ +var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g // eslint-disable-line no-control-regex +var TEXT_REGEXP = /^[\u000b\u0020-\u007e\u0080-\u00ff]+$/ // eslint-disable-line no-control-regex +var TOKEN_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/ + +/** + * RegExp to match quoted-pair in RFC 7230 sec 3.2.6 + * + * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + * obs-text = %x80-FF + */ +var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g // eslint-disable-line no-control-regex + +/** + * RegExp to match chars that must be quoted-pair in RFC 7230 sec 3.2.6 + */ +var QUOTE_REGEXP = /([\\"])/g + +/** + * RegExp to match type in RFC 7231 sec 3.1.1.1 + * + * media-type = type "/" subtype + * type = token + * subtype = token + */ +var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/ + +/** + * Module exports. + * @public + */ + +exports.format = format +exports.parse = parse + +/** + * Format object to media type. + * + * @param {object} obj + * @return {string} + * @public + */ + +function format (obj) { + if (!obj || typeof obj !== 'object') { + throw new TypeError('argument obj is required') + } + + var parameters = obj.parameters + var type = obj.type + + if (!type || !TYPE_REGEXP.test(type)) { + throw new TypeError('invalid type') + } + + var string = type + + // append parameters + if (parameters && typeof parameters === 'object') { + var param + var params = Object.keys(parameters).sort() + + for (var i = 0; i < params.length; i++) { + param = params[i] + + if (!TOKEN_REGEXP.test(param)) { + throw new TypeError('invalid parameter name') + } + + string += '; ' + param + '=' + qstring(parameters[param]) + } + } + + return string +} + +/** + * Parse media type to object. + * + * @param {string|object} string + * @return {Object} + * @public + */ + +function parse (string) { + if (!string) { + throw new TypeError('argument string is required') + } + + // support req/res-like objects as argument + var header = typeof string === 'object' + ? getcontenttype(string) + : string + + if (typeof header !== 'string') { + throw new TypeError('argument string is required to be a string') + } + + var index = header.indexOf(';') + var type = index !== -1 + ? header.slice(0, index).trim() + : header.trim() + + if (!TYPE_REGEXP.test(type)) { + throw new TypeError('invalid media type') + } + + var obj = new ContentType(type.toLowerCase()) + + // parse parameters + if (index !== -1) { + var key + var match + var value + + PARAM_REGEXP.lastIndex = index + + while ((match = PARAM_REGEXP.exec(header))) { + if (match.index !== index) { + throw new TypeError('invalid parameter format') + } + + index += match[0].length + key = match[1].toLowerCase() + value = match[2] + + if (value.charCodeAt(0) === 0x22 /* " */) { + // remove quotes + value = value.slice(1, -1) + + // remove escapes + if (value.indexOf('\\') !== -1) { + value = value.replace(QESC_REGEXP, '$1') + } + } + + obj.parameters[key] = value + } + + if (index !== header.length) { + throw new TypeError('invalid parameter format') + } + } + + return obj +} + +/** + * Get content-type from req/res objects. + * + * @param {object} + * @return {Object} + * @private + */ + +function getcontenttype (obj) { + var header + + if (typeof obj.getHeader === 'function') { + // res-like + header = obj.getHeader('content-type') + } else if (typeof obj.headers === 'object') { + // req-like + header = obj.headers && obj.headers['content-type'] + } + + if (typeof header !== 'string') { + throw new TypeError('content-type header is missing from object') + } + + return header +} + +/** + * Quote a string if necessary. + * + * @param {string} val + * @return {string} + * @private + */ + +function qstring (val) { + var str = String(val) + + // no need to quote tokens + if (TOKEN_REGEXP.test(str)) { + return str + } + + if (str.length > 0 && !TEXT_REGEXP.test(str)) { + throw new TypeError('invalid parameter value') + } + + return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"' +} + +/** + * Class to represent a content type. + * @private + */ +function ContentType (type) { + this.parameters = Object.create(null) + this.type = type +} diff --git a/gun-server/node_modules/content-type/package.json b/gun-server/node_modules/content-type/package.json new file mode 100644 index 0000000..9db19f6 --- /dev/null +++ b/gun-server/node_modules/content-type/package.json @@ -0,0 +1,42 @@ +{ + "name": "content-type", + "description": "Create and parse HTTP Content-Type header", + "version": "1.0.5", + "author": "Douglas Christopher Wilson ", + "license": "MIT", + "keywords": [ + "content-type", + "http", + "req", + "res", + "rfc7231" + ], + "repository": "jshttp/content-type", + "devDependencies": { + "deep-equal": "1.0.1", + "eslint": "8.32.0", + "eslint-config-standard": "15.0.1", + "eslint-plugin-import": "2.27.5", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "6.1.1", + "eslint-plugin-standard": "4.1.0", + "mocha": "10.2.0", + "nyc": "15.1.0" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec --check-leaks --bail test/", + "test-ci": "nyc --reporter=lcovonly --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "version": "node scripts/version-history.js && git add HISTORY.md" + } +} diff --git a/gun-server/node_modules/cookie-signature/.npmignore b/gun-server/node_modules/cookie-signature/.npmignore new file mode 100644 index 0000000..f1250e5 --- /dev/null +++ b/gun-server/node_modules/cookie-signature/.npmignore @@ -0,0 +1,4 @@ +support +test +examples +*.sock diff --git a/gun-server/node_modules/cookie-signature/History.md b/gun-server/node_modules/cookie-signature/History.md new file mode 100644 index 0000000..78513cc --- /dev/null +++ b/gun-server/node_modules/cookie-signature/History.md @@ -0,0 +1,38 @@ +1.0.6 / 2015-02-03 +================== + +* use `npm test` instead of `make test` to run tests +* clearer assertion messages when checking input + + +1.0.5 / 2014-09-05 +================== + +* add license to package.json + +1.0.4 / 2014-06-25 +================== + + * corrected avoidance of timing attacks (thanks @tenbits!) + +1.0.3 / 2014-01-28 +================== + + * [incorrect] fix for timing attacks + +1.0.2 / 2014-01-28 +================== + + * fix missing repository warning + * fix typo in test + +1.0.1 / 2013-04-15 +================== + + * Revert "Changed underlying HMAC algo. to sha512." + * Revert "Fix for timing attacks on MAC verification." + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/gun-server/node_modules/cookie-signature/Readme.md b/gun-server/node_modules/cookie-signature/Readme.md new file mode 100644 index 0000000..2559e84 --- /dev/null +++ b/gun-server/node_modules/cookie-signature/Readme.md @@ -0,0 +1,42 @@ + +# cookie-signature + + Sign and unsign cookies. + +## Example + +```js +var cookie = require('cookie-signature'); + +var val = cookie.sign('hello', 'tobiiscool'); +val.should.equal('hello.DGDUkGlIkCzPz+C0B064FNgHdEjox7ch8tOBGslZ5QI'); + +var val = cookie.sign('hello', 'tobiiscool'); +cookie.unsign(val, 'tobiiscool').should.equal('hello'); +cookie.unsign(val, 'luna').should.be.false; +``` + +## License + +(The MIT License) + +Copyright (c) 2012 LearnBoost <tj@learnboost.com> + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/gun-server/node_modules/cookie-signature/index.js b/gun-server/node_modules/cookie-signature/index.js new file mode 100644 index 0000000..b8c9463 --- /dev/null +++ b/gun-server/node_modules/cookie-signature/index.js @@ -0,0 +1,51 @@ +/** + * Module dependencies. + */ + +var crypto = require('crypto'); + +/** + * Sign the given `val` with `secret`. + * + * @param {String} val + * @param {String} secret + * @return {String} + * @api private + */ + +exports.sign = function(val, secret){ + if ('string' != typeof val) throw new TypeError("Cookie value must be provided as a string."); + if ('string' != typeof secret) throw new TypeError("Secret string must be provided."); + return val + '.' + crypto + .createHmac('sha256', secret) + .update(val) + .digest('base64') + .replace(/\=+$/, ''); +}; + +/** + * Unsign and decode the given `val` with `secret`, + * returning `false` if the signature is invalid. + * + * @param {String} val + * @param {String} secret + * @return {String|Boolean} + * @api private + */ + +exports.unsign = function(val, secret){ + if ('string' != typeof val) throw new TypeError("Signed cookie string must be provided."); + if ('string' != typeof secret) throw new TypeError("Secret string must be provided."); + var str = val.slice(0, val.lastIndexOf('.')) + , mac = exports.sign(str, secret); + + return sha1(mac) == sha1(val) ? str : false; +}; + +/** + * Private + */ + +function sha1(str){ + return crypto.createHash('sha1').update(str).digest('hex'); +} diff --git a/gun-server/node_modules/cookie-signature/package.json b/gun-server/node_modules/cookie-signature/package.json new file mode 100644 index 0000000..29c4498 --- /dev/null +++ b/gun-server/node_modules/cookie-signature/package.json @@ -0,0 +1,18 @@ +{ + "name": "cookie-signature", + "version": "1.0.6", + "description": "Sign and unsign cookies", + "keywords": ["cookie", "sign", "unsign"], + "author": "TJ Holowaychuk ", + "license": "MIT", + "repository": { "type": "git", "url": "https://github.com/visionmedia/node-cookie-signature.git"}, + "dependencies": {}, + "devDependencies": { + "mocha": "*", + "should": "*" + }, + "scripts": { + "test": "mocha --require should --reporter spec" + }, + "main": "index" +} diff --git a/gun-server/node_modules/cookie/HISTORY.md b/gun-server/node_modules/cookie/HISTORY.md new file mode 100644 index 0000000..41ae4b0 --- /dev/null +++ b/gun-server/node_modules/cookie/HISTORY.md @@ -0,0 +1,147 @@ +0.6.0 / 2023-11-06 +================== + + * Add `partitioned` option + +0.5.0 / 2022-04-11 +================== + + * Add `priority` option + * Fix `expires` option to reject invalid dates + * perf: improve default decode speed + * perf: remove slow string split in parse + +0.4.2 / 2022-02-02 +================== + + * perf: read value only when assigning in parse + * perf: remove unnecessary regexp in parse + +0.4.1 / 2020-04-21 +================== + + * Fix `maxAge` option to reject invalid values + +0.4.0 / 2019-05-15 +================== + + * Add `SameSite=None` support + +0.3.1 / 2016-05-26 +================== + + * Fix `sameSite: true` to work with draft-7 clients + - `true` now sends `SameSite=Strict` instead of `SameSite` + +0.3.0 / 2016-05-26 +================== + + * Add `sameSite` option + - Replaces `firstPartyOnly` option, never implemented by browsers + * Improve error message when `encode` is not a function + * Improve error message when `expires` is not a `Date` + +0.2.4 / 2016-05-20 +================== + + * perf: enable strict mode + * perf: use for loop in parse + * perf: use string concatenation for serialization + +0.2.3 / 2015-10-25 +================== + + * Fix cookie `Max-Age` to never be a floating point number + +0.2.2 / 2015-09-17 +================== + + * Fix regression when setting empty cookie value + - Ease the new restriction, which is just basic header-level validation + * Fix typo in invalid value errors + +0.2.1 / 2015-09-17 +================== + + * Throw on invalid values provided to `serialize` + - Ensures the resulting string is a valid HTTP header value + +0.2.0 / 2015-08-13 +================== + + * Add `firstPartyOnly` option + * Throw better error for invalid argument to parse + * perf: hoist regular expression + +0.1.5 / 2015-09-17 +================== + + * Fix regression when setting empty cookie value + - Ease the new restriction, which is just basic header-level validation + * Fix typo in invalid value errors + +0.1.4 / 2015-09-17 +================== + + * Throw better error for invalid argument to parse + * Throw on invalid values provided to `serialize` + - Ensures the resulting string is a valid HTTP header value + +0.1.3 / 2015-05-19 +================== + + * Reduce the scope of try-catch deopt + * Remove argument reassignments + +0.1.2 / 2014-04-16 +================== + + * Remove unnecessary files from npm package + +0.1.1 / 2014-02-23 +================== + + * Fix bad parse when cookie value contained a comma + * Fix support for `maxAge` of `0` + +0.1.0 / 2013-05-01 +================== + + * Add `decode` option + * Add `encode` option + +0.0.6 / 2013-04-08 +================== + + * Ignore cookie parts missing `=` + +0.0.5 / 2012-10-29 +================== + + * Return raw cookie value if value unescape errors + +0.0.4 / 2012-06-21 +================== + + * Use encode/decodeURIComponent for cookie encoding/decoding + - Improve server/client interoperability + +0.0.3 / 2012-06-06 +================== + + * Only escape special characters per the cookie RFC + +0.0.2 / 2012-06-01 +================== + + * Fix `maxAge` option to not throw error + +0.0.1 / 2012-05-28 +================== + + * Add more tests + +0.0.0 / 2012-05-28 +================== + + * Initial release diff --git a/gun-server/node_modules/cookie/LICENSE b/gun-server/node_modules/cookie/LICENSE new file mode 100644 index 0000000..058b6b4 --- /dev/null +++ b/gun-server/node_modules/cookie/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2012-2014 Roman Shtylman +Copyright (c) 2015 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/gun-server/node_modules/cookie/README.md b/gun-server/node_modules/cookie/README.md new file mode 100644 index 0000000..71fdac1 --- /dev/null +++ b/gun-server/node_modules/cookie/README.md @@ -0,0 +1,317 @@ +# cookie + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][ci-image]][ci-url] +[![Coverage Status][coveralls-image]][coveralls-url] + +Basic HTTP cookie parser and serializer for HTTP servers. + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install cookie +``` + +## API + +```js +var cookie = require('cookie'); +``` + +### cookie.parse(str, options) + +Parse an HTTP `Cookie` header string and returning an object of all cookie name-value pairs. +The `str` argument is the string representing a `Cookie` header value and `options` is an +optional object containing additional parsing options. + +```js +var cookies = cookie.parse('foo=bar; equation=E%3Dmc%5E2'); +// { foo: 'bar', equation: 'E=mc^2' } +``` + +#### Options + +`cookie.parse` accepts these properties in the options object. + +##### decode + +Specifies a function that will be used to decode a cookie's value. Since the value of a cookie +has a limited character set (and must be a simple string), this function can be used to decode +a previously-encoded cookie value into a JavaScript string or other object. + +The default function is the global `decodeURIComponent`, which will decode any URL-encoded +sequences into their byte representations. + +**note** if an error is thrown from this function, the original, non-decoded cookie value will +be returned as the cookie's value. + +### cookie.serialize(name, value, options) + +Serialize a cookie name-value pair into a `Set-Cookie` header string. The `name` argument is the +name for the cookie, the `value` argument is the value to set the cookie to, and the `options` +argument is an optional object containing additional serialization options. + +```js +var setCookie = cookie.serialize('foo', 'bar'); +// foo=bar +``` + +#### Options + +`cookie.serialize` accepts these properties in the options object. + +##### domain + +Specifies the value for the [`Domain` `Set-Cookie` attribute][rfc-6265-5.2.3]. By default, no +domain is set, and most clients will consider the cookie to apply to only the current domain. + +##### encode + +Specifies a function that will be used to encode a cookie's value. Since value of a cookie +has a limited character set (and must be a simple string), this function can be used to encode +a value into a string suited for a cookie's value. + +The default function is the global `encodeURIComponent`, which will encode a JavaScript string +into UTF-8 byte sequences and then URL-encode any that fall outside of the cookie range. + +##### expires + +Specifies the `Date` object to be the value for the [`Expires` `Set-Cookie` attribute][rfc-6265-5.2.1]. +By default, no expiration is set, and most clients will consider this a "non-persistent cookie" and +will delete it on a condition like exiting a web browser application. + +**note** the [cookie storage model specification][rfc-6265-5.3] states that if both `expires` and +`maxAge` are set, then `maxAge` takes precedence, but it is possible not all clients by obey this, +so if both are set, they should point to the same date and time. + +##### httpOnly + +Specifies the `boolean` value for the [`HttpOnly` `Set-Cookie` attribute][rfc-6265-5.2.6]. When truthy, +the `HttpOnly` attribute is set, otherwise it is not. By default, the `HttpOnly` attribute is not set. + +**note** be careful when setting this to `true`, as compliant clients will not allow client-side +JavaScript to see the cookie in `document.cookie`. + +##### maxAge + +Specifies the `number` (in seconds) to be the value for the [`Max-Age` `Set-Cookie` attribute][rfc-6265-5.2.2]. +The given number will be converted to an integer by rounding down. By default, no maximum age is set. + +**note** the [cookie storage model specification][rfc-6265-5.3] states that if both `expires` and +`maxAge` are set, then `maxAge` takes precedence, but it is possible not all clients by obey this, +so if both are set, they should point to the same date and time. + +##### partitioned + +Specifies the `boolean` value for the [`Partitioned` `Set-Cookie`](rfc-cutler-httpbis-partitioned-cookies) +attribute. When truthy, the `Partitioned` attribute is set, otherwise it is not. By default, the +`Partitioned` attribute is not set. + +**note** This is an attribute that has not yet been fully standardized, and may change in the future. +This also means many clients may ignore this attribute until they understand it. + +More information about can be found in [the proposal](https://github.com/privacycg/CHIPS). + +##### path + +Specifies the value for the [`Path` `Set-Cookie` attribute][rfc-6265-5.2.4]. By default, the path +is considered the ["default path"][rfc-6265-5.1.4]. + +##### priority + +Specifies the `string` to be the value for the [`Priority` `Set-Cookie` attribute][rfc-west-cookie-priority-00-4.1]. + + - `'low'` will set the `Priority` attribute to `Low`. + - `'medium'` will set the `Priority` attribute to `Medium`, the default priority when not set. + - `'high'` will set the `Priority` attribute to `High`. + +More information about the different priority levels can be found in +[the specification][rfc-west-cookie-priority-00-4.1]. + +**note** This is an attribute that has not yet been fully standardized, and may change in the future. +This also means many clients may ignore this attribute until they understand it. + +##### sameSite + +Specifies the `boolean` or `string` to be the value for the [`SameSite` `Set-Cookie` attribute][rfc-6265bis-09-5.4.7]. + + - `true` will set the `SameSite` attribute to `Strict` for strict same site enforcement. + - `false` will not set the `SameSite` attribute. + - `'lax'` will set the `SameSite` attribute to `Lax` for lax same site enforcement. + - `'none'` will set the `SameSite` attribute to `None` for an explicit cross-site cookie. + - `'strict'` will set the `SameSite` attribute to `Strict` for strict same site enforcement. + +More information about the different enforcement levels can be found in +[the specification][rfc-6265bis-09-5.4.7]. + +**note** This is an attribute that has not yet been fully standardized, and may change in the future. +This also means many clients may ignore this attribute until they understand it. + +##### secure + +Specifies the `boolean` value for the [`Secure` `Set-Cookie` attribute][rfc-6265-5.2.5]. When truthy, +the `Secure` attribute is set, otherwise it is not. By default, the `Secure` attribute is not set. + +**note** be careful when setting this to `true`, as compliant clients will not send the cookie back to +the server in the future if the browser does not have an HTTPS connection. + +## Example + +The following example uses this module in conjunction with the Node.js core HTTP server +to prompt a user for their name and display it back on future visits. + +```js +var cookie = require('cookie'); +var escapeHtml = require('escape-html'); +var http = require('http'); +var url = require('url'); + +function onRequest(req, res) { + // Parse the query string + var query = url.parse(req.url, true, true).query; + + if (query && query.name) { + // Set a new cookie with the name + res.setHeader('Set-Cookie', cookie.serialize('name', String(query.name), { + httpOnly: true, + maxAge: 60 * 60 * 24 * 7 // 1 week + })); + + // Redirect back after setting cookie + res.statusCode = 302; + res.setHeader('Location', req.headers.referer || '/'); + res.end(); + return; + } + + // Parse the cookies on the request + var cookies = cookie.parse(req.headers.cookie || ''); + + // Get the visitor name set in the cookie + var name = cookies.name; + + res.setHeader('Content-Type', 'text/html; charset=UTF-8'); + + if (name) { + res.write('

      Welcome back, ' + escapeHtml(name) + '!

      '); + } else { + res.write('

      Hello, new visitor!

      '); + } + + res.write('
      '); + res.write(' '); + res.end('
      '); +} + +http.createServer(onRequest).listen(3000); +``` + +## Testing + +```sh +$ npm test +``` + +## Benchmark + +``` +$ npm run bench + +> cookie@0.5.0 bench +> node benchmark/index.js + + node@18.18.2 + acorn@8.10.0 + ada@2.6.0 + ares@1.19.1 + brotli@1.0.9 + cldr@43.1 + icu@73.2 + llhttp@6.0.11 + modules@108 + napi@9 + nghttp2@1.57.0 + nghttp3@0.7.0 + ngtcp2@0.8.1 + openssl@3.0.10+quic + simdutf@3.2.14 + tz@2023c + undici@5.26.3 + unicode@15.0 + uv@1.44.2 + uvwasi@0.0.18 + v8@10.2.154.26-node.26 + zlib@1.2.13.1-motley + +> node benchmark/parse-top.js + + cookie.parse - top sites + + 14 tests completed. + + parse accounts.google.com x 2,588,913 ops/sec ±0.74% (186 runs sampled) + parse apple.com x 2,370,002 ops/sec ±0.69% (186 runs sampled) + parse cloudflare.com x 2,213,102 ops/sec ±0.88% (188 runs sampled) + parse docs.google.com x 2,194,157 ops/sec ±1.03% (184 runs sampled) + parse drive.google.com x 2,265,084 ops/sec ±0.79% (187 runs sampled) + parse en.wikipedia.org x 457,099 ops/sec ±0.81% (186 runs sampled) + parse linkedin.com x 504,407 ops/sec ±0.89% (186 runs sampled) + parse maps.google.com x 1,230,959 ops/sec ±0.98% (186 runs sampled) + parse microsoft.com x 926,294 ops/sec ±0.88% (184 runs sampled) + parse play.google.com x 2,311,338 ops/sec ±0.83% (185 runs sampled) + parse support.google.com x 1,508,850 ops/sec ±0.86% (186 runs sampled) + parse www.google.com x 1,022,582 ops/sec ±1.32% (182 runs sampled) + parse youtu.be x 332,136 ops/sec ±1.02% (185 runs sampled) + parse youtube.com x 323,833 ops/sec ±0.77% (183 runs sampled) + +> node benchmark/parse.js + + cookie.parse - generic + + 6 tests completed. + + simple x 3,214,032 ops/sec ±1.61% (183 runs sampled) + decode x 587,237 ops/sec ±1.16% (187 runs sampled) + unquote x 2,954,618 ops/sec ±1.35% (183 runs sampled) + duplicates x 857,008 ops/sec ±0.89% (187 runs sampled) + 10 cookies x 292,133 ops/sec ±0.89% (187 runs sampled) + 100 cookies x 22,610 ops/sec ±0.68% (187 runs sampled) +``` + +## References + +- [RFC 6265: HTTP State Management Mechanism][rfc-6265] +- [Same-site Cookies][rfc-6265bis-09-5.4.7] + +[rfc-cutler-httpbis-partitioned-cookies]: https://tools.ietf.org/html/draft-cutler-httpbis-partitioned-cookies/ +[rfc-west-cookie-priority-00-4.1]: https://tools.ietf.org/html/draft-west-cookie-priority-00#section-4.1 +[rfc-6265bis-09-5.4.7]: https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-09#section-5.4.7 +[rfc-6265]: https://tools.ietf.org/html/rfc6265 +[rfc-6265-5.1.4]: https://tools.ietf.org/html/rfc6265#section-5.1.4 +[rfc-6265-5.2.1]: https://tools.ietf.org/html/rfc6265#section-5.2.1 +[rfc-6265-5.2.2]: https://tools.ietf.org/html/rfc6265#section-5.2.2 +[rfc-6265-5.2.3]: https://tools.ietf.org/html/rfc6265#section-5.2.3 +[rfc-6265-5.2.4]: https://tools.ietf.org/html/rfc6265#section-5.2.4 +[rfc-6265-5.2.5]: https://tools.ietf.org/html/rfc6265#section-5.2.5 +[rfc-6265-5.2.6]: https://tools.ietf.org/html/rfc6265#section-5.2.6 +[rfc-6265-5.3]: https://tools.ietf.org/html/rfc6265#section-5.3 + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/jshttp/cookie/master?label=ci +[ci-url]: https://github.com/jshttp/cookie/actions/workflows/ci.yml +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/cookie/master +[coveralls-url]: https://coveralls.io/r/jshttp/cookie?branch=master +[node-image]: https://badgen.net/npm/node/cookie +[node-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/cookie +[npm-url]: https://npmjs.org/package/cookie +[npm-version-image]: https://badgen.net/npm/v/cookie diff --git a/gun-server/node_modules/cookie/SECURITY.md b/gun-server/node_modules/cookie/SECURITY.md new file mode 100644 index 0000000..fd4a6c5 --- /dev/null +++ b/gun-server/node_modules/cookie/SECURITY.md @@ -0,0 +1,25 @@ +# Security Policies and Procedures + +## Reporting a Bug + +The `cookie` team and community take all security bugs seriously. Thank +you for improving the security of the project. We appreciate your efforts and +responsible disclosure and will make every effort to acknowledge your +contributions. + +Report security bugs by emailing the current owner(s) of `cookie`. This +information can be found in the npm registry using the command +`npm owner ls cookie`. +If unsure or unable to get the information from the above, open an issue +in the [project issue tracker](https://github.com/jshttp/cookie/issues) +asking for the current contact information. + +To ensure the timely response to your report, please ensure that the entirety +of the report is contained within the email body and not solely behind a web +link or an attachment. + +At least one owner will acknowledge your email within 48 hours, and will send a +more detailed response within 48 hours indicating the next steps in handling +your report. After the initial reply to your report, the owners will +endeavor to keep you informed of the progress towards a fix and full +announcement, and may ask for additional information or guidance. diff --git a/gun-server/node_modules/cookie/index.js b/gun-server/node_modules/cookie/index.js new file mode 100644 index 0000000..03d4c38 --- /dev/null +++ b/gun-server/node_modules/cookie/index.js @@ -0,0 +1,274 @@ +/*! + * cookie + * Copyright(c) 2012-2014 Roman Shtylman + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +exports.parse = parse; +exports.serialize = serialize; + +/** + * Module variables. + * @private + */ + +var __toString = Object.prototype.toString + +/** + * RegExp to match field-content in RFC 7230 sec 3.2 + * + * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] + * field-vchar = VCHAR / obs-text + * obs-text = %x80-FF + */ + +var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/; + +/** + * Parse a cookie header. + * + * Parse the given cookie header string into an object + * The object has the various cookies as keys(names) => values + * + * @param {string} str + * @param {object} [options] + * @return {object} + * @public + */ + +function parse(str, options) { + if (typeof str !== 'string') { + throw new TypeError('argument str must be a string'); + } + + var obj = {} + var opt = options || {}; + var dec = opt.decode || decode; + + var index = 0 + while (index < str.length) { + var eqIdx = str.indexOf('=', index) + + // no more cookie pairs + if (eqIdx === -1) { + break + } + + var endIdx = str.indexOf(';', index) + + if (endIdx === -1) { + endIdx = str.length + } else if (endIdx < eqIdx) { + // backtrack on prior semicolon + index = str.lastIndexOf(';', eqIdx - 1) + 1 + continue + } + + var key = str.slice(index, eqIdx).trim() + + // only assign once + if (undefined === obj[key]) { + var val = str.slice(eqIdx + 1, endIdx).trim() + + // quoted values + if (val.charCodeAt(0) === 0x22) { + val = val.slice(1, -1) + } + + obj[key] = tryDecode(val, dec); + } + + index = endIdx + 1 + } + + return obj; +} + +/** + * Serialize data into a cookie header. + * + * Serialize the a name value pair into a cookie string suitable for + * http headers. An optional options object specified cookie parameters. + * + * serialize('foo', 'bar', { httpOnly: true }) + * => "foo=bar; httpOnly" + * + * @param {string} name + * @param {string} val + * @param {object} [options] + * @return {string} + * @public + */ + +function serialize(name, val, options) { + var opt = options || {}; + var enc = opt.encode || encode; + + if (typeof enc !== 'function') { + throw new TypeError('option encode is invalid'); + } + + if (!fieldContentRegExp.test(name)) { + throw new TypeError('argument name is invalid'); + } + + var value = enc(val); + + if (value && !fieldContentRegExp.test(value)) { + throw new TypeError('argument val is invalid'); + } + + var str = name + '=' + value; + + if (null != opt.maxAge) { + var maxAge = opt.maxAge - 0; + + if (isNaN(maxAge) || !isFinite(maxAge)) { + throw new TypeError('option maxAge is invalid') + } + + str += '; Max-Age=' + Math.floor(maxAge); + } + + if (opt.domain) { + if (!fieldContentRegExp.test(opt.domain)) { + throw new TypeError('option domain is invalid'); + } + + str += '; Domain=' + opt.domain; + } + + if (opt.path) { + if (!fieldContentRegExp.test(opt.path)) { + throw new TypeError('option path is invalid'); + } + + str += '; Path=' + opt.path; + } + + if (opt.expires) { + var expires = opt.expires + + if (!isDate(expires) || isNaN(expires.valueOf())) { + throw new TypeError('option expires is invalid'); + } + + str += '; Expires=' + expires.toUTCString() + } + + if (opt.httpOnly) { + str += '; HttpOnly'; + } + + if (opt.secure) { + str += '; Secure'; + } + + if (opt.partitioned) { + str += '; Partitioned' + } + + if (opt.priority) { + var priority = typeof opt.priority === 'string' + ? opt.priority.toLowerCase() + : opt.priority + + switch (priority) { + case 'low': + str += '; Priority=Low' + break + case 'medium': + str += '; Priority=Medium' + break + case 'high': + str += '; Priority=High' + break + default: + throw new TypeError('option priority is invalid') + } + } + + if (opt.sameSite) { + var sameSite = typeof opt.sameSite === 'string' + ? opt.sameSite.toLowerCase() : opt.sameSite; + + switch (sameSite) { + case true: + str += '; SameSite=Strict'; + break; + case 'lax': + str += '; SameSite=Lax'; + break; + case 'strict': + str += '; SameSite=Strict'; + break; + case 'none': + str += '; SameSite=None'; + break; + default: + throw new TypeError('option sameSite is invalid'); + } + } + + return str; +} + +/** + * URL-decode string value. Optimized to skip native call when no %. + * + * @param {string} str + * @returns {string} + */ + +function decode (str) { + return str.indexOf('%') !== -1 + ? decodeURIComponent(str) + : str +} + +/** + * URL-encode value. + * + * @param {string} val + * @returns {string} + */ + +function encode (val) { + return encodeURIComponent(val) +} + +/** + * Determine if value is a Date. + * + * @param {*} val + * @private + */ + +function isDate (val) { + return __toString.call(val) === '[object Date]' || + val instanceof Date +} + +/** + * Try decoding a string using a decoding function. + * + * @param {string} str + * @param {function} decode + * @private + */ + +function tryDecode(str, decode) { + try { + return decode(str); + } catch (e) { + return str; + } +} diff --git a/gun-server/node_modules/cookie/package.json b/gun-server/node_modules/cookie/package.json new file mode 100644 index 0000000..0c3f006 --- /dev/null +++ b/gun-server/node_modules/cookie/package.json @@ -0,0 +1,44 @@ +{ + "name": "cookie", + "description": "HTTP server cookie parsing and serialization", + "version": "0.6.0", + "author": "Roman Shtylman ", + "contributors": [ + "Douglas Christopher Wilson " + ], + "license": "MIT", + "keywords": [ + "cookie", + "cookies" + ], + "repository": "jshttp/cookie", + "devDependencies": { + "beautify-benchmark": "0.2.4", + "benchmark": "2.1.4", + "eslint": "8.53.0", + "eslint-plugin-markdown": "3.0.1", + "mocha": "10.2.0", + "nyc": "15.1.0", + "safe-buffer": "5.2.1", + "top-sites": "1.1.194" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "SECURITY.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "bench": "node benchmark/index.js", + "lint": "eslint .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "update-bench": "node scripts/update-benchmark.js", + "version": "node scripts/version-history.js && git add HISTORY.md" + } +} diff --git a/gun-server/node_modules/debug/.coveralls.yml b/gun-server/node_modules/debug/.coveralls.yml new file mode 100644 index 0000000..20a7068 --- /dev/null +++ b/gun-server/node_modules/debug/.coveralls.yml @@ -0,0 +1 @@ +repo_token: SIAeZjKYlHK74rbcFvNHMUzjRiMpflxve diff --git a/gun-server/node_modules/debug/.eslintrc b/gun-server/node_modules/debug/.eslintrc new file mode 100644 index 0000000..8a37ae2 --- /dev/null +++ b/gun-server/node_modules/debug/.eslintrc @@ -0,0 +1,11 @@ +{ + "env": { + "browser": true, + "node": true + }, + "rules": { + "no-console": 0, + "no-empty": [1, { "allowEmptyCatch": true }] + }, + "extends": "eslint:recommended" +} diff --git a/gun-server/node_modules/debug/.npmignore b/gun-server/node_modules/debug/.npmignore new file mode 100644 index 0000000..5f60eec --- /dev/null +++ b/gun-server/node_modules/debug/.npmignore @@ -0,0 +1,9 @@ +support +test +examples +example +*.sock +dist +yarn.lock +coverage +bower.json diff --git a/gun-server/node_modules/debug/.travis.yml b/gun-server/node_modules/debug/.travis.yml new file mode 100644 index 0000000..6c6090c --- /dev/null +++ b/gun-server/node_modules/debug/.travis.yml @@ -0,0 +1,14 @@ + +language: node_js +node_js: + - "6" + - "5" + - "4" + +install: + - make node_modules + +script: + - make lint + - make test + - make coveralls diff --git a/gun-server/node_modules/debug/CHANGELOG.md b/gun-server/node_modules/debug/CHANGELOG.md new file mode 100644 index 0000000..eadaa18 --- /dev/null +++ b/gun-server/node_modules/debug/CHANGELOG.md @@ -0,0 +1,362 @@ + +2.6.9 / 2017-09-22 +================== + + * remove ReDoS regexp in %o formatter (#504) + +2.6.8 / 2017-05-18 +================== + + * Fix: Check for undefined on browser globals (#462, @marbemac) + +2.6.7 / 2017-05-16 +================== + + * Fix: Update ms to 2.0.0 to fix regular expression denial of service vulnerability (#458, @hubdotcom) + * Fix: Inline extend function in node implementation (#452, @dougwilson) + * Docs: Fix typo (#455, @msasad) + +2.6.5 / 2017-04-27 +================== + + * Fix: null reference check on window.documentElement.style.WebkitAppearance (#447, @thebigredgeek) + * Misc: clean up browser reference checks (#447, @thebigredgeek) + * Misc: add npm-debug.log to .gitignore (@thebigredgeek) + + +2.6.4 / 2017-04-20 +================== + + * Fix: bug that would occure if process.env.DEBUG is a non-string value. (#444, @LucianBuzzo) + * Chore: ignore bower.json in npm installations. (#437, @joaovieira) + * Misc: update "ms" to v0.7.3 (@tootallnate) + +2.6.3 / 2017-03-13 +================== + + * Fix: Electron reference to `process.env.DEBUG` (#431, @paulcbetts) + * Docs: Changelog fix (@thebigredgeek) + +2.6.2 / 2017-03-10 +================== + + * Fix: DEBUG_MAX_ARRAY_LENGTH (#420, @slavaGanzin) + * Docs: Add backers and sponsors from Open Collective (#422, @piamancini) + * Docs: Add Slackin invite badge (@tootallnate) + +2.6.1 / 2017-02-10 +================== + + * Fix: Module's `export default` syntax fix for IE8 `Expected identifier` error + * Fix: Whitelist DEBUG_FD for values 1 and 2 only (#415, @pi0) + * Fix: IE8 "Expected identifier" error (#414, @vgoma) + * Fix: Namespaces would not disable once enabled (#409, @musikov) + +2.6.0 / 2016-12-28 +================== + + * Fix: added better null pointer checks for browser useColors (@thebigredgeek) + * Improvement: removed explicit `window.debug` export (#404, @tootallnate) + * Improvement: deprecated `DEBUG_FD` environment variable (#405, @tootallnate) + +2.5.2 / 2016-12-25 +================== + + * Fix: reference error on window within webworkers (#393, @KlausTrainer) + * Docs: fixed README typo (#391, @lurch) + * Docs: added notice about v3 api discussion (@thebigredgeek) + +2.5.1 / 2016-12-20 +================== + + * Fix: babel-core compatibility + +2.5.0 / 2016-12-20 +================== + + * Fix: wrong reference in bower file (@thebigredgeek) + * Fix: webworker compatibility (@thebigredgeek) + * Fix: output formatting issue (#388, @kribblo) + * Fix: babel-loader compatibility (#383, @escwald) + * Misc: removed built asset from repo and publications (@thebigredgeek) + * Misc: moved source files to /src (#378, @yamikuronue) + * Test: added karma integration and replaced babel with browserify for browser tests (#378, @yamikuronue) + * Test: coveralls integration (#378, @yamikuronue) + * Docs: simplified language in the opening paragraph (#373, @yamikuronue) + +2.4.5 / 2016-12-17 +================== + + * Fix: `navigator` undefined in Rhino (#376, @jochenberger) + * Fix: custom log function (#379, @hsiliev) + * Improvement: bit of cleanup + linting fixes (@thebigredgeek) + * Improvement: rm non-maintainted `dist/` dir (#375, @freewil) + * Docs: simplified language in the opening paragraph. (#373, @yamikuronue) + +2.4.4 / 2016-12-14 +================== + + * Fix: work around debug being loaded in preload scripts for electron (#368, @paulcbetts) + +2.4.3 / 2016-12-14 +================== + + * Fix: navigation.userAgent error for react native (#364, @escwald) + +2.4.2 / 2016-12-14 +================== + + * Fix: browser colors (#367, @tootallnate) + * Misc: travis ci integration (@thebigredgeek) + * Misc: added linting and testing boilerplate with sanity check (@thebigredgeek) + +2.4.1 / 2016-12-13 +================== + + * Fix: typo that broke the package (#356) + +2.4.0 / 2016-12-13 +================== + + * Fix: bower.json references unbuilt src entry point (#342, @justmatt) + * Fix: revert "handle regex special characters" (@tootallnate) + * Feature: configurable util.inspect()`options for NodeJS (#327, @tootallnate) + * Feature: %O`(big O) pretty-prints objects (#322, @tootallnate) + * Improvement: allow colors in workers (#335, @botverse) + * Improvement: use same color for same namespace. (#338, @lchenay) + +2.3.3 / 2016-11-09 +================== + + * Fix: Catch `JSON.stringify()` errors (#195, Jovan Alleyne) + * Fix: Returning `localStorage` saved values (#331, Levi Thomason) + * Improvement: Don't create an empty object when no `process` (Nathan Rajlich) + +2.3.2 / 2016-11-09 +================== + + * Fix: be super-safe in index.js as well (@TooTallNate) + * Fix: should check whether process exists (Tom Newby) + +2.3.1 / 2016-11-09 +================== + + * Fix: Added electron compatibility (#324, @paulcbetts) + * Improvement: Added performance optimizations (@tootallnate) + * Readme: Corrected PowerShell environment variable example (#252, @gimre) + * Misc: Removed yarn lock file from source control (#321, @fengmk2) + +2.3.0 / 2016-11-07 +================== + + * Fix: Consistent placement of ms diff at end of output (#215, @gorangajic) + * Fix: Escaping of regex special characters in namespace strings (#250, @zacronos) + * Fix: Fixed bug causing crash on react-native (#282, @vkarpov15) + * Feature: Enabled ES6+ compatible import via default export (#212 @bucaran) + * Feature: Added %O formatter to reflect Chrome's console.log capability (#279, @oncletom) + * Package: Update "ms" to 0.7.2 (#315, @DevSide) + * Package: removed superfluous version property from bower.json (#207 @kkirsche) + * Readme: fix USE_COLORS to DEBUG_COLORS + * Readme: Doc fixes for format string sugar (#269, @mlucool) + * Readme: Updated docs for DEBUG_FD and DEBUG_COLORS environment variables (#232, @mattlyons0) + * Readme: doc fixes for PowerShell (#271 #243, @exoticknight @unreadable) + * Readme: better docs for browser support (#224, @matthewmueller) + * Tooling: Added yarn integration for development (#317, @thebigredgeek) + * Misc: Renamed History.md to CHANGELOG.md (@thebigredgeek) + * Misc: Added license file (#226 #274, @CantemoInternal @sdaitzman) + * Misc: Updated contributors (@thebigredgeek) + +2.2.0 / 2015-05-09 +================== + + * package: update "ms" to v0.7.1 (#202, @dougwilson) + * README: add logging to file example (#193, @DanielOchoa) + * README: fixed a typo (#191, @amir-s) + * browser: expose `storage` (#190, @stephenmathieson) + * Makefile: add a `distclean` target (#189, @stephenmathieson) + +2.1.3 / 2015-03-13 +================== + + * Updated stdout/stderr example (#186) + * Updated example/stdout.js to match debug current behaviour + * Renamed example/stderr.js to stdout.js + * Update Readme.md (#184) + * replace high intensity foreground color for bold (#182, #183) + +2.1.2 / 2015-03-01 +================== + + * dist: recompile + * update "ms" to v0.7.0 + * package: update "browserify" to v9.0.3 + * component: fix "ms.js" repo location + * changed bower package name + * updated documentation about using debug in a browser + * fix: security error on safari (#167, #168, @yields) + +2.1.1 / 2014-12-29 +================== + + * browser: use `typeof` to check for `console` existence + * browser: check for `console.log` truthiness (fix IE 8/9) + * browser: add support for Chrome apps + * Readme: added Windows usage remarks + * Add `bower.json` to properly support bower install + +2.1.0 / 2014-10-15 +================== + + * node: implement `DEBUG_FD` env variable support + * package: update "browserify" to v6.1.0 + * package: add "license" field to package.json (#135, @panuhorsmalahti) + +2.0.0 / 2014-09-01 +================== + + * package: update "browserify" to v5.11.0 + * node: use stderr rather than stdout for logging (#29, @stephenmathieson) + +1.0.4 / 2014-07-15 +================== + + * dist: recompile + * example: remove `console.info()` log usage + * example: add "Content-Type" UTF-8 header to browser example + * browser: place %c marker after the space character + * browser: reset the "content" color via `color: inherit` + * browser: add colors support for Firefox >= v31 + * debug: prefer an instance `log()` function over the global one (#119) + * Readme: update documentation about styled console logs for FF v31 (#116, @wryk) + +1.0.3 / 2014-07-09 +================== + + * Add support for multiple wildcards in namespaces (#122, @seegno) + * browser: fix lint + +1.0.2 / 2014-06-10 +================== + + * browser: update color palette (#113, @gscottolson) + * common: make console logging function configurable (#108, @timoxley) + * node: fix %o colors on old node <= 0.8.x + * Makefile: find node path using shell/which (#109, @timoxley) + +1.0.1 / 2014-06-06 +================== + + * browser: use `removeItem()` to clear localStorage + * browser, node: don't set DEBUG if namespaces is undefined (#107, @leedm777) + * package: add "contributors" section + * node: fix comment typo + * README: list authors + +1.0.0 / 2014-06-04 +================== + + * make ms diff be global, not be scope + * debug: ignore empty strings in enable() + * node: make DEBUG_COLORS able to disable coloring + * *: export the `colors` array + * npmignore: don't publish the `dist` dir + * Makefile: refactor to use browserify + * package: add "browserify" as a dev dependency + * Readme: add Web Inspector Colors section + * node: reset terminal color for the debug content + * node: map "%o" to `util.inspect()` + * browser: map "%j" to `JSON.stringify()` + * debug: add custom "formatters" + * debug: use "ms" module for humanizing the diff + * Readme: add "bash" syntax highlighting + * browser: add Firebug color support + * browser: add colors for WebKit browsers + * node: apply log to `console` + * rewrite: abstract common logic for Node & browsers + * add .jshintrc file + +0.8.1 / 2014-04-14 +================== + + * package: re-add the "component" section + +0.8.0 / 2014-03-30 +================== + + * add `enable()` method for nodejs. Closes #27 + * change from stderr to stdout + * remove unnecessary index.js file + +0.7.4 / 2013-11-13 +================== + + * remove "browserify" key from package.json (fixes something in browserify) + +0.7.3 / 2013-10-30 +================== + + * fix: catch localStorage security error when cookies are blocked (Chrome) + * add debug(err) support. Closes #46 + * add .browser prop to package.json. Closes #42 + +0.7.2 / 2013-02-06 +================== + + * fix package.json + * fix: Mobile Safari (private mode) is broken with debug + * fix: Use unicode to send escape character to shell instead of octal to work with strict mode javascript + +0.7.1 / 2013-02-05 +================== + + * add repository URL to package.json + * add DEBUG_COLORED to force colored output + * add browserify support + * fix component. Closes #24 + +0.7.0 / 2012-05-04 +================== + + * Added .component to package.json + * Added debug.component.js build + +0.6.0 / 2012-03-16 +================== + + * Added support for "-" prefix in DEBUG [Vinay Pulim] + * Added `.enabled` flag to the node version [TooTallNate] + +0.5.0 / 2012-02-02 +================== + + * Added: humanize diffs. Closes #8 + * Added `debug.disable()` to the CS variant + * Removed padding. Closes #10 + * Fixed: persist client-side variant again. Closes #9 + +0.4.0 / 2012-02-01 +================== + + * Added browser variant support for older browsers [TooTallNate] + * Added `debug.enable('project:*')` to browser variant [TooTallNate] + * Added padding to diff (moved it to the right) + +0.3.0 / 2012-01-26 +================== + + * Added millisecond diff when isatty, otherwise UTC string + +0.2.0 / 2012-01-22 +================== + + * Added wildcard support + +0.1.0 / 2011-12-02 +================== + + * Added: remove colors unless stderr isatty [TooTallNate] + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/gun-server/node_modules/debug/LICENSE b/gun-server/node_modules/debug/LICENSE new file mode 100644 index 0000000..658c933 --- /dev/null +++ b/gun-server/node_modules/debug/LICENSE @@ -0,0 +1,19 @@ +(The MIT License) + +Copyright (c) 2014 TJ Holowaychuk + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software +and associated documentation files (the 'Software'), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial +portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT +LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/gun-server/node_modules/debug/Makefile b/gun-server/node_modules/debug/Makefile new file mode 100644 index 0000000..584da8b --- /dev/null +++ b/gun-server/node_modules/debug/Makefile @@ -0,0 +1,50 @@ +# get Makefile directory name: http://stackoverflow.com/a/5982798/376773 +THIS_MAKEFILE_PATH:=$(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST)) +THIS_DIR:=$(shell cd $(dir $(THIS_MAKEFILE_PATH));pwd) + +# BIN directory +BIN := $(THIS_DIR)/node_modules/.bin + +# Path +PATH := node_modules/.bin:$(PATH) +SHELL := /bin/bash + +# applications +NODE ?= $(shell which node) +YARN ?= $(shell which yarn) +PKG ?= $(if $(YARN),$(YARN),$(NODE) $(shell which npm)) +BROWSERIFY ?= $(NODE) $(BIN)/browserify + +.FORCE: + +install: node_modules + +node_modules: package.json + @NODE_ENV= $(PKG) install + @touch node_modules + +lint: .FORCE + eslint browser.js debug.js index.js node.js + +test-node: .FORCE + istanbul cover node_modules/mocha/bin/_mocha -- test/**.js + +test-browser: .FORCE + mkdir -p dist + + @$(BROWSERIFY) \ + --standalone debug \ + . > dist/debug.js + + karma start --single-run + rimraf dist + +test: .FORCE + concurrently \ + "make test-node" \ + "make test-browser" + +coveralls: + cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js + +.PHONY: all install clean distclean diff --git a/gun-server/node_modules/debug/README.md b/gun-server/node_modules/debug/README.md new file mode 100644 index 0000000..f67be6b --- /dev/null +++ b/gun-server/node_modules/debug/README.md @@ -0,0 +1,312 @@ +# debug +[![Build Status](https://travis-ci.org/visionmedia/debug.svg?branch=master)](https://travis-ci.org/visionmedia/debug) [![Coverage Status](https://coveralls.io/repos/github/visionmedia/debug/badge.svg?branch=master)](https://coveralls.io/github/visionmedia/debug?branch=master) [![Slack](https://visionmedia-community-slackin.now.sh/badge.svg)](https://visionmedia-community-slackin.now.sh/) [![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers) +[![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors) + + + +A tiny node.js debugging utility modelled after node core's debugging technique. + +**Discussion around the V3 API is under way [here](https://github.com/visionmedia/debug/issues/370)** + +## Installation + +```bash +$ npm install debug +``` + +## Usage + +`debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole. + +Example _app.js_: + +```js +var debug = require('debug')('http') + , http = require('http') + , name = 'My App'; + +// fake app + +debug('booting %s', name); + +http.createServer(function(req, res){ + debug(req.method + ' ' + req.url); + res.end('hello\n'); +}).listen(3000, function(){ + debug('listening'); +}); + +// fake worker of some kind + +require('./worker'); +``` + +Example _worker.js_: + +```js +var debug = require('debug')('worker'); + +setInterval(function(){ + debug('doing some work'); +}, 1000); +``` + + The __DEBUG__ environment variable is then used to enable these based on space or comma-delimited names. Here are some examples: + + ![debug http and worker](http://f.cl.ly/items/18471z1H402O24072r1J/Screenshot.png) + + ![debug worker](http://f.cl.ly/items/1X413v1a3M0d3C2c1E0i/Screenshot.png) + +#### Windows note + + On Windows the environment variable is set using the `set` command. + + ```cmd + set DEBUG=*,-not_this + ``` + + Note that PowerShell uses different syntax to set environment variables. + + ```cmd + $env:DEBUG = "*,-not_this" + ``` + +Then, run the program to be debugged as usual. + +## Millisecond diff + + When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. + + ![](http://f.cl.ly/items/2i3h1d3t121M2Z1A3Q0N/Screenshot.png) + + When stdout is not a TTY, `Date#toUTCString()` is used, making it more useful for logging the debug information as shown below: + + ![](http://f.cl.ly/items/112H3i0e0o0P0a2Q2r11/Screenshot.png) + +## Conventions + + If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". + +## Wildcards + + The `*` character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. + + You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=*,-connect:*` would include all debuggers except those starting with "connect:". + +## Environment Variables + + When running through Node.js, you can set a few environment variables that will + change the behavior of the debug logging: + +| Name | Purpose | +|-----------|-------------------------------------------------| +| `DEBUG` | Enables/disables specific debugging namespaces. | +| `DEBUG_COLORS`| Whether or not to use colors in the debug output. | +| `DEBUG_DEPTH` | Object inspection depth. | +| `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. | + + + __Note:__ The environment variables beginning with `DEBUG_` end up being + converted into an Options object that gets used with `%o`/`%O` formatters. + See the Node.js documentation for + [`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) + for the complete list. + +## Formatters + + + Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. Below are the officially supported formatters: + +| Formatter | Representation | +|-----------|----------------| +| `%O` | Pretty-print an Object on multiple lines. | +| `%o` | Pretty-print an Object all on a single line. | +| `%s` | String. | +| `%d` | Number (both integer and float). | +| `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | +| `%%` | Single percent sign ('%'). This does not consume an argument. | + +### Custom formatters + + You can add custom formatters by extending the `debug.formatters` object. For example, if you wanted to add support for rendering a Buffer as hex with `%h`, you could do something like: + +```js +const createDebug = require('debug') +createDebug.formatters.h = (v) => { + return v.toString('hex') +} + +// …elsewhere +const debug = createDebug('foo') +debug('this is hex: %h', new Buffer('hello world')) +// foo this is hex: 68656c6c6f20776f726c6421 +0ms +``` + +## Browser support + You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify), + or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest), + if you don't want to build it yourself. + + Debug's enable state is currently persisted by `localStorage`. + Consider the situation shown below where you have `worker:a` and `worker:b`, + and wish to debug both. You can enable this using `localStorage.debug`: + +```js +localStorage.debug = 'worker:*' +``` + +And then refresh the page. + +```js +a = debug('worker:a'); +b = debug('worker:b'); + +setInterval(function(){ + a('doing some work'); +}, 1000); + +setInterval(function(){ + b('doing some work'); +}, 1200); +``` + +#### Web Inspector Colors + + Colors are also enabled on "Web Inspectors" that understand the `%c` formatting + option. These are WebKit web inspectors, Firefox ([since version + 31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/)) + and the Firebug plugin for Firefox (any version). + + Colored output looks something like: + + ![](https://cloud.githubusercontent.com/assets/71256/3139768/b98c5fd8-e8ef-11e3-862a-f7253b6f47c6.png) + + +## Output streams + + By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method: + +Example _stdout.js_: + +```js +var debug = require('debug'); +var error = debug('app:error'); + +// by default stderr is used +error('goes to stderr!'); + +var log = debug('app:log'); +// set this namespace to log via console.log +log.log = console.log.bind(console); // don't forget to bind to console! +log('goes to stdout'); +error('still goes to stderr!'); + +// set all output to go via console.info +// overrides all per-namespace log settings +debug.log = console.info.bind(console); +error('now goes to stdout via console.info'); +log('still goes to stdout, but via console.info now'); +``` + + +## Authors + + - TJ Holowaychuk + - Nathan Rajlich + - Andrew Rhyne + +## Backers + +Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +## Sponsors + +Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +## License + +(The MIT License) + +Copyright (c) 2014-2016 TJ Holowaychuk <tj@vision-media.ca> + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/gun-server/node_modules/debug/component.json b/gun-server/node_modules/debug/component.json new file mode 100644 index 0000000..9de2641 --- /dev/null +++ b/gun-server/node_modules/debug/component.json @@ -0,0 +1,19 @@ +{ + "name": "debug", + "repo": "visionmedia/debug", + "description": "small debugging utility", + "version": "2.6.9", + "keywords": [ + "debug", + "log", + "debugger" + ], + "main": "src/browser.js", + "scripts": [ + "src/browser.js", + "src/debug.js" + ], + "dependencies": { + "rauchg/ms.js": "0.7.1" + } +} diff --git a/gun-server/node_modules/debug/karma.conf.js b/gun-server/node_modules/debug/karma.conf.js new file mode 100644 index 0000000..103a82d --- /dev/null +++ b/gun-server/node_modules/debug/karma.conf.js @@ -0,0 +1,70 @@ +// Karma configuration +// Generated on Fri Dec 16 2016 13:09:51 GMT+0000 (UTC) + +module.exports = function(config) { + config.set({ + + // base path that will be used to resolve all patterns (eg. files, exclude) + basePath: '', + + + // frameworks to use + // available frameworks: https://npmjs.org/browse/keyword/karma-adapter + frameworks: ['mocha', 'chai', 'sinon'], + + + // list of files / patterns to load in the browser + files: [ + 'dist/debug.js', + 'test/*spec.js' + ], + + + // list of files to exclude + exclude: [ + 'src/node.js' + ], + + + // preprocess matching files before serving them to the browser + // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor + preprocessors: { + }, + + // test results reporter to use + // possible values: 'dots', 'progress' + // available reporters: https://npmjs.org/browse/keyword/karma-reporter + reporters: ['progress'], + + + // web server port + port: 9876, + + + // enable / disable colors in the output (reporters and logs) + colors: true, + + + // level of logging + // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG + logLevel: config.LOG_INFO, + + + // enable / disable watching file and executing tests whenever any file changes + autoWatch: true, + + + // start these browsers + // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher + browsers: ['PhantomJS'], + + + // Continuous Integration mode + // if true, Karma captures browsers, runs the tests and exits + singleRun: false, + + // Concurrency level + // how many browser should be started simultaneous + concurrency: Infinity + }) +} diff --git a/gun-server/node_modules/debug/node.js b/gun-server/node_modules/debug/node.js new file mode 100644 index 0000000..7fc36fe --- /dev/null +++ b/gun-server/node_modules/debug/node.js @@ -0,0 +1 @@ +module.exports = require('./src/node'); diff --git a/gun-server/node_modules/debug/package.json b/gun-server/node_modules/debug/package.json new file mode 100644 index 0000000..dc787ba --- /dev/null +++ b/gun-server/node_modules/debug/package.json @@ -0,0 +1,49 @@ +{ + "name": "debug", + "version": "2.6.9", + "repository": { + "type": "git", + "url": "git://github.com/visionmedia/debug.git" + }, + "description": "small debugging utility", + "keywords": [ + "debug", + "log", + "debugger" + ], + "author": "TJ Holowaychuk ", + "contributors": [ + "Nathan Rajlich (http://n8.io)", + "Andrew Rhyne " + ], + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + }, + "devDependencies": { + "browserify": "9.0.3", + "chai": "^3.5.0", + "concurrently": "^3.1.0", + "coveralls": "^2.11.15", + "eslint": "^3.12.1", + "istanbul": "^0.4.5", + "karma": "^1.3.0", + "karma-chai": "^0.1.0", + "karma-mocha": "^1.3.0", + "karma-phantomjs-launcher": "^1.0.2", + "karma-sinon": "^1.0.5", + "mocha": "^3.2.0", + "mocha-lcov-reporter": "^1.2.0", + "rimraf": "^2.5.4", + "sinon": "^1.17.6", + "sinon-chai": "^2.8.0" + }, + "main": "./src/index.js", + "browser": "./src/browser.js", + "component": { + "scripts": { + "debug/index.js": "browser.js", + "debug/debug.js": "debug.js" + } + } +} diff --git a/gun-server/node_modules/debug/src/browser.js b/gun-server/node_modules/debug/src/browser.js new file mode 100644 index 0000000..7106924 --- /dev/null +++ b/gun-server/node_modules/debug/src/browser.js @@ -0,0 +1,185 @@ +/** + * This is the web browser implementation of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = require('./debug'); +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = 'undefined' != typeof chrome + && 'undefined' != typeof chrome.storage + ? chrome.storage.local + : localstorage(); + +/** + * Colors. + */ + +exports.colors = [ + 'lightseagreen', + 'forestgreen', + 'goldenrod', + 'dodgerblue', + 'darkorchid', + 'crimson' +]; + +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ + +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { + return true; + } + + // is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +} + +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + +exports.formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (err) { + return '[UnexpectedJSONParseError]: ' + err.message; + } +}; + + +/** + * Colorize log arguments if enabled. + * + * @api public + */ + +function formatArgs(args) { + var useColors = this.useColors; + + args[0] = (useColors ? '%c' : '') + + this.namespace + + (useColors ? ' %c' : ' ') + + args[0] + + (useColors ? '%c ' : ' ') + + '+' + exports.humanize(this.diff); + + if (!useColors) return; + + var c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit') + + // the final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + var index = 0; + var lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, function(match) { + if ('%%' === match) return; + index++; + if ('%c' === match) { + // we only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); +} + +/** + * Invokes `console.log()` when available. + * No-op when `console.log` is not a "function". + * + * @api public + */ + +function log() { + // this hackery is required for IE8/9, where + // the `console.log` function doesn't have 'apply' + return 'object' === typeof console + && console.log + && Function.prototype.apply.call(console.log, console, arguments); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + +function save(namespaces) { + try { + if (null == namespaces) { + exports.storage.removeItem('debug'); + } else { + exports.storage.debug = namespaces; + } + } catch(e) {} +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + var r; + try { + r = exports.storage.debug; + } catch(e) {} + + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } + + return r; +} + +/** + * Enable namespaces listed in `localStorage.debug` initially. + */ + +exports.enable(load()); + +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ + +function localstorage() { + try { + return window.localStorage; + } catch (e) {} +} diff --git a/gun-server/node_modules/debug/src/debug.js b/gun-server/node_modules/debug/src/debug.js new file mode 100644 index 0000000..6a5e3fc --- /dev/null +++ b/gun-server/node_modules/debug/src/debug.js @@ -0,0 +1,202 @@ + +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; +exports.coerce = coerce; +exports.disable = disable; +exports.enable = enable; +exports.enabled = enabled; +exports.humanize = require('ms'); + +/** + * The currently active debug mode names, and names to skip. + */ + +exports.names = []; +exports.skips = []; + +/** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + +exports.formatters = {}; + +/** + * Previous log timestamp. + */ + +var prevTime; + +/** + * Select a color. + * @param {String} namespace + * @return {Number} + * @api private + */ + +function selectColor(namespace) { + var hash = 0, i; + + for (i in namespace) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return exports.colors[Math.abs(hash) % exports.colors.length]; +} + +/** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + +function createDebug(namespace) { + + function debug() { + // disabled? + if (!debug.enabled) return; + + var self = debug; + + // set `diff` timestamp + var curr = +new Date(); + var ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + // turn the `arguments` into a proper Array + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + + args[0] = exports.coerce(args[0]); + + if ('string' !== typeof args[0]) { + // anything else let's inspect with %O + args.unshift('%O'); + } + + // apply any `formatters` transformations + var index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { + // if we encounter an escaped % then don't increase the array index + if (match === '%%') return match; + index++; + var formatter = exports.formatters[format]; + if ('function' === typeof formatter) { + var val = args[index]; + match = formatter.call(self, val); + + // now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); + + // apply env-specific formatting (colors, etc.) + exports.formatArgs.call(self, args); + + var logFn = debug.log || exports.log || console.log.bind(console); + logFn.apply(self, args); + } + + debug.namespace = namespace; + debug.enabled = exports.enabled(namespace); + debug.useColors = exports.useColors(); + debug.color = selectColor(namespace); + + // env-specific initialization logic for debug instances + if ('function' === typeof exports.init) { + exports.init(debug); + } + + return debug; +} + +/** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + +function enable(namespaces) { + exports.save(namespaces); + + exports.names = []; + exports.skips = []; + + var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + var len = split.length; + + for (var i = 0; i < len; i++) { + if (!split[i]) continue; // ignore empty strings + namespaces = split[i].replace(/\*/g, '.*?'); + if (namespaces[0] === '-') { + exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + exports.names.push(new RegExp('^' + namespaces + '$')); + } + } +} + +/** + * Disable debug output. + * + * @api public + */ + +function disable() { + exports.enable(''); +} + +/** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + +function enabled(name) { + var i, len; + for (i = 0, len = exports.skips.length; i < len; i++) { + if (exports.skips[i].test(name)) { + return false; + } + } + for (i = 0, len = exports.names.length; i < len; i++) { + if (exports.names[i].test(name)) { + return true; + } + } + return false; +} + +/** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; +} diff --git a/gun-server/node_modules/debug/src/index.js b/gun-server/node_modules/debug/src/index.js new file mode 100644 index 0000000..e12cf4d --- /dev/null +++ b/gun-server/node_modules/debug/src/index.js @@ -0,0 +1,10 @@ +/** + * Detect Electron renderer process, which is node, but we should + * treat as a browser. + */ + +if (typeof process !== 'undefined' && process.type === 'renderer') { + module.exports = require('./browser.js'); +} else { + module.exports = require('./node.js'); +} diff --git a/gun-server/node_modules/debug/src/inspector-log.js b/gun-server/node_modules/debug/src/inspector-log.js new file mode 100644 index 0000000..60ea6c0 --- /dev/null +++ b/gun-server/node_modules/debug/src/inspector-log.js @@ -0,0 +1,15 @@ +module.exports = inspectorLog; + +// black hole +const nullStream = new (require('stream').Writable)(); +nullStream._write = () => {}; + +/** + * Outputs a `console.log()` to the Node.js Inspector console *only*. + */ +function inspectorLog() { + const stdout = console._stdout; + console._stdout = nullStream; + console.log.apply(console, arguments); + console._stdout = stdout; +} diff --git a/gun-server/node_modules/debug/src/node.js b/gun-server/node_modules/debug/src/node.js new file mode 100644 index 0000000..b15109c --- /dev/null +++ b/gun-server/node_modules/debug/src/node.js @@ -0,0 +1,248 @@ +/** + * Module dependencies. + */ + +var tty = require('tty'); +var util = require('util'); + +/** + * This is the Node.js implementation of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = require('./debug'); +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; + +/** + * Colors. + */ + +exports.colors = [6, 2, 3, 4, 5, 1]; + +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ + +exports.inspectOpts = Object.keys(process.env).filter(function (key) { + return /^debug_/i.test(key); +}).reduce(function (obj, key) { + // camel-case + var prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }); + + // coerce string value into JS value + var val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) val = true; + else if (/^(no|off|false|disabled)$/i.test(val)) val = false; + else if (val === 'null') val = null; + else val = Number(val); + + obj[prop] = val; + return obj; +}, {}); + +/** + * The file descriptor to write the `debug()` calls to. + * Set the `DEBUG_FD` env variable to override with another value. i.e.: + * + * $ DEBUG_FD=3 node script.js 3>debug.log + */ + +var fd = parseInt(process.env.DEBUG_FD, 10) || 2; + +if (1 !== fd && 2 !== fd) { + util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')() +} + +var stream = 1 === fd ? process.stdout : + 2 === fd ? process.stderr : + createWritableStdioStream(fd); + +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ + +function useColors() { + return 'colors' in exports.inspectOpts + ? Boolean(exports.inspectOpts.colors) + : tty.isatty(fd); +} + +/** + * Map %o to `util.inspect()`, all on a single line. + */ + +exports.formatters.o = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n').map(function(str) { + return str.trim() + }).join(' '); +}; + +/** + * Map %o to `util.inspect()`, allowing multiple lines if needed. + */ + +exports.formatters.O = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; + +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ + +function formatArgs(args) { + var name = this.namespace; + var useColors = this.useColors; + + if (useColors) { + var c = this.color; + var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m'; + + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m'); + } else { + args[0] = new Date().toUTCString() + + ' ' + name + ' ' + args[0]; + } +} + +/** + * Invokes `util.format()` with the specified arguments and writes to `stream`. + */ + +function log() { + return stream.write(util.format.apply(util, arguments) + '\n'); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + +function save(namespaces) { + if (null == namespaces) { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } else { + process.env.DEBUG = namespaces; + } +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + return process.env.DEBUG; +} + +/** + * Copied from `node/src/node.js`. + * + * XXX: It's lame that node doesn't expose this API out-of-the-box. It also + * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame. + */ + +function createWritableStdioStream (fd) { + var stream; + var tty_wrap = process.binding('tty_wrap'); + + // Note stream._type is used for test-module-load-list.js + + switch (tty_wrap.guessHandleType(fd)) { + case 'TTY': + stream = new tty.WriteStream(fd); + stream._type = 'tty'; + + // Hack to have stream not keep the event loop alive. + // See https://github.com/joyent/node/issues/1726 + if (stream._handle && stream._handle.unref) { + stream._handle.unref(); + } + break; + + case 'FILE': + var fs = require('fs'); + stream = new fs.SyncWriteStream(fd, { autoClose: false }); + stream._type = 'fs'; + break; + + case 'PIPE': + case 'TCP': + var net = require('net'); + stream = new net.Socket({ + fd: fd, + readable: false, + writable: true + }); + + // FIXME Should probably have an option in net.Socket to create a + // stream from an existing fd which is writable only. But for now + // we'll just add this hack and set the `readable` member to false. + // Test: ./node test/fixtures/echo.js < /etc/passwd + stream.readable = false; + stream.read = null; + stream._type = 'pipe'; + + // FIXME Hack to have stream not keep the event loop alive. + // See https://github.com/joyent/node/issues/1726 + if (stream._handle && stream._handle.unref) { + stream._handle.unref(); + } + break; + + default: + // Probably an error on in uv_guess_handle() + throw new Error('Implement me. Unknown stream file type!'); + } + + // For supporting legacy API we put the FD here. + stream.fd = fd; + + stream._isStdio = true; + + return stream; +} + +/** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ + +function init (debug) { + debug.inspectOpts = {}; + + var keys = Object.keys(exports.inspectOpts); + for (var i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} + +/** + * Enable namespaces listed in `process.env.DEBUG` initially. + */ + +exports.enable(load()); diff --git a/gun-server/node_modules/define-data-property/.eslintrc b/gun-server/node_modules/define-data-property/.eslintrc new file mode 100644 index 0000000..75443e8 --- /dev/null +++ b/gun-server/node_modules/define-data-property/.eslintrc @@ -0,0 +1,24 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "complexity": 0, + "id-length": 0, + "new-cap": ["error", { + "capIsNewExceptions": [ + "GetIntrinsic", + ], + }], + }, + + "overrides": [ + { + "files": "test/**", + "rules": { + "max-lines-per-function": "off", + }, + }, + ], +} diff --git a/gun-server/node_modules/define-data-property/.github/FUNDING.yml b/gun-server/node_modules/define-data-property/.github/FUNDING.yml new file mode 100644 index 0000000..3e17725 --- /dev/null +++ b/gun-server/node_modules/define-data-property/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/define-data-property +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/gun-server/node_modules/define-data-property/.nycrc b/gun-server/node_modules/define-data-property/.nycrc new file mode 100644 index 0000000..1826526 --- /dev/null +++ b/gun-server/node_modules/define-data-property/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/gun-server/node_modules/define-data-property/CHANGELOG.md b/gun-server/node_modules/define-data-property/CHANGELOG.md new file mode 100644 index 0000000..4eed75e --- /dev/null +++ b/gun-server/node_modules/define-data-property/CHANGELOG.md @@ -0,0 +1,70 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.1.4](https://github.com/ljharb/define-data-property/compare/v1.1.3...v1.1.4) - 2024-02-13 + +### Commits + +- [Refactor] use `es-define-property` [`90f2f4c`](https://github.com/ljharb/define-data-property/commit/90f2f4cc20298401e71c28e1e08888db12021453) +- [Dev Deps] update `@types/object.getownpropertydescriptors` [`cd929d9`](https://github.com/ljharb/define-data-property/commit/cd929d9a04f5f2fdcfa9d5be140940b91a083153) + +## [v1.1.3](https://github.com/ljharb/define-data-property/compare/v1.1.2...v1.1.3) - 2024-02-12 + +### Commits + +- [types] hand-write d.ts instead of emitting it [`0cbc988`](https://github.com/ljharb/define-data-property/commit/0cbc988203c105f2d97948327c7167ebd33bd318) +- [meta] simplify `exports` [`690781e`](https://github.com/ljharb/define-data-property/commit/690781eed28bbf2d6766237efda0ba6dd591609e) +- [Dev Deps] update `hasown`; clean up DT packages [`6cdfd1c`](https://github.com/ljharb/define-data-property/commit/6cdfd1cb2d91d791bfd18cda5d5cab232fd5d8fc) +- [actions] cleanup [`3142bc6`](https://github.com/ljharb/define-data-property/commit/3142bc6a4bc406a51f5b04f31e98562a27f35ffd) +- [meta] add `funding` [`8474423`](https://github.com/ljharb/define-data-property/commit/847442391a79779af3e0f1bf0b5bb923552b7804) +- [Deps] update `get-intrinsic` [`3e9be00`](https://github.com/ljharb/define-data-property/commit/3e9be00e07784ba34e7c77d8bc0fdbc832ad61de) + +## [v1.1.2](https://github.com/ljharb/define-data-property/compare/v1.1.1...v1.1.2) - 2024-02-05 + +### Commits + +- [Dev Deps] update @types packages, `object-inspect`, `tape`, `typescript` [`df41bf8`](https://github.com/ljharb/define-data-property/commit/df41bf84ca3456be6226055caab44e38e3a7fd2f) +- [Dev Deps] update DT packages, `aud`, `npmignore`, `tape`, typescript` [`fab0e4e`](https://github.com/ljharb/define-data-property/commit/fab0e4ec709ee02b79f42d6db3ee5f26e0a34b8a) +- [Dev Deps] use `hasown` instead of `has` [`aa51ef9`](https://github.com/ljharb/define-data-property/commit/aa51ef93f6403d49d9bb72a807bcdb6e418978c0) +- [Refactor] use `es-errors`, so things that only need those do not need `get-intrinsic` [`d89be50`](https://github.com/ljharb/define-data-property/commit/d89be50571175888d391238605122679f7e65ffc) +- [Deps] update `has-property-descriptors` [`7af887c`](https://github.com/ljharb/define-data-property/commit/7af887c9083b59b195b0079e04815cfed9fcee2b) +- [Deps] update `get-intrinsic` [`bb8728e`](https://github.com/ljharb/define-data-property/commit/bb8728ec42cd998505a7157ae24853a560c20646) + +## [v1.1.1](https://github.com/ljharb/define-data-property/compare/v1.1.0...v1.1.1) - 2023-10-12 + +### Commits + +- [Tests] fix tests in ES3 engines [`5c6920e`](https://github.com/ljharb/define-data-property/commit/5c6920edd1f52f675b02f417e539c28135b43f94) +- [Dev Deps] update `@types/es-value-fixtures`, `@types/for-each`, `@types/gopd`, `@types/has-property-descriptors`, `tape`, `typescript` [`7d82dfc`](https://github.com/ljharb/define-data-property/commit/7d82dfc20f778b4465bba06335dd53f6f431aea3) +- [Fix] IE 8 has a broken `Object.defineProperty` [`0672e1a`](https://github.com/ljharb/define-data-property/commit/0672e1af2a9fcc787e7c23b96dea60d290df5548) +- [meta] emit types on prepack [`73acb1f`](https://github.com/ljharb/define-data-property/commit/73acb1f903c21b314ec7156bf10f73c7910530c0) +- [Dev Deps] update `tape`, `typescript` [`9489a77`](https://github.com/ljharb/define-data-property/commit/9489a7738bf2ecf0ac71d5b78ec4ca6ad7ba0142) + +## [v1.1.0](https://github.com/ljharb/define-data-property/compare/v1.0.1...v1.1.0) - 2023-09-13 + +### Commits + +- [New] add `loose` arg [`155235a`](https://github.com/ljharb/define-data-property/commit/155235a4c4d7741f6de01cd87c99599a56654b72) +- [New] allow `null` to be passed for the non* args [`7d2fa5f`](https://github.com/ljharb/define-data-property/commit/7d2fa5f06be0392736c13b126f7cd38979f34792) + +## [v1.0.1](https://github.com/ljharb/define-data-property/compare/v1.0.0...v1.0.1) - 2023-09-12 + +### Commits + +- [meta] add TS types [`43d763c`](https://github.com/ljharb/define-data-property/commit/43d763c6c883f652de1c9c02ef6216ee507ffa69) +- [Dev Deps] update `@types/tape`, `typescript` [`f444985`](https://github.com/ljharb/define-data-property/commit/f444985811c36f3e6448a03ad2f9b7898917f4c7) +- [meta] add `safe-publish-latest`, [`172bb10`](https://github.com/ljharb/define-data-property/commit/172bb10890896ebb160e64398f6ee55760107bee) + +## v1.0.0 - 2023-09-12 + +### Commits + +- Initial implementation, tests, readme [`5b43d6b`](https://github.com/ljharb/define-data-property/commit/5b43d6b44e675a904810467a7d4e0adb7efc3196) +- Initial commit [`35e577a`](https://github.com/ljharb/define-data-property/commit/35e577a6ba59a98befa97776d70d90f3bea9009d) +- npm init [`82a0a04`](https://github.com/ljharb/define-data-property/commit/82a0a04a321ca7de220af02d41e2745e8a9962ed) +- Only apps should have lockfiles [`96df244`](https://github.com/ljharb/define-data-property/commit/96df244a3c6f426f9a2437be825d1c6f5dd7158e) +- [meta] use `npmignore` to autogenerate an npmignore file [`a87ff18`](https://github.com/ljharb/define-data-property/commit/a87ff18cb79e14c2eb5720486c4759fd9a189375) diff --git a/gun-server/node_modules/define-data-property/LICENSE b/gun-server/node_modules/define-data-property/LICENSE new file mode 100644 index 0000000..b4213ac --- /dev/null +++ b/gun-server/node_modules/define-data-property/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/gun-server/node_modules/define-data-property/README.md b/gun-server/node_modules/define-data-property/README.md new file mode 100644 index 0000000..f2304da --- /dev/null +++ b/gun-server/node_modules/define-data-property/README.md @@ -0,0 +1,67 @@ +# define-data-property [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Define a data property on an object. Will fall back to assignment in an engine without descriptors. + +The three `non*` argument can also be passed `null`, which will use the existing state if available. + +The `loose` argument will mean that if you attempt to set a non-normal data property, in an environment without descriptor support, it will fall back to normal assignment. + +## Usage + +```javascript +var defineDataProperty = require('define-data-property'); +var assert = require('assert'); + +var obj = {}; +defineDataProperty(obj, 'key', 'value'); +defineDataProperty( + obj, + 'key2', + 'value', + true, // nonEnumerable, optional + false, // nonWritable, optional + true, // nonConfigurable, optional + false // loose, optional +); + +assert.deepEqual( + Object.getOwnPropertyDescriptors(obj), + { + key: { + configurable: true, + enumerable: true, + value: 'value', + writable: true, + }, + key2: { + configurable: false, + enumerable: false, + value: 'value', + writable: true, + }, + } +); +``` + +[package-url]: https://npmjs.org/package/define-data-property +[npm-version-svg]: https://versionbadg.es/ljharb/define-data-property.svg +[deps-svg]: https://david-dm.org/ljharb/define-data-property.svg +[deps-url]: https://david-dm.org/ljharb/define-data-property +[dev-deps-svg]: https://david-dm.org/ljharb/define-data-property/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/define-data-property#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/define-data-property.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/define-data-property.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/define-data-property.svg +[downloads-url]: https://npm-stat.com/charts.html?package=define-data-property +[codecov-image]: https://codecov.io/gh/ljharb/define-data-property/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/define-data-property/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/define-data-property +[actions-url]: https://github.com/ljharb/define-data-property/actions diff --git a/gun-server/node_modules/define-data-property/index.d.ts b/gun-server/node_modules/define-data-property/index.d.ts new file mode 100644 index 0000000..b56a77d --- /dev/null +++ b/gun-server/node_modules/define-data-property/index.d.ts @@ -0,0 +1,12 @@ + +declare function defineDataProperty( + obj: Record, + property: keyof typeof obj, + value: typeof obj[typeof property], + nonEnumerable?: boolean | null, + nonWritable?: boolean | null, + nonConfigurable?: boolean | null, + loose?: boolean +): void; + +export = defineDataProperty; \ No newline at end of file diff --git a/gun-server/node_modules/define-data-property/index.js b/gun-server/node_modules/define-data-property/index.js new file mode 100644 index 0000000..e1a38c0 --- /dev/null +++ b/gun-server/node_modules/define-data-property/index.js @@ -0,0 +1,56 @@ +'use strict'; + +var $defineProperty = require('es-define-property'); + +var $SyntaxError = require('es-errors/syntax'); +var $TypeError = require('es-errors/type'); + +var gopd = require('gopd'); + +/** @type {import('.')} */ +module.exports = function defineDataProperty( + obj, + property, + value +) { + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + throw new $TypeError('`obj` must be an object or a function`'); + } + if (typeof property !== 'string' && typeof property !== 'symbol') { + throw new $TypeError('`property` must be a string or a symbol`'); + } + if (arguments.length > 3 && typeof arguments[3] !== 'boolean' && arguments[3] !== null) { + throw new $TypeError('`nonEnumerable`, if provided, must be a boolean or null'); + } + if (arguments.length > 4 && typeof arguments[4] !== 'boolean' && arguments[4] !== null) { + throw new $TypeError('`nonWritable`, if provided, must be a boolean or null'); + } + if (arguments.length > 5 && typeof arguments[5] !== 'boolean' && arguments[5] !== null) { + throw new $TypeError('`nonConfigurable`, if provided, must be a boolean or null'); + } + if (arguments.length > 6 && typeof arguments[6] !== 'boolean') { + throw new $TypeError('`loose`, if provided, must be a boolean'); + } + + var nonEnumerable = arguments.length > 3 ? arguments[3] : null; + var nonWritable = arguments.length > 4 ? arguments[4] : null; + var nonConfigurable = arguments.length > 5 ? arguments[5] : null; + var loose = arguments.length > 6 ? arguments[6] : false; + + /* @type {false | TypedPropertyDescriptor} */ + var desc = !!gopd && gopd(obj, property); + + if ($defineProperty) { + $defineProperty(obj, property, { + configurable: nonConfigurable === null && desc ? desc.configurable : !nonConfigurable, + enumerable: nonEnumerable === null && desc ? desc.enumerable : !nonEnumerable, + value: value, + writable: nonWritable === null && desc ? desc.writable : !nonWritable + }); + } else if (loose || (!nonEnumerable && !nonWritable && !nonConfigurable)) { + // must fall back to [[Set]], and was not explicitly asked to make non-enumerable, non-writable, or non-configurable + obj[property] = value; // eslint-disable-line no-param-reassign + } else { + throw new $SyntaxError('This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.'); + } +}; diff --git a/gun-server/node_modules/define-data-property/package.json b/gun-server/node_modules/define-data-property/package.json new file mode 100644 index 0000000..eec4097 --- /dev/null +++ b/gun-server/node_modules/define-data-property/package.json @@ -0,0 +1,106 @@ +{ + "name": "define-data-property", + "version": "1.1.4", + "description": "Define a data property on an object. Will fall back to assignment in an engine without descriptors.", + "main": "index.js", + "types": "./index.d.ts", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "tsc": "tsc -p .", + "prelint": "evalmd README.md", + "lint": "eslint --ext=js,mjs .", + "postlint": "npm run tsc", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/define-data-property.git" + }, + "keywords": [ + "define", + "data", + "property", + "object", + "accessor", + "javascript", + "ecmascript", + "enumerable", + "configurable", + "writable" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/define-data-property/issues" + }, + "homepage": "https://github.com/ljharb/define-data-property#readme", + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "gopd": "^1.0.1" + }, + "devDependencies": { + "@ljharb/eslint-config": "^21.1.0", + "@types/call-bind": "^1.0.5", + "@types/define-properties": "^1.1.5", + "@types/es-value-fixtures": "^1.4.4", + "@types/for-each": "^0.3.3", + "@types/get-intrinsic": "^1.2.2", + "@types/gopd": "^1.0.3", + "@types/has-property-descriptors": "^1.0.3", + "@types/object-inspect": "^1.8.4", + "@types/object.getownpropertydescriptors": "^2.1.4", + "@types/tape": "^5.6.4", + "aud": "^2.0.4", + "auto-changelog": "^2.4.0", + "es-value-fixtures": "^1.4.2", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "for-each": "^0.3.3", + "hasown": "^2.0.1", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "object-inspect": "^1.13.1", + "object.getownpropertydescriptors": "^2.1.7", + "reflect.ownkeys": "^1.1.4", + "safe-publish-latest": "^2.0.0", + "tape": "^5.7.4", + "typescript": "next" + }, + "engines": { + "node": ">= 0.4" + }, + "testling": { + "files": "test/index.js" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows", + "types/reflect.ownkeys" + ] + } +} diff --git a/gun-server/node_modules/define-data-property/test/index.js b/gun-server/node_modules/define-data-property/test/index.js new file mode 100644 index 0000000..68204c6 --- /dev/null +++ b/gun-server/node_modules/define-data-property/test/index.js @@ -0,0 +1,392 @@ +'use strict'; + +var test = require('tape'); +var v = require('es-value-fixtures'); +var forEach = require('for-each'); +var inspect = require('object-inspect'); +var hasOwn = require('hasown'); +var hasPropertyDescriptors = require('has-property-descriptors')(); +var getOwnPropertyDescriptors = require('object.getownpropertydescriptors'); +var ownKeys = require('reflect.ownkeys'); + +var defineDataProperty = require('../'); + +test('defineDataProperty', function (t) { + t.test('argument validation', function (st) { + forEach(v.primitives, function (nonObject) { + st['throws']( + // @ts-expect-error + function () { defineDataProperty(nonObject, 'key', 'value'); }, + TypeError, + 'throws on non-object input: ' + inspect(nonObject) + ); + }); + + forEach(v.nonPropertyKeys, function (nonPropertyKey) { + st['throws']( + // @ts-expect-error + function () { defineDataProperty({}, nonPropertyKey, 'value'); }, + TypeError, + 'throws on non-PropertyKey input: ' + inspect(nonPropertyKey) + ); + }); + + forEach(v.nonBooleans, function (nonBoolean) { + if (nonBoolean !== null) { + st['throws']( + // @ts-expect-error + function () { defineDataProperty({}, 'key', 'value', nonBoolean); }, + TypeError, + 'throws on non-boolean nonEnumerable: ' + inspect(nonBoolean) + ); + + st['throws']( + // @ts-expect-error + function () { defineDataProperty({}, 'key', 'value', false, nonBoolean); }, + TypeError, + 'throws on non-boolean nonWritable: ' + inspect(nonBoolean) + ); + + st['throws']( + // @ts-expect-error + function () { defineDataProperty({}, 'key', 'value', false, false, nonBoolean); }, + TypeError, + 'throws on non-boolean nonConfigurable: ' + inspect(nonBoolean) + ); + } + }); + + st.end(); + }); + + t.test('normal data property', function (st) { + /** @type {Record} */ + var obj = { existing: 'existing property' }; + st.ok(hasOwn(obj, 'existing'), 'has initial own property'); + st.equal(obj.existing, 'existing property', 'has expected initial value'); + + var res = defineDataProperty(obj, 'added', 'added property'); + st.equal(res, void undefined, 'returns `undefined`'); + st.ok(hasOwn(obj, 'added'), 'has expected own property'); + st.equal(obj.added, 'added property', 'has expected value'); + + defineDataProperty(obj, 'existing', 'new value'); + st.ok(hasOwn(obj, 'existing'), 'still has expected own property'); + st.equal(obj.existing, 'new value', 'has new expected value'); + + defineDataProperty(obj, 'explicit1', 'new value', false); + st.ok(hasOwn(obj, 'explicit1'), 'has expected own property (explicit enumerable)'); + st.equal(obj.explicit1, 'new value', 'has new expected value (explicit enumerable)'); + + defineDataProperty(obj, 'explicit2', 'new value', false, false); + st.ok(hasOwn(obj, 'explicit2'), 'has expected own property (explicit writable)'); + st.equal(obj.explicit2, 'new value', 'has new expected value (explicit writable)'); + + defineDataProperty(obj, 'explicit3', 'new value', false, false, false); + st.ok(hasOwn(obj, 'explicit3'), 'has expected own property (explicit configurable)'); + st.equal(obj.explicit3, 'new value', 'has new expected value (explicit configurable)'); + + st.end(); + }); + + t.test('loose mode', { skip: !hasPropertyDescriptors }, function (st) { + var obj = { existing: 'existing property' }; + + defineDataProperty(obj, 'added', 'added value 1', true, null, null, true); + st.deepEqual( + getOwnPropertyDescriptors(obj), + { + existing: { + configurable: true, + enumerable: true, + value: 'existing property', + writable: true + }, + added: { + configurable: true, + enumerable: !hasPropertyDescriptors, + value: 'added value 1', + writable: true + } + }, + 'in loose mode, obj still adds property 1' + ); + + defineDataProperty(obj, 'added', 'added value 2', false, true, null, true); + st.deepEqual( + getOwnPropertyDescriptors(obj), + { + existing: { + configurable: true, + enumerable: true, + value: 'existing property', + writable: true + }, + added: { + configurable: true, + enumerable: true, + value: 'added value 2', + writable: !hasPropertyDescriptors + } + }, + 'in loose mode, obj still adds property 2' + ); + + defineDataProperty(obj, 'added', 'added value 3', false, false, true, true); + st.deepEqual( + getOwnPropertyDescriptors(obj), + { + existing: { + configurable: true, + enumerable: true, + value: 'existing property', + writable: true + }, + added: { + configurable: !hasPropertyDescriptors, + enumerable: true, + value: 'added value 3', + writable: true + } + }, + 'in loose mode, obj still adds property 3' + ); + + st.end(); + }); + + t.test('non-normal data property, ES3', { skip: hasPropertyDescriptors }, function (st) { + /** @type {Record} */ + var obj = { existing: 'existing property' }; + + st['throws']( + function () { defineDataProperty(obj, 'added', 'added value', true); }, + SyntaxError, + 'nonEnumerable throws a Syntax Error' + ); + + st['throws']( + function () { defineDataProperty(obj, 'added', 'added value', false, true); }, + SyntaxError, + 'nonWritable throws a Syntax Error' + ); + + st['throws']( + function () { defineDataProperty(obj, 'added', 'added value', false, false, true); }, + SyntaxError, + 'nonWritable throws a Syntax Error' + ); + + st.deepEqual( + ownKeys(obj), + ['existing'], + 'obj still has expected keys' + ); + st.equal(obj.existing, 'existing property', 'obj still has expected values'); + + st.end(); + }); + + t.test('new non-normal data property, ES5+', { skip: !hasPropertyDescriptors }, function (st) { + /** @type {Record} */ + var obj = { existing: 'existing property' }; + + defineDataProperty(obj, 'nonEnum', null, true); + defineDataProperty(obj, 'nonWrit', null, false, true); + defineDataProperty(obj, 'nonConf', null, false, false, true); + + st.deepEqual( + getOwnPropertyDescriptors(obj), + { + existing: { + configurable: true, + enumerable: true, + value: 'existing property', + writable: true + }, + nonEnum: { + configurable: true, + enumerable: false, + value: null, + writable: true + }, + nonWrit: { + configurable: true, + enumerable: true, + value: null, + writable: false + }, + nonConf: { + configurable: false, + enumerable: true, + value: null, + writable: true + } + }, + 'obj has expected property descriptors' + ); + + st.end(); + }); + + t.test('existing non-normal data property, ES5+', { skip: !hasPropertyDescriptors }, function (st) { + // test case changing an existing non-normal property + + /** @type {Record} */ + var obj = {}; + Object.defineProperty(obj, 'nonEnum', { configurable: true, enumerable: false, value: null, writable: true }); + Object.defineProperty(obj, 'nonWrit', { configurable: true, enumerable: true, value: null, writable: false }); + Object.defineProperty(obj, 'nonConf', { configurable: false, enumerable: true, value: null, writable: true }); + + st.deepEqual( + getOwnPropertyDescriptors(obj), + { + nonEnum: { + configurable: true, + enumerable: false, + value: null, + writable: true + }, + nonWrit: { + configurable: true, + enumerable: true, + value: null, + writable: false + }, + nonConf: { + configurable: false, + enumerable: true, + value: null, + writable: true + } + }, + 'obj initially has expected property descriptors' + ); + + defineDataProperty(obj, 'nonEnum', 'new value', false); + defineDataProperty(obj, 'nonWrit', 'new value', false, false); + st['throws']( + function () { defineDataProperty(obj, 'nonConf', 'new value', false, false, false); }, + TypeError, + 'can not alter a nonconfigurable property' + ); + + st.deepEqual( + getOwnPropertyDescriptors(obj), + { + nonEnum: { + configurable: true, + enumerable: true, + value: 'new value', + writable: true + }, + nonWrit: { + configurable: true, + enumerable: true, + value: 'new value', + writable: true + }, + nonConf: { + configurable: false, + enumerable: true, + value: null, + writable: true + } + }, + 'obj ends up with expected property descriptors' + ); + + st.end(); + }); + + t.test('frozen object, ES5+', { skip: !hasPropertyDescriptors }, function (st) { + var frozen = Object.freeze({ existing: true }); + + st['throws']( + function () { defineDataProperty(frozen, 'existing', 'new value'); }, + TypeError, + 'frozen object can not modify an existing property' + ); + + st['throws']( + function () { defineDataProperty(frozen, 'new', 'new property'); }, + TypeError, + 'frozen object can not add a new property' + ); + + st.end(); + }); + + t.test('sealed object, ES5+', { skip: !hasPropertyDescriptors }, function (st) { + var sealed = Object.seal({ existing: true }); + st.deepEqual( + Object.getOwnPropertyDescriptor(sealed, 'existing'), + { + configurable: false, + enumerable: true, + value: true, + writable: true + }, + 'existing value on sealed object has expected descriptor' + ); + + defineDataProperty(sealed, 'existing', 'new value'); + + st.deepEqual( + Object.getOwnPropertyDescriptor(sealed, 'existing'), + { + configurable: false, + enumerable: true, + value: 'new value', + writable: true + }, + 'existing value on sealed object has changed descriptor' + ); + + st['throws']( + function () { defineDataProperty(sealed, 'new', 'new property'); }, + TypeError, + 'sealed object can not add a new property' + ); + + st.end(); + }); + + t.test('nonextensible object, ES5+', { skip: !hasPropertyDescriptors }, function (st) { + var nonExt = Object.preventExtensions({ existing: true }); + + st.deepEqual( + Object.getOwnPropertyDescriptor(nonExt, 'existing'), + { + configurable: true, + enumerable: true, + value: true, + writable: true + }, + 'existing value on non-extensible object has expected descriptor' + ); + + defineDataProperty(nonExt, 'existing', 'new value', true); + + st.deepEqual( + Object.getOwnPropertyDescriptor(nonExt, 'existing'), + { + configurable: true, + enumerable: false, + value: 'new value', + writable: true + }, + 'existing value on non-extensible object has changed descriptor' + ); + + st['throws']( + function () { defineDataProperty(nonExt, 'new', 'new property'); }, + TypeError, + 'non-extensible object can not add a new property' + ); + + st.end(); + }); + + t.end(); +}); diff --git a/gun-server/node_modules/define-data-property/tsconfig.json b/gun-server/node_modules/define-data-property/tsconfig.json new file mode 100644 index 0000000..69f060d --- /dev/null +++ b/gun-server/node_modules/define-data-property/tsconfig.json @@ -0,0 +1,59 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig to read more about this file */ + + /* Projects */ + + /* Language and Environment */ + "target": "es2022", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ + // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ + "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ + // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ + + /* Modules */ + "module": "commonjs", /* Specify what module code is generated. */ + // "rootDir": "./", /* Specify the root folder within your source files. */ + // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */ + // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ + // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ + // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ + "typeRoots": ["types"], /* Specify multiple folders that act like './node_modules/@types'. */ + "resolveJsonModule": true, /* Enable importing .json files. */ + + /* JavaScript Support */ + "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ + "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ + "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ + + /* Emit */ + "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ + "declarationMap": true, /* Create sourcemaps for d.ts files. */ + // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ + "noEmit": true, /* Disable emitting files from a compilation. */ + + /* Interop Constraints */ + "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ + "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ + "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ + + /* Type Checking */ + "strict": true, /* Enable all strict type-checking options. */ + "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ + "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ + "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ + "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ + "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ + "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ + "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ + "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ + "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ + // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ + + /* Completeness */ + // "skipLibCheck": true /* Skip type checking all .d.ts files. */ + }, + "exclude": [ + "coverage" + ] +} diff --git a/gun-server/node_modules/depd/History.md b/gun-server/node_modules/depd/History.md new file mode 100644 index 0000000..cd9ebaa --- /dev/null +++ b/gun-server/node_modules/depd/History.md @@ -0,0 +1,103 @@ +2.0.0 / 2018-10-26 +================== + + * Drop support for Node.js 0.6 + * Replace internal `eval` usage with `Function` constructor + * Use instance methods on `process` to check for listeners + +1.1.2 / 2018-01-11 +================== + + * perf: remove argument reassignment + * Support Node.js 0.6 to 9.x + +1.1.1 / 2017-07-27 +================== + + * Remove unnecessary `Buffer` loading + * Support Node.js 0.6 to 8.x + +1.1.0 / 2015-09-14 +================== + + * Enable strict mode in more places + * Support io.js 3.x + * Support io.js 2.x + * Support web browser loading + - Requires bundler like Browserify or webpack + +1.0.1 / 2015-04-07 +================== + + * Fix `TypeError`s when under `'use strict'` code + * Fix useless type name on auto-generated messages + * Support io.js 1.x + * Support Node.js 0.12 + +1.0.0 / 2014-09-17 +================== + + * No changes + +0.4.5 / 2014-09-09 +================== + + * Improve call speed to functions using the function wrapper + * Support Node.js 0.6 + +0.4.4 / 2014-07-27 +================== + + * Work-around v8 generating empty stack traces + +0.4.3 / 2014-07-26 +================== + + * Fix exception when global `Error.stackTraceLimit` is too low + +0.4.2 / 2014-07-19 +================== + + * Correct call site for wrapped functions and properties + +0.4.1 / 2014-07-19 +================== + + * Improve automatic message generation for function properties + +0.4.0 / 2014-07-19 +================== + + * Add `TRACE_DEPRECATION` environment variable + * Remove non-standard grey color from color output + * Support `--no-deprecation` argument + * Support `--trace-deprecation` argument + * Support `deprecate.property(fn, prop, message)` + +0.3.0 / 2014-06-16 +================== + + * Add `NO_DEPRECATION` environment variable + +0.2.0 / 2014-06-15 +================== + + * Add `deprecate.property(obj, prop, message)` + * Remove `supports-color` dependency for node.js 0.8 + +0.1.0 / 2014-06-15 +================== + + * Add `deprecate.function(fn, message)` + * Add `process.on('deprecation', fn)` emitter + * Automatically generate message when omitted from `deprecate()` + +0.0.1 / 2014-06-15 +================== + + * Fix warning for dynamic calls at singe call site + +0.0.0 / 2014-06-15 +================== + + * Initial implementation diff --git a/gun-server/node_modules/depd/LICENSE b/gun-server/node_modules/depd/LICENSE new file mode 100644 index 0000000..248de7a --- /dev/null +++ b/gun-server/node_modules/depd/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014-2018 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/gun-server/node_modules/depd/Readme.md b/gun-server/node_modules/depd/Readme.md new file mode 100644 index 0000000..043d1ca --- /dev/null +++ b/gun-server/node_modules/depd/Readme.md @@ -0,0 +1,280 @@ +# depd + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Linux Build][travis-image]][travis-url] +[![Windows Build][appveyor-image]][appveyor-url] +[![Coverage Status][coveralls-image]][coveralls-url] + +Deprecate all the things + +> With great modules comes great responsibility; mark things deprecated! + +## Install + +This module is installed directly using `npm`: + +```sh +$ npm install depd +``` + +This module can also be bundled with systems like +[Browserify](http://browserify.org/) or [webpack](https://webpack.github.io/), +though by default this module will alter it's API to no longer display or +track deprecations. + +## API + + + +```js +var deprecate = require('depd')('my-module') +``` + +This library allows you to display deprecation messages to your users. +This library goes above and beyond with deprecation warnings by +introspection of the call stack (but only the bits that it is interested +in). + +Instead of just warning on the first invocation of a deprecated +function and never again, this module will warn on the first invocation +of a deprecated function per unique call site, making it ideal to alert +users of all deprecated uses across the code base, rather than just +whatever happens to execute first. + +The deprecation warnings from this module also include the file and line +information for the call into the module that the deprecated function was +in. + +**NOTE** this library has a similar interface to the `debug` module, and +this module uses the calling file to get the boundary for the call stacks, +so you should always create a new `deprecate` object in each file and not +within some central file. + +### depd(namespace) + +Create a new deprecate function that uses the given namespace name in the +messages and will display the call site prior to the stack entering the +file this function was called from. It is highly suggested you use the +name of your module as the namespace. + +### deprecate(message) + +Call this function from deprecated code to display a deprecation message. +This message will appear once per unique caller site. Caller site is the +first call site in the stack in a different file from the caller of this +function. + +If the message is omitted, a message is generated for you based on the site +of the `deprecate()` call and will display the name of the function called, +similar to the name displayed in a stack trace. + +### deprecate.function(fn, message) + +Call this function to wrap a given function in a deprecation message on any +call to the function. An optional message can be supplied to provide a custom +message. + +### deprecate.property(obj, prop, message) + +Call this function to wrap a given property on object in a deprecation message +on any accessing or setting of the property. An optional message can be supplied +to provide a custom message. + +The method must be called on the object where the property belongs (not +inherited from the prototype). + +If the property is a data descriptor, it will be converted to an accessor +descriptor in order to display the deprecation message. + +### process.on('deprecation', fn) + +This module will allow easy capturing of deprecation errors by emitting the +errors as the type "deprecation" on the global `process`. If there are no +listeners for this type, the errors are written to STDERR as normal, but if +there are any listeners, nothing will be written to STDERR and instead only +emitted. From there, you can write the errors in a different format or to a +logging source. + +The error represents the deprecation and is emitted only once with the same +rules as writing to STDERR. The error has the following properties: + + - `message` - This is the message given by the library + - `name` - This is always `'DeprecationError'` + - `namespace` - This is the namespace the deprecation came from + - `stack` - This is the stack of the call to the deprecated thing + +Example `error.stack` output: + +``` +DeprecationError: my-cool-module deprecated oldfunction + at Object. ([eval]-wrapper:6:22) + at Module._compile (module.js:456:26) + at evalScript (node.js:532:25) + at startup (node.js:80:7) + at node.js:902:3 +``` + +### process.env.NO_DEPRECATION + +As a user of modules that are deprecated, the environment variable `NO_DEPRECATION` +is provided as a quick solution to silencing deprecation warnings from being +output. The format of this is similar to that of `DEBUG`: + +```sh +$ NO_DEPRECATION=my-module,othermod node app.js +``` + +This will suppress deprecations from being output for "my-module" and "othermod". +The value is a list of comma-separated namespaces. To suppress every warning +across all namespaces, use the value `*` for a namespace. + +Providing the argument `--no-deprecation` to the `node` executable will suppress +all deprecations (only available in Node.js 0.8 or higher). + +**NOTE** This will not suppress the deperecations given to any "deprecation" +event listeners, just the output to STDERR. + +### process.env.TRACE_DEPRECATION + +As a user of modules that are deprecated, the environment variable `TRACE_DEPRECATION` +is provided as a solution to getting more detailed location information in deprecation +warnings by including the entire stack trace. The format of this is the same as +`NO_DEPRECATION`: + +```sh +$ TRACE_DEPRECATION=my-module,othermod node app.js +``` + +This will include stack traces for deprecations being output for "my-module" and +"othermod". The value is a list of comma-separated namespaces. To trace every +warning across all namespaces, use the value `*` for a namespace. + +Providing the argument `--trace-deprecation` to the `node` executable will trace +all deprecations (only available in Node.js 0.8 or higher). + +**NOTE** This will not trace the deperecations silenced by `NO_DEPRECATION`. + +## Display + +![message](files/message.png) + +When a user calls a function in your library that you mark deprecated, they +will see the following written to STDERR (in the given colors, similar colors +and layout to the `debug` module): + +``` +bright cyan bright yellow +| | reset cyan +| | | | +▼ ▼ ▼ ▼ +my-cool-module deprecated oldfunction [eval]-wrapper:6:22 +▲ ▲ ▲ ▲ +| | | | +namespace | | location of mycoolmod.oldfunction() call + | deprecation message + the word "deprecated" +``` + +If the user redirects their STDERR to a file or somewhere that does not support +colors, they see (similar layout to the `debug` module): + +``` +Sun, 15 Jun 2014 05:21:37 GMT my-cool-module deprecated oldfunction at [eval]-wrapper:6:22 +▲ ▲ ▲ ▲ ▲ +| | | | | +timestamp of message namespace | | location of mycoolmod.oldfunction() call + | deprecation message + the word "deprecated" +``` + +## Examples + +### Deprecating all calls to a function + +This will display a deprecated message about "oldfunction" being deprecated +from "my-module" on STDERR. + +```js +var deprecate = require('depd')('my-cool-module') + +// message automatically derived from function name +// Object.oldfunction +exports.oldfunction = deprecate.function(function oldfunction () { + // all calls to function are deprecated +}) + +// specific message +exports.oldfunction = deprecate.function(function () { + // all calls to function are deprecated +}, 'oldfunction') +``` + +### Conditionally deprecating a function call + +This will display a deprecated message about "weirdfunction" being deprecated +from "my-module" on STDERR when called with less than 2 arguments. + +```js +var deprecate = require('depd')('my-cool-module') + +exports.weirdfunction = function () { + if (arguments.length < 2) { + // calls with 0 or 1 args are deprecated + deprecate('weirdfunction args < 2') + } +} +``` + +When calling `deprecate` as a function, the warning is counted per call site +within your own module, so you can display different deprecations depending +on different situations and the users will still get all the warnings: + +```js +var deprecate = require('depd')('my-cool-module') + +exports.weirdfunction = function () { + if (arguments.length < 2) { + // calls with 0 or 1 args are deprecated + deprecate('weirdfunction args < 2') + } else if (typeof arguments[0] !== 'string') { + // calls with non-string first argument are deprecated + deprecate('weirdfunction non-string first arg') + } +} +``` + +### Deprecating property access + +This will display a deprecated message about "oldprop" being deprecated +from "my-module" on STDERR when accessed. A deprecation will be displayed +when setting the value and when getting the value. + +```js +var deprecate = require('depd')('my-cool-module') + +exports.oldprop = 'something' + +// message automatically derives from property name +deprecate.property(exports, 'oldprop') + +// explicit message +deprecate.property(exports, 'oldprop', 'oldprop >= 0.10') +``` + +## License + +[MIT](LICENSE) + +[appveyor-image]: https://badgen.net/appveyor/ci/dougwilson/nodejs-depd/master?label=windows +[appveyor-url]: https://ci.appveyor.com/project/dougwilson/nodejs-depd +[coveralls-image]: https://badgen.net/coveralls/c/github/dougwilson/nodejs-depd/master +[coveralls-url]: https://coveralls.io/r/dougwilson/nodejs-depd?branch=master +[node-image]: https://badgen.net/npm/node/depd +[node-url]: https://nodejs.org/en/download/ +[npm-downloads-image]: https://badgen.net/npm/dm/depd +[npm-url]: https://npmjs.org/package/depd +[npm-version-image]: https://badgen.net/npm/v/depd +[travis-image]: https://badgen.net/travis/dougwilson/nodejs-depd/master?label=linux +[travis-url]: https://travis-ci.org/dougwilson/nodejs-depd diff --git a/gun-server/node_modules/depd/index.js b/gun-server/node_modules/depd/index.js new file mode 100644 index 0000000..1bf2fcf --- /dev/null +++ b/gun-server/node_modules/depd/index.js @@ -0,0 +1,538 @@ +/*! + * depd + * Copyright(c) 2014-2018 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module dependencies. + */ + +var relative = require('path').relative + +/** + * Module exports. + */ + +module.exports = depd + +/** + * Get the path to base files on. + */ + +var basePath = process.cwd() + +/** + * Determine if namespace is contained in the string. + */ + +function containsNamespace (str, namespace) { + var vals = str.split(/[ ,]+/) + var ns = String(namespace).toLowerCase() + + for (var i = 0; i < vals.length; i++) { + var val = vals[i] + + // namespace contained + if (val && (val === '*' || val.toLowerCase() === ns)) { + return true + } + } + + return false +} + +/** + * Convert a data descriptor to accessor descriptor. + */ + +function convertDataDescriptorToAccessor (obj, prop, message) { + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + var value = descriptor.value + + descriptor.get = function getter () { return value } + + if (descriptor.writable) { + descriptor.set = function setter (val) { return (value = val) } + } + + delete descriptor.value + delete descriptor.writable + + Object.defineProperty(obj, prop, descriptor) + + return descriptor +} + +/** + * Create arguments string to keep arity. + */ + +function createArgumentsString (arity) { + var str = '' + + for (var i = 0; i < arity; i++) { + str += ', arg' + i + } + + return str.substr(2) +} + +/** + * Create stack string from stack. + */ + +function createStackString (stack) { + var str = this.name + ': ' + this.namespace + + if (this.message) { + str += ' deprecated ' + this.message + } + + for (var i = 0; i < stack.length; i++) { + str += '\n at ' + stack[i].toString() + } + + return str +} + +/** + * Create deprecate for namespace in caller. + */ + +function depd (namespace) { + if (!namespace) { + throw new TypeError('argument namespace is required') + } + + var stack = getStack() + var site = callSiteLocation(stack[1]) + var file = site[0] + + function deprecate (message) { + // call to self as log + log.call(deprecate, message) + } + + deprecate._file = file + deprecate._ignored = isignored(namespace) + deprecate._namespace = namespace + deprecate._traced = istraced(namespace) + deprecate._warned = Object.create(null) + + deprecate.function = wrapfunction + deprecate.property = wrapproperty + + return deprecate +} + +/** + * Determine if event emitter has listeners of a given type. + * + * The way to do this check is done three different ways in Node.js >= 0.8 + * so this consolidates them into a minimal set using instance methods. + * + * @param {EventEmitter} emitter + * @param {string} type + * @returns {boolean} + * @private + */ + +function eehaslisteners (emitter, type) { + var count = typeof emitter.listenerCount !== 'function' + ? emitter.listeners(type).length + : emitter.listenerCount(type) + + return count > 0 +} + +/** + * Determine if namespace is ignored. + */ + +function isignored (namespace) { + if (process.noDeprecation) { + // --no-deprecation support + return true + } + + var str = process.env.NO_DEPRECATION || '' + + // namespace ignored + return containsNamespace(str, namespace) +} + +/** + * Determine if namespace is traced. + */ + +function istraced (namespace) { + if (process.traceDeprecation) { + // --trace-deprecation support + return true + } + + var str = process.env.TRACE_DEPRECATION || '' + + // namespace traced + return containsNamespace(str, namespace) +} + +/** + * Display deprecation message. + */ + +function log (message, site) { + var haslisteners = eehaslisteners(process, 'deprecation') + + // abort early if no destination + if (!haslisteners && this._ignored) { + return + } + + var caller + var callFile + var callSite + var depSite + var i = 0 + var seen = false + var stack = getStack() + var file = this._file + + if (site) { + // provided site + depSite = site + callSite = callSiteLocation(stack[1]) + callSite.name = depSite.name + file = callSite[0] + } else { + // get call site + i = 2 + depSite = callSiteLocation(stack[i]) + callSite = depSite + } + + // get caller of deprecated thing in relation to file + for (; i < stack.length; i++) { + caller = callSiteLocation(stack[i]) + callFile = caller[0] + + if (callFile === file) { + seen = true + } else if (callFile === this._file) { + file = this._file + } else if (seen) { + break + } + } + + var key = caller + ? depSite.join(':') + '__' + caller.join(':') + : undefined + + if (key !== undefined && key in this._warned) { + // already warned + return + } + + this._warned[key] = true + + // generate automatic message from call site + var msg = message + if (!msg) { + msg = callSite === depSite || !callSite.name + ? defaultMessage(depSite) + : defaultMessage(callSite) + } + + // emit deprecation if listeners exist + if (haslisteners) { + var err = DeprecationError(this._namespace, msg, stack.slice(i)) + process.emit('deprecation', err) + return + } + + // format and write message + var format = process.stderr.isTTY + ? formatColor + : formatPlain + var output = format.call(this, msg, caller, stack.slice(i)) + process.stderr.write(output + '\n', 'utf8') +} + +/** + * Get call site location as array. + */ + +function callSiteLocation (callSite) { + var file = callSite.getFileName() || '' + var line = callSite.getLineNumber() + var colm = callSite.getColumnNumber() + + if (callSite.isEval()) { + file = callSite.getEvalOrigin() + ', ' + file + } + + var site = [file, line, colm] + + site.callSite = callSite + site.name = callSite.getFunctionName() + + return site +} + +/** + * Generate a default message from the site. + */ + +function defaultMessage (site) { + var callSite = site.callSite + var funcName = site.name + + // make useful anonymous name + if (!funcName) { + funcName = '' + } + + var context = callSite.getThis() + var typeName = context && callSite.getTypeName() + + // ignore useless type name + if (typeName === 'Object') { + typeName = undefined + } + + // make useful type name + if (typeName === 'Function') { + typeName = context.name || typeName + } + + return typeName && callSite.getMethodName() + ? typeName + '.' + funcName + : funcName +} + +/** + * Format deprecation message without color. + */ + +function formatPlain (msg, caller, stack) { + var timestamp = new Date().toUTCString() + + var formatted = timestamp + + ' ' + this._namespace + + ' deprecated ' + msg + + // add stack trace + if (this._traced) { + for (var i = 0; i < stack.length; i++) { + formatted += '\n at ' + stack[i].toString() + } + + return formatted + } + + if (caller) { + formatted += ' at ' + formatLocation(caller) + } + + return formatted +} + +/** + * Format deprecation message with color. + */ + +function formatColor (msg, caller, stack) { + var formatted = '\x1b[36;1m' + this._namespace + '\x1b[22;39m' + // bold cyan + ' \x1b[33;1mdeprecated\x1b[22;39m' + // bold yellow + ' \x1b[0m' + msg + '\x1b[39m' // reset + + // add stack trace + if (this._traced) { + for (var i = 0; i < stack.length; i++) { + formatted += '\n \x1b[36mat ' + stack[i].toString() + '\x1b[39m' // cyan + } + + return formatted + } + + if (caller) { + formatted += ' \x1b[36m' + formatLocation(caller) + '\x1b[39m' // cyan + } + + return formatted +} + +/** + * Format call site location. + */ + +function formatLocation (callSite) { + return relative(basePath, callSite[0]) + + ':' + callSite[1] + + ':' + callSite[2] +} + +/** + * Get the stack as array of call sites. + */ + +function getStack () { + var limit = Error.stackTraceLimit + var obj = {} + var prep = Error.prepareStackTrace + + Error.prepareStackTrace = prepareObjectStackTrace + Error.stackTraceLimit = Math.max(10, limit) + + // capture the stack + Error.captureStackTrace(obj) + + // slice this function off the top + var stack = obj.stack.slice(1) + + Error.prepareStackTrace = prep + Error.stackTraceLimit = limit + + return stack +} + +/** + * Capture call site stack from v8. + */ + +function prepareObjectStackTrace (obj, stack) { + return stack +} + +/** + * Return a wrapped function in a deprecation message. + */ + +function wrapfunction (fn, message) { + if (typeof fn !== 'function') { + throw new TypeError('argument fn must be a function') + } + + var args = createArgumentsString(fn.length) + var stack = getStack() + var site = callSiteLocation(stack[1]) + + site.name = fn.name + + // eslint-disable-next-line no-new-func + var deprecatedfn = new Function('fn', 'log', 'deprecate', 'message', 'site', + '"use strict"\n' + + 'return function (' + args + ') {' + + 'log.call(deprecate, message, site)\n' + + 'return fn.apply(this, arguments)\n' + + '}')(fn, log, this, message, site) + + return deprecatedfn +} + +/** + * Wrap property in a deprecation message. + */ + +function wrapproperty (obj, prop, message) { + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + throw new TypeError('argument obj must be object') + } + + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + + if (!descriptor) { + throw new TypeError('must call property on owner object') + } + + if (!descriptor.configurable) { + throw new TypeError('property must be configurable') + } + + var deprecate = this + var stack = getStack() + var site = callSiteLocation(stack[1]) + + // set site name + site.name = prop + + // convert data descriptor + if ('value' in descriptor) { + descriptor = convertDataDescriptorToAccessor(obj, prop, message) + } + + var get = descriptor.get + var set = descriptor.set + + // wrap getter + if (typeof get === 'function') { + descriptor.get = function getter () { + log.call(deprecate, message, site) + return get.apply(this, arguments) + } + } + + // wrap setter + if (typeof set === 'function') { + descriptor.set = function setter () { + log.call(deprecate, message, site) + return set.apply(this, arguments) + } + } + + Object.defineProperty(obj, prop, descriptor) +} + +/** + * Create DeprecationError for deprecation + */ + +function DeprecationError (namespace, message, stack) { + var error = new Error() + var stackString + + Object.defineProperty(error, 'constructor', { + value: DeprecationError + }) + + Object.defineProperty(error, 'message', { + configurable: true, + enumerable: false, + value: message, + writable: true + }) + + Object.defineProperty(error, 'name', { + enumerable: false, + configurable: true, + value: 'DeprecationError', + writable: true + }) + + Object.defineProperty(error, 'namespace', { + configurable: true, + enumerable: false, + value: namespace, + writable: true + }) + + Object.defineProperty(error, 'stack', { + configurable: true, + enumerable: false, + get: function () { + if (stackString !== undefined) { + return stackString + } + + // prepare stack trace + return (stackString = createStackString.call(this, stack)) + }, + set: function setter (val) { + stackString = val + } + }) + + return error +} diff --git a/gun-server/node_modules/depd/lib/browser/index.js b/gun-server/node_modules/depd/lib/browser/index.js new file mode 100644 index 0000000..6be45cc --- /dev/null +++ b/gun-server/node_modules/depd/lib/browser/index.js @@ -0,0 +1,77 @@ +/*! + * depd + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = depd + +/** + * Create deprecate for namespace in caller. + */ + +function depd (namespace) { + if (!namespace) { + throw new TypeError('argument namespace is required') + } + + function deprecate (message) { + // no-op in browser + } + + deprecate._file = undefined + deprecate._ignored = true + deprecate._namespace = namespace + deprecate._traced = false + deprecate._warned = Object.create(null) + + deprecate.function = wrapfunction + deprecate.property = wrapproperty + + return deprecate +} + +/** + * Return a wrapped function in a deprecation message. + * + * This is a no-op version of the wrapper, which does nothing but call + * validation. + */ + +function wrapfunction (fn, message) { + if (typeof fn !== 'function') { + throw new TypeError('argument fn must be a function') + } + + return fn +} + +/** + * Wrap property in a deprecation message. + * + * This is a no-op version of the wrapper, which does nothing but call + * validation. + */ + +function wrapproperty (obj, prop, message) { + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + throw new TypeError('argument obj must be object') + } + + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + + if (!descriptor) { + throw new TypeError('must call property on owner object') + } + + if (!descriptor.configurable) { + throw new TypeError('property must be configurable') + } +} diff --git a/gun-server/node_modules/depd/package.json b/gun-server/node_modules/depd/package.json new file mode 100644 index 0000000..3857e19 --- /dev/null +++ b/gun-server/node_modules/depd/package.json @@ -0,0 +1,45 @@ +{ + "name": "depd", + "description": "Deprecate all the things", + "version": "2.0.0", + "author": "Douglas Christopher Wilson ", + "license": "MIT", + "keywords": [ + "deprecate", + "deprecated" + ], + "repository": "dougwilson/nodejs-depd", + "browser": "lib/browser/index.js", + "devDependencies": { + "benchmark": "2.1.4", + "beautify-benchmark": "0.2.4", + "eslint": "5.7.0", + "eslint-config-standard": "12.0.0", + "eslint-plugin-import": "2.14.0", + "eslint-plugin-markdown": "1.0.0-beta.7", + "eslint-plugin-node": "7.0.1", + "eslint-plugin-promise": "4.0.1", + "eslint-plugin-standard": "4.0.0", + "istanbul": "0.4.5", + "mocha": "5.2.0", + "safe-buffer": "5.1.2", + "uid-safe": "2.1.5" + }, + "files": [ + "lib/", + "History.md", + "LICENSE", + "index.js", + "Readme.md" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "bench": "node benchmark/index.js", + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --bail test/", + "test-ci": "istanbul cover --print=none node_modules/mocha/bin/_mocha -- --reporter spec test/ && istanbul report lcovonly text-summary", + "test-cov": "istanbul cover --print=none node_modules/mocha/bin/_mocha -- --reporter dot test/ && istanbul report lcov text-summary" + } +} diff --git a/gun-server/node_modules/destroy/LICENSE b/gun-server/node_modules/destroy/LICENSE new file mode 100644 index 0000000..0e2c35f --- /dev/null +++ b/gun-server/node_modules/destroy/LICENSE @@ -0,0 +1,23 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com +Copyright (c) 2015-2022 Douglas Christopher Wilson doug@somethingdoug.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/gun-server/node_modules/destroy/README.md b/gun-server/node_modules/destroy/README.md new file mode 100644 index 0000000..e7701ae --- /dev/null +++ b/gun-server/node_modules/destroy/README.md @@ -0,0 +1,63 @@ +# destroy + +[![NPM version][npm-image]][npm-url] +[![Build Status][github-actions-ci-image]][github-actions-ci-url] +[![Test coverage][coveralls-image]][coveralls-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +Destroy a stream. + +This module is meant to ensure a stream gets destroyed, handling different APIs +and Node.js bugs. + +## API + +```js +var destroy = require('destroy') +``` + +### destroy(stream [, suppress]) + +Destroy the given stream, and optionally suppress any future `error` events. + +In most cases, this is identical to a simple `stream.destroy()` call. The rules +are as follows for a given stream: + + 1. If the `stream` is an instance of `ReadStream`, then call `stream.destroy()` + and add a listener to the `open` event to call `stream.close()` if it is + fired. This is for a Node.js bug that will leak a file descriptor if + `.destroy()` is called before `open`. + 2. If the `stream` is an instance of a zlib stream, then call `stream.destroy()` + and close the underlying zlib handle if open, otherwise call `stream.close()`. + This is for consistency across Node.js versions and a Node.js bug that will + leak a native zlib handle. + 3. If the `stream` is not an instance of `Stream`, then nothing happens. + 4. If the `stream` has a `.destroy()` method, then call it. + +The function returns the `stream` passed in as the argument. + +## Example + +```js +var destroy = require('destroy') + +var fs = require('fs') +var stream = fs.createReadStream('package.json') + +// ... and later +destroy(stream) +``` + +[npm-image]: https://img.shields.io/npm/v/destroy.svg?style=flat-square +[npm-url]: https://npmjs.org/package/destroy +[github-tag]: http://img.shields.io/github/tag/stream-utils/destroy.svg?style=flat-square +[github-url]: https://github.com/stream-utils/destroy/tags +[coveralls-image]: https://img.shields.io/coveralls/stream-utils/destroy.svg?style=flat-square +[coveralls-url]: https://coveralls.io/r/stream-utils/destroy?branch=master +[license-image]: http://img.shields.io/npm/l/destroy.svg?style=flat-square +[license-url]: LICENSE.md +[downloads-image]: http://img.shields.io/npm/dm/destroy.svg?style=flat-square +[downloads-url]: https://npmjs.org/package/destroy +[github-actions-ci-image]: https://img.shields.io/github/workflow/status/stream-utils/destroy/ci/master?label=ci&style=flat-square +[github-actions-ci-url]: https://github.com/stream-utils/destroy/actions/workflows/ci.yml diff --git a/gun-server/node_modules/destroy/index.js b/gun-server/node_modules/destroy/index.js new file mode 100644 index 0000000..7fd5c09 --- /dev/null +++ b/gun-server/node_modules/destroy/index.js @@ -0,0 +1,209 @@ +/*! + * destroy + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015-2022 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var EventEmitter = require('events').EventEmitter +var ReadStream = require('fs').ReadStream +var Stream = require('stream') +var Zlib = require('zlib') + +/** + * Module exports. + * @public + */ + +module.exports = destroy + +/** + * Destroy the given stream, and optionally suppress any future `error` events. + * + * @param {object} stream + * @param {boolean} suppress + * @public + */ + +function destroy (stream, suppress) { + if (isFsReadStream(stream)) { + destroyReadStream(stream) + } else if (isZlibStream(stream)) { + destroyZlibStream(stream) + } else if (hasDestroy(stream)) { + stream.destroy() + } + + if (isEventEmitter(stream) && suppress) { + stream.removeAllListeners('error') + stream.addListener('error', noop) + } + + return stream +} + +/** + * Destroy a ReadStream. + * + * @param {object} stream + * @private + */ + +function destroyReadStream (stream) { + stream.destroy() + + if (typeof stream.close === 'function') { + // node.js core bug work-around + stream.on('open', onOpenClose) + } +} + +/** + * Close a Zlib stream. + * + * Zlib streams below Node.js 4.5.5 have a buggy implementation + * of .close() when zlib encountered an error. + * + * @param {object} stream + * @private + */ + +function closeZlibStream (stream) { + if (stream._hadError === true) { + var prop = stream._binding === null + ? '_binding' + : '_handle' + + stream[prop] = { + close: function () { this[prop] = null } + } + } + + stream.close() +} + +/** + * Destroy a Zlib stream. + * + * Zlib streams don't have a destroy function in Node.js 6. On top of that + * simply calling destroy on a zlib stream in Node.js 8+ will result in a + * memory leak. So until that is fixed, we need to call both close AND destroy. + * + * PR to fix memory leak: https://github.com/nodejs/node/pull/23734 + * + * In Node.js 6+8, it's important that destroy is called before close as the + * stream would otherwise emit the error 'zlib binding closed'. + * + * @param {object} stream + * @private + */ + +function destroyZlibStream (stream) { + if (typeof stream.destroy === 'function') { + // node.js core bug work-around + // istanbul ignore if: node.js 0.8 + if (stream._binding) { + // node.js < 0.10.0 + stream.destroy() + if (stream._processing) { + stream._needDrain = true + stream.once('drain', onDrainClearBinding) + } else { + stream._binding.clear() + } + } else if (stream._destroy && stream._destroy !== Stream.Transform.prototype._destroy) { + // node.js >= 12, ^11.1.0, ^10.15.1 + stream.destroy() + } else if (stream._destroy && typeof stream.close === 'function') { + // node.js 7, 8 + stream.destroyed = true + stream.close() + } else { + // fallback + // istanbul ignore next + stream.destroy() + } + } else if (typeof stream.close === 'function') { + // node.js < 8 fallback + closeZlibStream(stream) + } +} + +/** + * Determine if stream has destroy. + * @private + */ + +function hasDestroy (stream) { + return stream instanceof Stream && + typeof stream.destroy === 'function' +} + +/** + * Determine if val is EventEmitter. + * @private + */ + +function isEventEmitter (val) { + return val instanceof EventEmitter +} + +/** + * Determine if stream is fs.ReadStream stream. + * @private + */ + +function isFsReadStream (stream) { + return stream instanceof ReadStream +} + +/** + * Determine if stream is Zlib stream. + * @private + */ + +function isZlibStream (stream) { + return stream instanceof Zlib.Gzip || + stream instanceof Zlib.Gunzip || + stream instanceof Zlib.Deflate || + stream instanceof Zlib.DeflateRaw || + stream instanceof Zlib.Inflate || + stream instanceof Zlib.InflateRaw || + stream instanceof Zlib.Unzip +} + +/** + * No-op function. + * @private + */ + +function noop () {} + +/** + * On drain handler to clear binding. + * @private + */ + +// istanbul ignore next: node.js 0.8 +function onDrainClearBinding () { + this._binding.clear() +} + +/** + * On open handler to close stream. + * @private + */ + +function onOpenClose () { + if (typeof this.fd === 'number') { + // actually close down the fd + this.close() + } +} diff --git a/gun-server/node_modules/destroy/package.json b/gun-server/node_modules/destroy/package.json new file mode 100644 index 0000000..c85e438 --- /dev/null +++ b/gun-server/node_modules/destroy/package.json @@ -0,0 +1,48 @@ +{ + "name": "destroy", + "description": "destroy a stream if possible", + "version": "1.2.0", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com", + "twitter": "https://twitter.com/jongleberry" + }, + "contributors": [ + "Douglas Christopher Wilson " + ], + "license": "MIT", + "repository": "stream-utils/destroy", + "devDependencies": { + "eslint": "7.32.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.25.4", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "5.2.0", + "eslint-plugin-standard": "4.1.0", + "mocha": "9.2.2", + "nyc": "15.1.0" + }, + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec", + "test-ci": "nyc --reporter=lcovonly --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + }, + "files": [ + "index.js", + "LICENSE" + ], + "keywords": [ + "stream", + "streams", + "destroy", + "cleanup", + "leak", + "fd" + ] +} diff --git a/gun-server/node_modules/ee-first/LICENSE b/gun-server/node_modules/ee-first/LICENSE new file mode 100644 index 0000000..a7ae8ee --- /dev/null +++ b/gun-server/node_modules/ee-first/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/gun-server/node_modules/ee-first/README.md b/gun-server/node_modules/ee-first/README.md new file mode 100644 index 0000000..cbd2478 --- /dev/null +++ b/gun-server/node_modules/ee-first/README.md @@ -0,0 +1,80 @@ +# EE First + +[![NPM version][npm-image]][npm-url] +[![Build status][travis-image]][travis-url] +[![Test coverage][coveralls-image]][coveralls-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] +[![Gittip][gittip-image]][gittip-url] + +Get the first event in a set of event emitters and event pairs, +then clean up after itself. + +## Install + +```sh +$ npm install ee-first +``` + +## API + +```js +var first = require('ee-first') +``` + +### first(arr, listener) + +Invoke `listener` on the first event from the list specified in `arr`. `arr` is +an array of arrays, with each array in the format `[ee, ...event]`. `listener` +will be called only once, the first time any of the given events are emitted. If +`error` is one of the listened events, then if that fires first, the `listener` +will be given the `err` argument. + +The `listener` is invoked as `listener(err, ee, event, args)`, where `err` is the +first argument emitted from an `error` event, if applicable; `ee` is the event +emitter that fired; `event` is the string event name that fired; and `args` is an +array of the arguments that were emitted on the event. + +```js +var ee1 = new EventEmitter() +var ee2 = new EventEmitter() + +first([ + [ee1, 'close', 'end', 'error'], + [ee2, 'error'] +], function (err, ee, event, args) { + // listener invoked +}) +``` + +#### .cancel() + +The group of listeners can be cancelled before being invoked and have all the event +listeners removed from the underlying event emitters. + +```js +var thunk = first([ + [ee1, 'close', 'end', 'error'], + [ee2, 'error'] +], function (err, ee, event, args) { + // listener invoked +}) + +// cancel and clean up +thunk.cancel() +``` + +[npm-image]: https://img.shields.io/npm/v/ee-first.svg?style=flat-square +[npm-url]: https://npmjs.org/package/ee-first +[github-tag]: http://img.shields.io/github/tag/jonathanong/ee-first.svg?style=flat-square +[github-url]: https://github.com/jonathanong/ee-first/tags +[travis-image]: https://img.shields.io/travis/jonathanong/ee-first.svg?style=flat-square +[travis-url]: https://travis-ci.org/jonathanong/ee-first +[coveralls-image]: https://img.shields.io/coveralls/jonathanong/ee-first.svg?style=flat-square +[coveralls-url]: https://coveralls.io/r/jonathanong/ee-first?branch=master +[license-image]: http://img.shields.io/npm/l/ee-first.svg?style=flat-square +[license-url]: LICENSE.md +[downloads-image]: http://img.shields.io/npm/dm/ee-first.svg?style=flat-square +[downloads-url]: https://npmjs.org/package/ee-first +[gittip-image]: https://img.shields.io/gittip/jonathanong.svg?style=flat-square +[gittip-url]: https://www.gittip.com/jonathanong/ diff --git a/gun-server/node_modules/ee-first/index.js b/gun-server/node_modules/ee-first/index.js new file mode 100644 index 0000000..501287c --- /dev/null +++ b/gun-server/node_modules/ee-first/index.js @@ -0,0 +1,95 @@ +/*! + * ee-first + * Copyright(c) 2014 Jonathan Ong + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = first + +/** + * Get the first event in a set of event emitters and event pairs. + * + * @param {array} stuff + * @param {function} done + * @public + */ + +function first(stuff, done) { + if (!Array.isArray(stuff)) + throw new TypeError('arg must be an array of [ee, events...] arrays') + + var cleanups = [] + + for (var i = 0; i < stuff.length; i++) { + var arr = stuff[i] + + if (!Array.isArray(arr) || arr.length < 2) + throw new TypeError('each array member must be [ee, events...]') + + var ee = arr[0] + + for (var j = 1; j < arr.length; j++) { + var event = arr[j] + var fn = listener(event, callback) + + // listen to the event + ee.on(event, fn) + // push this listener to the list of cleanups + cleanups.push({ + ee: ee, + event: event, + fn: fn, + }) + } + } + + function callback() { + cleanup() + done.apply(null, arguments) + } + + function cleanup() { + var x + for (var i = 0; i < cleanups.length; i++) { + x = cleanups[i] + x.ee.removeListener(x.event, x.fn) + } + } + + function thunk(fn) { + done = fn + } + + thunk.cancel = cleanup + + return thunk +} + +/** + * Create the event listener. + * @private + */ + +function listener(event, done) { + return function onevent(arg1) { + var args = new Array(arguments.length) + var ee = this + var err = event === 'error' + ? arg1 + : null + + // copy args to prevent arguments escaping scope + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i] + } + + done(err, ee, event, args) + } +} diff --git a/gun-server/node_modules/ee-first/package.json b/gun-server/node_modules/ee-first/package.json new file mode 100644 index 0000000..b6d0b7d --- /dev/null +++ b/gun-server/node_modules/ee-first/package.json @@ -0,0 +1,29 @@ +{ + "name": "ee-first", + "description": "return the first event in a set of ee/event pairs", + "version": "1.1.1", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com", + "twitter": "https://twitter.com/jongleberry" + }, + "contributors": [ + "Douglas Christopher Wilson " + ], + "license": "MIT", + "repository": "jonathanong/ee-first", + "devDependencies": { + "istanbul": "0.3.9", + "mocha": "2.2.5" + }, + "files": [ + "index.js", + "LICENSE" + ], + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + } +} diff --git a/gun-server/node_modules/encodeurl/HISTORY.md b/gun-server/node_modules/encodeurl/HISTORY.md new file mode 100644 index 0000000..41313b2 --- /dev/null +++ b/gun-server/node_modules/encodeurl/HISTORY.md @@ -0,0 +1,14 @@ +1.0.2 / 2018-01-21 +================== + + * Fix encoding `%` as last character + +1.0.1 / 2016-06-09 +================== + + * Fix encoding unpaired surrogates at start/end of string + +1.0.0 / 2016-06-08 +================== + + * Initial release diff --git a/gun-server/node_modules/encodeurl/LICENSE b/gun-server/node_modules/encodeurl/LICENSE new file mode 100644 index 0000000..8812229 --- /dev/null +++ b/gun-server/node_modules/encodeurl/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2016 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/gun-server/node_modules/encodeurl/README.md b/gun-server/node_modules/encodeurl/README.md new file mode 100644 index 0000000..127c5a0 --- /dev/null +++ b/gun-server/node_modules/encodeurl/README.md @@ -0,0 +1,128 @@ +# encodeurl + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Encode a URL to a percent-encoded form, excluding already-encoded sequences + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install encodeurl +``` + +## API + +```js +var encodeUrl = require('encodeurl') +``` + +### encodeUrl(url) + +Encode a URL to a percent-encoded form, excluding already-encoded sequences. + +This function will take an already-encoded URL and encode all the non-URL +code points (as UTF-8 byte sequences). This function will not encode the +"%" character unless it is not part of a valid sequence (`%20` will be +left as-is, but `%foo` will be encoded as `%25foo`). + +This encode is meant to be "safe" and does not throw errors. It will try as +hard as it can to properly encode the given URL, including replacing any raw, +unpaired surrogate pairs with the Unicode replacement character prior to +encoding. + +This function is _similar_ to the intrinsic function `encodeURI`, except it +will not encode the `%` character if that is part of a valid sequence, will +not encode `[` and `]` (for IPv6 hostnames) and will replace raw, unpaired +surrogate pairs with the Unicode replacement character (instead of throwing). + +## Examples + +### Encode a URL containing user-controled data + +```js +var encodeUrl = require('encodeurl') +var escapeHtml = require('escape-html') + +http.createServer(function onRequest (req, res) { + // get encoded form of inbound url + var url = encodeUrl(req.url) + + // create html message + var body = '

      Location ' + escapeHtml(url) + ' not found

      ' + + // send a 404 + res.statusCode = 404 + res.setHeader('Content-Type', 'text/html; charset=UTF-8') + res.setHeader('Content-Length', String(Buffer.byteLength(body, 'utf-8'))) + res.end(body, 'utf-8') +}) +``` + +### Encode a URL for use in a header field + +```js +var encodeUrl = require('encodeurl') +var escapeHtml = require('escape-html') +var url = require('url') + +http.createServer(function onRequest (req, res) { + // parse inbound url + var href = url.parse(req) + + // set new host for redirect + href.host = 'localhost' + href.protocol = 'https:' + href.slashes = true + + // create location header + var location = encodeUrl(url.format(href)) + + // create html message + var body = '

      Redirecting to new site: ' + escapeHtml(location) + '

      ' + + // send a 301 + res.statusCode = 301 + res.setHeader('Content-Type', 'text/html; charset=UTF-8') + res.setHeader('Content-Length', String(Buffer.byteLength(body, 'utf-8'))) + res.setHeader('Location', location) + res.end(body, 'utf-8') +}) +``` + +## Testing + +```sh +$ npm test +$ npm run lint +``` + +## References + +- [RFC 3986: Uniform Resource Identifier (URI): Generic Syntax][rfc-3986] +- [WHATWG URL Living Standard][whatwg-url] + +[rfc-3986]: https://tools.ietf.org/html/rfc3986 +[whatwg-url]: https://url.spec.whatwg.org/ + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/encodeurl.svg +[npm-url]: https://npmjs.org/package/encodeurl +[node-version-image]: https://img.shields.io/node/v/encodeurl.svg +[node-version-url]: https://nodejs.org/en/download +[travis-image]: https://img.shields.io/travis/pillarjs/encodeurl.svg +[travis-url]: https://travis-ci.org/pillarjs/encodeurl +[coveralls-image]: https://img.shields.io/coveralls/pillarjs/encodeurl.svg +[coveralls-url]: https://coveralls.io/r/pillarjs/encodeurl?branch=master +[downloads-image]: https://img.shields.io/npm/dm/encodeurl.svg +[downloads-url]: https://npmjs.org/package/encodeurl diff --git a/gun-server/node_modules/encodeurl/index.js b/gun-server/node_modules/encodeurl/index.js new file mode 100644 index 0000000..fc4906c --- /dev/null +++ b/gun-server/node_modules/encodeurl/index.js @@ -0,0 +1,60 @@ +/*! + * encodeurl + * Copyright(c) 2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = encodeUrl + +/** + * RegExp to match non-URL code points, *after* encoding (i.e. not including "%") + * and including invalid escape sequences. + * @private + */ + +var ENCODE_CHARS_REGEXP = /(?:[^\x21\x25\x26-\x3B\x3D\x3F-\x5B\x5D\x5F\x61-\x7A\x7E]|%(?:[^0-9A-Fa-f]|[0-9A-Fa-f][^0-9A-Fa-f]|$))+/g + +/** + * RegExp to match unmatched surrogate pair. + * @private + */ + +var UNMATCHED_SURROGATE_PAIR_REGEXP = /(^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]|[\uD800-\uDBFF]([^\uDC00-\uDFFF]|$)/g + +/** + * String to replace unmatched surrogate pair with. + * @private + */ + +var UNMATCHED_SURROGATE_PAIR_REPLACE = '$1\uFFFD$2' + +/** + * Encode a URL to a percent-encoded form, excluding already-encoded sequences. + * + * This function will take an already-encoded URL and encode all the non-URL + * code points. This function will not encode the "%" character unless it is + * not part of a valid sequence (`%20` will be left as-is, but `%foo` will + * be encoded as `%25foo`). + * + * This encode is meant to be "safe" and does not throw errors. It will try as + * hard as it can to properly encode the given URL, including replacing any raw, + * unpaired surrogate pairs with the Unicode replacement character prior to + * encoding. + * + * @param {string} url + * @return {string} + * @public + */ + +function encodeUrl (url) { + return String(url) + .replace(UNMATCHED_SURROGATE_PAIR_REGEXP, UNMATCHED_SURROGATE_PAIR_REPLACE) + .replace(ENCODE_CHARS_REGEXP, encodeURI) +} diff --git a/gun-server/node_modules/encodeurl/package.json b/gun-server/node_modules/encodeurl/package.json new file mode 100644 index 0000000..b9f25ef --- /dev/null +++ b/gun-server/node_modules/encodeurl/package.json @@ -0,0 +1,40 @@ +{ + "name": "encodeurl", + "description": "Encode a URL to a percent-encoded form, excluding already-encoded sequences", + "version": "1.0.2", + "contributors": [ + "Douglas Christopher Wilson " + ], + "license": "MIT", + "keywords": [ + "encode", + "encodeurl", + "url" + ], + "repository": "pillarjs/encodeurl", + "devDependencies": { + "eslint": "3.19.0", + "eslint-config-standard": "10.2.1", + "eslint-plugin-import": "2.8.0", + "eslint-plugin-node": "5.2.1", + "eslint-plugin-promise": "3.6.0", + "eslint-plugin-standard": "3.0.1", + "istanbul": "0.4.5", + "mocha": "2.5.3" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + } +} diff --git a/gun-server/node_modules/es-define-property/.eslintrc b/gun-server/node_modules/es-define-property/.eslintrc new file mode 100644 index 0000000..46f3b12 --- /dev/null +++ b/gun-server/node_modules/es-define-property/.eslintrc @@ -0,0 +1,13 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "new-cap": ["error", { + "capIsNewExceptions": [ + "GetIntrinsic", + ], + }], + }, +} diff --git a/gun-server/node_modules/es-define-property/.github/FUNDING.yml b/gun-server/node_modules/es-define-property/.github/FUNDING.yml new file mode 100644 index 0000000..4445451 --- /dev/null +++ b/gun-server/node_modules/es-define-property/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/es-define-property +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with a single custom sponsorship URL diff --git a/gun-server/node_modules/es-define-property/.nycrc b/gun-server/node_modules/es-define-property/.nycrc new file mode 100644 index 0000000..bdd626c --- /dev/null +++ b/gun-server/node_modules/es-define-property/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/gun-server/node_modules/es-define-property/CHANGELOG.md b/gun-server/node_modules/es-define-property/CHANGELOG.md new file mode 100644 index 0000000..4dce2ec --- /dev/null +++ b/gun-server/node_modules/es-define-property/CHANGELOG.md @@ -0,0 +1,15 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## v1.0.0 - 2024-02-12 + +### Commits + +- Initial implementation, tests, readme, types [`3e154e1`](https://github.com/ljharb/es-define-property/commit/3e154e11a2fee09127220f5e503bf2c0a31dd480) +- Initial commit [`07d98de`](https://github.com/ljharb/es-define-property/commit/07d98de34a4dc31ff5e83a37c0c3f49e0d85cd50) +- npm init [`c4eb634`](https://github.com/ljharb/es-define-property/commit/c4eb6348b0d3886aac36cef34ad2ee0665ea6f3e) +- Only apps should have lockfiles [`7af86ec`](https://github.com/ljharb/es-define-property/commit/7af86ec1d311ec0b17fdfe616a25f64276903856) diff --git a/gun-server/node_modules/es-define-property/LICENSE b/gun-server/node_modules/es-define-property/LICENSE new file mode 100644 index 0000000..f82f389 --- /dev/null +++ b/gun-server/node_modules/es-define-property/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/gun-server/node_modules/es-define-property/README.md b/gun-server/node_modules/es-define-property/README.md new file mode 100644 index 0000000..9b291bd --- /dev/null +++ b/gun-server/node_modules/es-define-property/README.md @@ -0,0 +1,49 @@ +# es-define-property [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +`Object.defineProperty`, but not IE 8's broken one. + +## Example + +```js +const assert = require('assert'); + +const $defineProperty = require('es-define-property'); + +if ($defineProperty) { + assert.equal($defineProperty, Object.defineProperty); +} else if (Object.defineProperty) { + assert.equal($defineProperty, false, 'this is IE 8'); +} else { + assert.equal($defineProperty, false, 'this is an ES3 engine'); +} +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +## Security + +Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report. + +[package-url]: https://npmjs.org/package/es-define-property +[npm-version-svg]: https://versionbadg.es/ljharb/es-define-property.svg +[deps-svg]: https://david-dm.org/ljharb/es-define-property.svg +[deps-url]: https://david-dm.org/ljharb/es-define-property +[dev-deps-svg]: https://david-dm.org/ljharb/es-define-property/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/es-define-property#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/es-define-property.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/es-define-property.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/es-define-property.svg +[downloads-url]: https://npm-stat.com/charts.html?package=es-define-property +[codecov-image]: https://codecov.io/gh/ljharb/es-define-property/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/es-define-property/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/es-define-property +[actions-url]: https://github.com/ljharb/es-define-property/actions diff --git a/gun-server/node_modules/es-define-property/index.d.ts b/gun-server/node_modules/es-define-property/index.d.ts new file mode 100644 index 0000000..6012247 --- /dev/null +++ b/gun-server/node_modules/es-define-property/index.d.ts @@ -0,0 +1,3 @@ +declare const defineProperty: false | typeof Object.defineProperty; + +export = defineProperty; \ No newline at end of file diff --git a/gun-server/node_modules/es-define-property/index.js b/gun-server/node_modules/es-define-property/index.js new file mode 100644 index 0000000..f32737d --- /dev/null +++ b/gun-server/node_modules/es-define-property/index.js @@ -0,0 +1,16 @@ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); + +/** @type {import('.')} */ +var $defineProperty = GetIntrinsic('%Object.defineProperty%', true) || false; +if ($defineProperty) { + try { + $defineProperty({}, 'a', { value: 1 }); + } catch (e) { + // IE 8 has a broken defineProperty + $defineProperty = false; + } +} + +module.exports = $defineProperty; diff --git a/gun-server/node_modules/es-define-property/package.json b/gun-server/node_modules/es-define-property/package.json new file mode 100644 index 0000000..45bc90f --- /dev/null +++ b/gun-server/node_modules/es-define-property/package.json @@ -0,0 +1,81 @@ +{ + "name": "es-define-property", + "version": "1.0.0", + "description": "`Object.defineProperty`, but not IE 8's broken one.", + "main": "index.js", + "types": "./index.d.ts", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "prelint": "evalmd README.md", + "lint": "eslint --ext=js,mjs .", + "postlint": "tsc -p .", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/es-define-property.git" + }, + "keywords": [ + "javascript", + "ecmascript", + "object", + "define", + "property", + "defineProperty", + "Object.defineProperty" + ], + "author": "Jordan Harband ", + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/es-define-property/issues" + }, + "homepage": "https://github.com/ljharb/es-define-property#readme", + "dependencies": { + "get-intrinsic": "^1.2.4" + }, + "devDependencies": { + "@ljharb/eslint-config": "^21.1.0", + "@types/get-intrinsic": "^1.2.2", + "@types/gopd": "^1.0.3", + "@types/tape": "^5.6.4", + "aud": "^2.0.4", + "auto-changelog": "^2.4.0", + "eslint": "^8.8.0", + "evalmd": "^0.0.19", + "gopd": "^1.0.1", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.7.4", + "typescript": "next" + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + } +} diff --git a/gun-server/node_modules/es-define-property/test/index.js b/gun-server/node_modules/es-define-property/test/index.js new file mode 100644 index 0000000..dbc054e --- /dev/null +++ b/gun-server/node_modules/es-define-property/test/index.js @@ -0,0 +1,55 @@ +'use strict'; + +var $defineProperty = require('../'); + +var test = require('tape'); +var gOPD = require('gopd'); + +test('defineProperty: supported', { skip: !$defineProperty }, function (t) { + t.plan(4); + + t.equal(typeof $defineProperty, 'function', 'defineProperty is supported'); + if ($defineProperty && gOPD) { // this `if` check is just to shut TS up + var o = { a: 1 }; + + $defineProperty(o, 'b', { enumerable: true, value: 2 }); + t.deepEqual( + gOPD(o, 'b'), + { + configurable: false, + enumerable: true, + value: 2, + writable: false + }, + 'property descriptor is as expected' + ); + + $defineProperty(o, 'c', { enumerable: false, value: 3, writable: true }); + t.deepEqual( + gOPD(o, 'c'), + { + configurable: false, + enumerable: false, + value: 3, + writable: true + }, + 'property descriptor is as expected' + ); + } + + t.equal($defineProperty, Object.defineProperty, 'defineProperty is Object.defineProperty'); + + t.end(); +}); + +test('defineProperty: not supported', { skip: !!$defineProperty }, function (t) { + t.notOk($defineProperty, 'defineProperty is not supported'); + + t.match( + typeof $defineProperty, + /^(?:undefined|boolean)$/, + '`typeof defineProperty` is `undefined` or `boolean`' + ); + + t.end(); +}); diff --git a/gun-server/node_modules/es-define-property/tsconfig.json b/gun-server/node_modules/es-define-property/tsconfig.json new file mode 100644 index 0000000..fdfa155 --- /dev/null +++ b/gun-server/node_modules/es-define-property/tsconfig.json @@ -0,0 +1,50 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig.json to read more about this file */ + + /* Projects */ + + /* Language and Environment */ + "target": "es2022", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ + // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ + "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ + // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ + + /* Modules */ + "module": "commonjs", /* Specify what module code is generated. */ + // "rootDir": "./", /* Specify the root folder within your source files. */ + // "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */ + // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ + // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ + // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ + // "typeRoots": ["types"], /* Specify multiple folders that act like `./node_modules/@types`. */ + "resolveJsonModule": true, /* Enable importing .json files. */ + // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ + + /* JavaScript Support */ + "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */ + "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ + "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */ + + /* Emit */ + "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ + "declarationMap": true, /* Create sourcemaps for d.ts files. */ + "noEmit": true, /* Disable emitting files from a compilation. */ + + /* Interop Constraints */ + "allowSyntheticDefaultImports": true, /* Allow `import x from y` when a module doesn't have a default export. */ + "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */ + "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ + + /* Type Checking */ + "strict": true, /* Enable all strict type-checking options. */ + + /* Completeness */ + // "skipLibCheck": true /* Skip type checking all .d.ts files. */ + }, + "exclude": [ + "coverage", + "test/list-exports" + ], +} diff --git a/gun-server/node_modules/es-errors/.eslintrc b/gun-server/node_modules/es-errors/.eslintrc new file mode 100644 index 0000000..3b5d9e9 --- /dev/null +++ b/gun-server/node_modules/es-errors/.eslintrc @@ -0,0 +1,5 @@ +{ + "root": true, + + "extends": "@ljharb", +} diff --git a/gun-server/node_modules/es-errors/.github/FUNDING.yml b/gun-server/node_modules/es-errors/.github/FUNDING.yml new file mode 100644 index 0000000..f1b8805 --- /dev/null +++ b/gun-server/node_modules/es-errors/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/es-errors +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with a single custom sponsorship URL diff --git a/gun-server/node_modules/es-errors/CHANGELOG.md b/gun-server/node_modules/es-errors/CHANGELOG.md new file mode 100644 index 0000000..204a9e9 --- /dev/null +++ b/gun-server/node_modules/es-errors/CHANGELOG.md @@ -0,0 +1,40 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.3.0](https://github.com/ljharb/es-errors/compare/v1.2.1...v1.3.0) - 2024-02-05 + +### Commits + +- [New] add `EvalError` and `URIError` [`1927627`](https://github.com/ljharb/es-errors/commit/1927627ba68cb6c829d307231376c967db53acdf) + +## [v1.2.1](https://github.com/ljharb/es-errors/compare/v1.2.0...v1.2.1) - 2024-02-04 + +### Commits + +- [Fix] add missing `exports` entry [`5bb5f28`](https://github.com/ljharb/es-errors/commit/5bb5f280f98922701109d6ebb82eea2257cecc7e) + +## [v1.2.0](https://github.com/ljharb/es-errors/compare/v1.1.0...v1.2.0) - 2024-02-04 + +### Commits + +- [New] add `ReferenceError` [`6d8cf5b`](https://github.com/ljharb/es-errors/commit/6d8cf5bbb6f3f598d02cf6f30e468ba2caa8e143) + +## [v1.1.0](https://github.com/ljharb/es-errors/compare/v1.0.0...v1.1.0) - 2024-02-04 + +### Commits + +- [New] add base Error [`2983ab6`](https://github.com/ljharb/es-errors/commit/2983ab65f7bc5441276cb021dc3aa03c78881698) + +## v1.0.0 - 2024-02-03 + +### Commits + +- Initial implementation, tests, readme, type [`8f47631`](https://github.com/ljharb/es-errors/commit/8f476317e9ad76f40ad648081829b1a1a3a1288b) +- Initial commit [`ea5d099`](https://github.com/ljharb/es-errors/commit/ea5d099ef18e550509ab9e2be000526afd81c385) +- npm init [`6f5ebf9`](https://github.com/ljharb/es-errors/commit/6f5ebf9cead474dadd72b9e63dad315820a089ae) +- Only apps should have lockfiles [`e1a0aeb`](https://github.com/ljharb/es-errors/commit/e1a0aeb7b80f5cfc56be54d6b2100e915d47def8) +- [meta] add `sideEffects` flag [`a9c7d46`](https://github.com/ljharb/es-errors/commit/a9c7d460a492f1d8a241c836bc25a322a19cc043) diff --git a/gun-server/node_modules/es-errors/LICENSE b/gun-server/node_modules/es-errors/LICENSE new file mode 100644 index 0000000..f82f389 --- /dev/null +++ b/gun-server/node_modules/es-errors/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/gun-server/node_modules/es-errors/README.md b/gun-server/node_modules/es-errors/README.md new file mode 100644 index 0000000..8dbfacf --- /dev/null +++ b/gun-server/node_modules/es-errors/README.md @@ -0,0 +1,55 @@ +# es-errors [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +A simple cache for a few of the JS Error constructors. + +## Example + +```js +const assert = require('assert'); + +const Base = require('es-errors'); +const Eval = require('es-errors/eval'); +const Range = require('es-errors/range'); +const Ref = require('es-errors/ref'); +const Syntax = require('es-errors/syntax'); +const Type = require('es-errors/type'); +const URI = require('es-errors/uri'); + +assert.equal(Base, Error); +assert.equal(Eval, EvalError); +assert.equal(Range, RangeError); +assert.equal(Ref, ReferenceError); +assert.equal(Syntax, SyntaxError); +assert.equal(Type, TypeError); +assert.equal(URI, URIError); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +## Security + +Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report. + +[package-url]: https://npmjs.org/package/es-errors +[npm-version-svg]: https://versionbadg.es/ljharb/es-errors.svg +[deps-svg]: https://david-dm.org/ljharb/es-errors.svg +[deps-url]: https://david-dm.org/ljharb/es-errors +[dev-deps-svg]: https://david-dm.org/ljharb/es-errors/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/es-errors#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/es-errors.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/es-errors.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/es-errors.svg +[downloads-url]: https://npm-stat.com/charts.html?package=es-errors +[codecov-image]: https://codecov.io/gh/ljharb/es-errors/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/es-errors/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/es-errors +[actions-url]: https://github.com/ljharb/es-errors/actions diff --git a/gun-server/node_modules/es-errors/eval.d.ts b/gun-server/node_modules/es-errors/eval.d.ts new file mode 100644 index 0000000..e4210e0 --- /dev/null +++ b/gun-server/node_modules/es-errors/eval.d.ts @@ -0,0 +1,3 @@ +declare const EvalError: EvalErrorConstructor; + +export = EvalError; diff --git a/gun-server/node_modules/es-errors/eval.js b/gun-server/node_modules/es-errors/eval.js new file mode 100644 index 0000000..725ccb6 --- /dev/null +++ b/gun-server/node_modules/es-errors/eval.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./eval')} */ +module.exports = EvalError; diff --git a/gun-server/node_modules/es-errors/index.d.ts b/gun-server/node_modules/es-errors/index.d.ts new file mode 100644 index 0000000..69bdbc9 --- /dev/null +++ b/gun-server/node_modules/es-errors/index.d.ts @@ -0,0 +1,3 @@ +declare const Error: ErrorConstructor; + +export = Error; diff --git a/gun-server/node_modules/es-errors/index.js b/gun-server/node_modules/es-errors/index.js new file mode 100644 index 0000000..cc0c521 --- /dev/null +++ b/gun-server/node_modules/es-errors/index.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('.')} */ +module.exports = Error; diff --git a/gun-server/node_modules/es-errors/package.json b/gun-server/node_modules/es-errors/package.json new file mode 100644 index 0000000..ff8c2a5 --- /dev/null +++ b/gun-server/node_modules/es-errors/package.json @@ -0,0 +1,80 @@ +{ + "name": "es-errors", + "version": "1.3.0", + "description": "A simple cache for a few of the JS Error constructors.", + "main": "index.js", + "exports": { + ".": "./index.js", + "./eval": "./eval.js", + "./range": "./range.js", + "./ref": "./ref.js", + "./syntax": "./syntax.js", + "./type": "./type.js", + "./uri": "./uri.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "pretest": "npm run lint", + "test": "npm run tests-only", + "tests-only": "nyc tape 'test/**/*.js'", + "posttest": "aud --production", + "prelint": "evalmd README.md", + "lint": "eslint --ext=js,mjs .", + "postlint": "tsc -p . && eclint check $(git ls-files | xargs find 2> /dev/null | grep -vE 'node_modules|\\.git' | grep -v dist/)", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/es-errors.git" + }, + "keywords": [ + "javascript", + "ecmascript", + "error", + "typeerror", + "syntaxerror", + "rangeerror" + ], + "author": "Jordan Harband ", + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/es-errors/issues" + }, + "homepage": "https://github.com/ljharb/es-errors#readme", + "devDependencies": { + "@ljharb/eslint-config": "^21.1.0", + "@types/tape": "^5.6.4", + "aud": "^2.0.4", + "auto-changelog": "^2.4.0", + "eclint": "^2.8.1", + "eslint": "^8.8.0", + "evalmd": "^0.0.19", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.7.4", + "typescript": "next" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/gun-server/node_modules/es-errors/range.d.ts b/gun-server/node_modules/es-errors/range.d.ts new file mode 100644 index 0000000..3a12e86 --- /dev/null +++ b/gun-server/node_modules/es-errors/range.d.ts @@ -0,0 +1,3 @@ +declare const RangeError: RangeErrorConstructor; + +export = RangeError; diff --git a/gun-server/node_modules/es-errors/range.js b/gun-server/node_modules/es-errors/range.js new file mode 100644 index 0000000..2044fe0 --- /dev/null +++ b/gun-server/node_modules/es-errors/range.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./range')} */ +module.exports = RangeError; diff --git a/gun-server/node_modules/es-errors/ref.d.ts b/gun-server/node_modules/es-errors/ref.d.ts new file mode 100644 index 0000000..a13107e --- /dev/null +++ b/gun-server/node_modules/es-errors/ref.d.ts @@ -0,0 +1,3 @@ +declare const ReferenceError: ReferenceErrorConstructor; + +export = ReferenceError; diff --git a/gun-server/node_modules/es-errors/ref.js b/gun-server/node_modules/es-errors/ref.js new file mode 100644 index 0000000..d7c430f --- /dev/null +++ b/gun-server/node_modules/es-errors/ref.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./ref')} */ +module.exports = ReferenceError; diff --git a/gun-server/node_modules/es-errors/syntax.d.ts b/gun-server/node_modules/es-errors/syntax.d.ts new file mode 100644 index 0000000..6a0c53c --- /dev/null +++ b/gun-server/node_modules/es-errors/syntax.d.ts @@ -0,0 +1,3 @@ +declare const SyntaxError: SyntaxErrorConstructor; + +export = SyntaxError; diff --git a/gun-server/node_modules/es-errors/syntax.js b/gun-server/node_modules/es-errors/syntax.js new file mode 100644 index 0000000..5f5fdde --- /dev/null +++ b/gun-server/node_modules/es-errors/syntax.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./syntax')} */ +module.exports = SyntaxError; diff --git a/gun-server/node_modules/es-errors/test/index.js b/gun-server/node_modules/es-errors/test/index.js new file mode 100644 index 0000000..1ff0277 --- /dev/null +++ b/gun-server/node_modules/es-errors/test/index.js @@ -0,0 +1,19 @@ +'use strict'; + +var test = require('tape'); + +var E = require('../'); +var R = require('../range'); +var Ref = require('../ref'); +var S = require('../syntax'); +var T = require('../type'); + +test('errors', function (t) { + t.equal(E, Error); + t.equal(R, RangeError); + t.equal(Ref, ReferenceError); + t.equal(S, SyntaxError); + t.equal(T, TypeError); + + t.end(); +}); diff --git a/gun-server/node_modules/es-errors/tsconfig.json b/gun-server/node_modules/es-errors/tsconfig.json new file mode 100644 index 0000000..99dfeb6 --- /dev/null +++ b/gun-server/node_modules/es-errors/tsconfig.json @@ -0,0 +1,49 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig.json to read more about this file */ + + /* Projects */ + + /* Language and Environment */ + "target": "es5", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ + // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ + "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ + // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ + + /* Modules */ + "module": "commonjs", /* Specify what module code is generated. */ + // "rootDir": "./", /* Specify the root folder within your source files. */ + // "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */ + // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ + // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ + // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ + // "typeRoots": ["types"], /* Specify multiple folders that act like `./node_modules/@types`. */ + "resolveJsonModule": true, /* Enable importing .json files. */ + // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ + + /* JavaScript Support */ + "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */ + "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ + "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */ + + /* Emit */ + "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ + "declarationMap": true, /* Create sourcemaps for d.ts files. */ + "noEmit": true, /* Disable emitting files from a compilation. */ + + /* Interop Constraints */ + "allowSyntheticDefaultImports": true, /* Allow `import x from y` when a module doesn't have a default export. */ + "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */ + "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ + + /* Type Checking */ + "strict": true, /* Enable all strict type-checking options. */ + + /* Completeness */ + // "skipLibCheck": true /* Skip type checking all .d.ts files. */ + }, + "exclude": [ + "coverage", + ], +} diff --git a/gun-server/node_modules/es-errors/type.d.ts b/gun-server/node_modules/es-errors/type.d.ts new file mode 100644 index 0000000..576fb51 --- /dev/null +++ b/gun-server/node_modules/es-errors/type.d.ts @@ -0,0 +1,3 @@ +declare const TypeError: TypeErrorConstructor + +export = TypeError; diff --git a/gun-server/node_modules/es-errors/type.js b/gun-server/node_modules/es-errors/type.js new file mode 100644 index 0000000..9769e44 --- /dev/null +++ b/gun-server/node_modules/es-errors/type.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./type')} */ +module.exports = TypeError; diff --git a/gun-server/node_modules/es-errors/uri.d.ts b/gun-server/node_modules/es-errors/uri.d.ts new file mode 100644 index 0000000..c3261c9 --- /dev/null +++ b/gun-server/node_modules/es-errors/uri.d.ts @@ -0,0 +1,3 @@ +declare const URIError: URIErrorConstructor; + +export = URIError; diff --git a/gun-server/node_modules/es-errors/uri.js b/gun-server/node_modules/es-errors/uri.js new file mode 100644 index 0000000..e9cd1c7 --- /dev/null +++ b/gun-server/node_modules/es-errors/uri.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./uri')} */ +module.exports = URIError; diff --git a/gun-server/node_modules/escape-html/LICENSE b/gun-server/node_modules/escape-html/LICENSE new file mode 100644 index 0000000..2e70de9 --- /dev/null +++ b/gun-server/node_modules/escape-html/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2012-2013 TJ Holowaychuk +Copyright (c) 2015 Andreas Lubbe +Copyright (c) 2015 Tiancheng "Timothy" Gu + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/gun-server/node_modules/escape-html/Readme.md b/gun-server/node_modules/escape-html/Readme.md new file mode 100644 index 0000000..653d9ea --- /dev/null +++ b/gun-server/node_modules/escape-html/Readme.md @@ -0,0 +1,43 @@ + +# escape-html + + Escape string for use in HTML + +## Example + +```js +var escape = require('escape-html'); +var html = escape('foo & bar'); +// -> foo & bar +``` + +## Benchmark + +``` +$ npm run-script bench + +> escape-html@1.0.3 bench nodejs-escape-html +> node benchmark/index.js + + + http_parser@1.0 + node@0.10.33 + v8@3.14.5.9 + ares@1.9.0-DEV + uv@0.10.29 + zlib@1.2.3 + modules@11 + openssl@1.0.1j + + 1 test completed. + 2 tests completed. + 3 tests completed. + + no special characters x 19,435,271 ops/sec ±0.85% (187 runs sampled) + single special character x 6,132,421 ops/sec ±0.67% (194 runs sampled) + many special characters x 3,175,826 ops/sec ±0.65% (193 runs sampled) +``` + +## License + + MIT \ No newline at end of file diff --git a/gun-server/node_modules/escape-html/index.js b/gun-server/node_modules/escape-html/index.js new file mode 100644 index 0000000..bf9e226 --- /dev/null +++ b/gun-server/node_modules/escape-html/index.js @@ -0,0 +1,78 @@ +/*! + * escape-html + * Copyright(c) 2012-2013 TJ Holowaychuk + * Copyright(c) 2015 Andreas Lubbe + * Copyright(c) 2015 Tiancheng "Timothy" Gu + * MIT Licensed + */ + +'use strict'; + +/** + * Module variables. + * @private + */ + +var matchHtmlRegExp = /["'&<>]/; + +/** + * Module exports. + * @public + */ + +module.exports = escapeHtml; + +/** + * Escape special characters in the given string of html. + * + * @param {string} string The string to escape for inserting into HTML + * @return {string} + * @public + */ + +function escapeHtml(string) { + var str = '' + string; + var match = matchHtmlRegExp.exec(str); + + if (!match) { + return str; + } + + var escape; + var html = ''; + var index = 0; + var lastIndex = 0; + + for (index = match.index; index < str.length; index++) { + switch (str.charCodeAt(index)) { + case 34: // " + escape = '"'; + break; + case 38: // & + escape = '&'; + break; + case 39: // ' + escape = '''; + break; + case 60: // < + escape = '<'; + break; + case 62: // > + escape = '>'; + break; + default: + continue; + } + + if (lastIndex !== index) { + html += str.substring(lastIndex, index); + } + + lastIndex = index + 1; + html += escape; + } + + return lastIndex !== index + ? html + str.substring(lastIndex, index) + : html; +} diff --git a/gun-server/node_modules/escape-html/package.json b/gun-server/node_modules/escape-html/package.json new file mode 100644 index 0000000..57ec7bd --- /dev/null +++ b/gun-server/node_modules/escape-html/package.json @@ -0,0 +1,24 @@ +{ + "name": "escape-html", + "description": "Escape string for use in HTML", + "version": "1.0.3", + "license": "MIT", + "keywords": [ + "escape", + "html", + "utility" + ], + "repository": "component/escape-html", + "devDependencies": { + "benchmark": "1.0.0", + "beautify-benchmark": "0.2.4" + }, + "files": [ + "LICENSE", + "Readme.md", + "index.js" + ], + "scripts": { + "bench": "node benchmark/index.js" + } +} diff --git a/gun-server/node_modules/etag/HISTORY.md b/gun-server/node_modules/etag/HISTORY.md new file mode 100644 index 0000000..222b293 --- /dev/null +++ b/gun-server/node_modules/etag/HISTORY.md @@ -0,0 +1,83 @@ +1.8.1 / 2017-09-12 +================== + + * perf: replace regular expression with substring + +1.8.0 / 2017-02-18 +================== + + * Use SHA1 instead of MD5 for ETag hashing + - Improves performance for larger entities + - Works with FIPS 140-2 OpenSSL configuration + +1.7.0 / 2015-06-08 +================== + + * Always include entity length in ETags for hash length extensions + * Generate non-Stats ETags using MD5 only (no longer CRC32) + * Improve stat performance by removing hashing + * Remove base64 padding in ETags to shorten + * Use MD5 instead of MD4 in weak ETags over 1KB + +1.6.0 / 2015-05-10 +================== + + * Improve support for JXcore + * Remove requirement of `atime` in the stats object + * Support "fake" stats objects in environments without `fs` + +1.5.1 / 2014-11-19 +================== + + * deps: crc@3.2.1 + - Minor fixes + +1.5.0 / 2014-10-14 +================== + + * Improve string performance + * Slightly improve speed for weak ETags over 1KB + +1.4.0 / 2014-09-21 +================== + + * Support "fake" stats objects + * Support Node.js 0.6 + +1.3.1 / 2014-09-14 +================== + + * Use the (new and improved) `crc` for crc32 + +1.3.0 / 2014-08-29 +================== + + * Default strings to strong ETags + * Improve speed for weak ETags over 1KB + +1.2.1 / 2014-08-29 +================== + + * Use the (much faster) `buffer-crc32` for crc32 + +1.2.0 / 2014-08-24 +================== + + * Add support for file stat objects + +1.1.0 / 2014-08-24 +================== + + * Add fast-path for empty entity + * Add weak ETag generation + * Shrink size of generated ETags + +1.0.1 / 2014-08-24 +================== + + * Fix behavior of string containing Unicode + +1.0.0 / 2014-05-18 +================== + + * Initial release diff --git a/gun-server/node_modules/etag/LICENSE b/gun-server/node_modules/etag/LICENSE new file mode 100644 index 0000000..cab251c --- /dev/null +++ b/gun-server/node_modules/etag/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014-2016 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/gun-server/node_modules/etag/README.md b/gun-server/node_modules/etag/README.md new file mode 100644 index 0000000..09c2169 --- /dev/null +++ b/gun-server/node_modules/etag/README.md @@ -0,0 +1,159 @@ +# etag + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Create simple HTTP ETags + +This module generates HTTP ETags (as defined in RFC 7232) for use in +HTTP responses. + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install etag +``` + +## API + + + +```js +var etag = require('etag') +``` + +### etag(entity, [options]) + +Generate a strong ETag for the given entity. This should be the complete +body of the entity. Strings, `Buffer`s, and `fs.Stats` are accepted. By +default, a strong ETag is generated except for `fs.Stats`, which will +generate a weak ETag (this can be overwritten by `options.weak`). + + + +```js +res.setHeader('ETag', etag(body)) +``` + +#### Options + +`etag` accepts these properties in the options object. + +##### weak + +Specifies if the generated ETag will include the weak validator mark (that +is, the leading `W/`). The actual entity tag is the same. The default value +is `false`, unless the `entity` is `fs.Stats`, in which case it is `true`. + +## Testing + +```sh +$ npm test +``` + +## Benchmark + +```bash +$ npm run-script bench + +> etag@1.8.1 bench nodejs-etag +> node benchmark/index.js + + http_parser@2.7.0 + node@6.11.1 + v8@5.1.281.103 + uv@1.11.0 + zlib@1.2.11 + ares@1.10.1-DEV + icu@58.2 + modules@48 + openssl@1.0.2k + +> node benchmark/body0-100b.js + + 100B body + + 4 tests completed. + + buffer - strong x 258,647 ops/sec ±1.07% (180 runs sampled) + buffer - weak x 263,812 ops/sec ±0.61% (184 runs sampled) + string - strong x 259,955 ops/sec ±1.19% (185 runs sampled) + string - weak x 264,356 ops/sec ±1.09% (184 runs sampled) + +> node benchmark/body1-1kb.js + + 1KB body + + 4 tests completed. + + buffer - strong x 189,018 ops/sec ±1.12% (182 runs sampled) + buffer - weak x 190,586 ops/sec ±0.81% (186 runs sampled) + string - strong x 144,272 ops/sec ±0.96% (188 runs sampled) + string - weak x 145,380 ops/sec ±1.43% (187 runs sampled) + +> node benchmark/body2-5kb.js + + 5KB body + + 4 tests completed. + + buffer - strong x 92,435 ops/sec ±0.42% (188 runs sampled) + buffer - weak x 92,373 ops/sec ±0.58% (189 runs sampled) + string - strong x 48,850 ops/sec ±0.56% (186 runs sampled) + string - weak x 49,380 ops/sec ±0.56% (190 runs sampled) + +> node benchmark/body3-10kb.js + + 10KB body + + 4 tests completed. + + buffer - strong x 55,989 ops/sec ±0.93% (188 runs sampled) + buffer - weak x 56,148 ops/sec ±0.55% (190 runs sampled) + string - strong x 27,345 ops/sec ±0.43% (188 runs sampled) + string - weak x 27,496 ops/sec ±0.45% (190 runs sampled) + +> node benchmark/body4-100kb.js + + 100KB body + + 4 tests completed. + + buffer - strong x 7,083 ops/sec ±0.22% (190 runs sampled) + buffer - weak x 7,115 ops/sec ±0.26% (191 runs sampled) + string - strong x 3,068 ops/sec ±0.34% (190 runs sampled) + string - weak x 3,096 ops/sec ±0.35% (190 runs sampled) + +> node benchmark/stats.js + + stat + + 4 tests completed. + + real - strong x 871,642 ops/sec ±0.34% (189 runs sampled) + real - weak x 867,613 ops/sec ±0.39% (190 runs sampled) + fake - strong x 401,051 ops/sec ±0.40% (189 runs sampled) + fake - weak x 400,100 ops/sec ±0.47% (188 runs sampled) +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/etag.svg +[npm-url]: https://npmjs.org/package/etag +[node-version-image]: https://img.shields.io/node/v/etag.svg +[node-version-url]: https://nodejs.org/en/download/ +[travis-image]: https://img.shields.io/travis/jshttp/etag/master.svg +[travis-url]: https://travis-ci.org/jshttp/etag +[coveralls-image]: https://img.shields.io/coveralls/jshttp/etag/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/etag?branch=master +[downloads-image]: https://img.shields.io/npm/dm/etag.svg +[downloads-url]: https://npmjs.org/package/etag diff --git a/gun-server/node_modules/etag/index.js b/gun-server/node_modules/etag/index.js new file mode 100644 index 0000000..2a585c9 --- /dev/null +++ b/gun-server/node_modules/etag/index.js @@ -0,0 +1,131 @@ +/*! + * etag + * Copyright(c) 2014-2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = etag + +/** + * Module dependencies. + * @private + */ + +var crypto = require('crypto') +var Stats = require('fs').Stats + +/** + * Module variables. + * @private + */ + +var toString = Object.prototype.toString + +/** + * Generate an entity tag. + * + * @param {Buffer|string} entity + * @return {string} + * @private + */ + +function entitytag (entity) { + if (entity.length === 0) { + // fast-path empty + return '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"' + } + + // compute hash of entity + var hash = crypto + .createHash('sha1') + .update(entity, 'utf8') + .digest('base64') + .substring(0, 27) + + // compute length of entity + var len = typeof entity === 'string' + ? Buffer.byteLength(entity, 'utf8') + : entity.length + + return '"' + len.toString(16) + '-' + hash + '"' +} + +/** + * Create a simple ETag. + * + * @param {string|Buffer|Stats} entity + * @param {object} [options] + * @param {boolean} [options.weak] + * @return {String} + * @public + */ + +function etag (entity, options) { + if (entity == null) { + throw new TypeError('argument entity is required') + } + + // support fs.Stats object + var isStats = isstats(entity) + var weak = options && typeof options.weak === 'boolean' + ? options.weak + : isStats + + // validate argument + if (!isStats && typeof entity !== 'string' && !Buffer.isBuffer(entity)) { + throw new TypeError('argument entity must be string, Buffer, or fs.Stats') + } + + // generate entity tag + var tag = isStats + ? stattag(entity) + : entitytag(entity) + + return weak + ? 'W/' + tag + : tag +} + +/** + * Determine if object is a Stats object. + * + * @param {object} obj + * @return {boolean} + * @api private + */ + +function isstats (obj) { + // genuine fs.Stats + if (typeof Stats === 'function' && obj instanceof Stats) { + return true + } + + // quack quack + return obj && typeof obj === 'object' && + 'ctime' in obj && toString.call(obj.ctime) === '[object Date]' && + 'mtime' in obj && toString.call(obj.mtime) === '[object Date]' && + 'ino' in obj && typeof obj.ino === 'number' && + 'size' in obj && typeof obj.size === 'number' +} + +/** + * Generate a tag for a stat. + * + * @param {object} stat + * @return {string} + * @private + */ + +function stattag (stat) { + var mtime = stat.mtime.getTime().toString(16) + var size = stat.size.toString(16) + + return '"' + size + '-' + mtime + '"' +} diff --git a/gun-server/node_modules/etag/package.json b/gun-server/node_modules/etag/package.json new file mode 100644 index 0000000..b06ab80 --- /dev/null +++ b/gun-server/node_modules/etag/package.json @@ -0,0 +1,47 @@ +{ + "name": "etag", + "description": "Create simple HTTP ETags", + "version": "1.8.1", + "contributors": [ + "Douglas Christopher Wilson ", + "David Björklund " + ], + "license": "MIT", + "keywords": [ + "etag", + "http", + "res" + ], + "repository": "jshttp/etag", + "devDependencies": { + "beautify-benchmark": "0.2.4", + "benchmark": "2.1.4", + "eslint": "3.19.0", + "eslint-config-standard": "10.2.1", + "eslint-plugin-import": "2.7.0", + "eslint-plugin-markdown": "1.0.0-beta.6", + "eslint-plugin-node": "5.1.1", + "eslint-plugin-promise": "3.5.0", + "eslint-plugin-standard": "3.0.1", + "istanbul": "0.4.5", + "mocha": "1.21.5", + "safe-buffer": "5.1.1", + "seedrandom": "2.4.3" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "bench": "node benchmark/index.js", + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + } +} diff --git a/gun-server/node_modules/express/History.md b/gun-server/node_modules/express/History.md new file mode 100644 index 0000000..ac2e7cf --- /dev/null +++ b/gun-server/node_modules/express/History.md @@ -0,0 +1,3615 @@ +4.19.2 / 2024-03-25 +========== + + * Improved fix for open redirect allow list bypass + +4.19.1 / 2024-03-20 +========== + + * Allow passing non-strings to res.location with new encoding handling checks + +4.19.0 / 2024-03-20 +========== + + * Prevent open redirect allow list bypass due to encodeurl + * deps: cookie@0.6.0 + +4.18.3 / 2024-02-29 +========== + + * Fix routing requests without method + * deps: body-parser@1.20.2 + - Fix strict json error message on Node.js 19+ + - deps: content-type@~1.0.5 + - deps: raw-body@2.5.2 + * deps: cookie@0.6.0 + - Add `partitioned` option + +4.18.2 / 2022-10-08 +=================== + + * Fix regression routing a large stack in a single route + * deps: body-parser@1.20.1 + - deps: qs@6.11.0 + - perf: remove unnecessary object clone + * deps: qs@6.11.0 + +4.18.1 / 2022-04-29 +=================== + + * Fix hanging on large stack of sync routes + +4.18.0 / 2022-04-25 +=================== + + * Add "root" option to `res.download` + * Allow `options` without `filename` in `res.download` + * Deprecate string and non-integer arguments to `res.status` + * Fix behavior of `null`/`undefined` as `maxAge` in `res.cookie` + * Fix handling very large stacks of sync middleware + * Ignore `Object.prototype` values in settings through `app.set`/`app.get` + * Invoke `default` with same arguments as types in `res.format` + * Support proper 205 responses using `res.send` + * Use `http-errors` for `res.format` error + * deps: body-parser@1.20.0 + - Fix error message for json parse whitespace in `strict` + - Fix internal error when inflated body exceeds limit + - Prevent loss of async hooks context + - Prevent hanging when request already read + - deps: depd@2.0.0 + - deps: http-errors@2.0.0 + - deps: on-finished@2.4.1 + - deps: qs@6.10.3 + - deps: raw-body@2.5.1 + * deps: cookie@0.5.0 + - Add `priority` option + - Fix `expires` option to reject invalid dates + * deps: depd@2.0.0 + - Replace internal `eval` usage with `Function` constructor + - Use instance methods on `process` to check for listeners + * deps: finalhandler@1.2.0 + - Remove set content headers that break response + - deps: on-finished@2.4.1 + - deps: statuses@2.0.1 + * deps: on-finished@2.4.1 + - Prevent loss of async hooks context + * deps: qs@6.10.3 + * deps: send@0.18.0 + - Fix emitted 416 error missing headers property + - Limit the headers removed for 304 response + - deps: depd@2.0.0 + - deps: destroy@1.2.0 + - deps: http-errors@2.0.0 + - deps: on-finished@2.4.1 + - deps: statuses@2.0.1 + * deps: serve-static@1.15.0 + - deps: send@0.18.0 + * deps: statuses@2.0.1 + - Remove code 306 + - Rename `425 Unordered Collection` to standard `425 Too Early` + +4.17.3 / 2022-02-16 +=================== + + * deps: accepts@~1.3.8 + - deps: mime-types@~2.1.34 + - deps: negotiator@0.6.3 + * deps: body-parser@1.19.2 + - deps: bytes@3.1.2 + - deps: qs@6.9.7 + - deps: raw-body@2.4.3 + * deps: cookie@0.4.2 + * deps: qs@6.9.7 + * Fix handling of `__proto__` keys + * pref: remove unnecessary regexp for trust proxy + +4.17.2 / 2021-12-16 +=================== + + * Fix handling of `undefined` in `res.jsonp` + * Fix handling of `undefined` when `"json escape"` is enabled + * Fix incorrect middleware execution with unanchored `RegExp`s + * Fix `res.jsonp(obj, status)` deprecation message + * Fix typo in `res.is` JSDoc + * deps: body-parser@1.19.1 + - deps: bytes@3.1.1 + - deps: http-errors@1.8.1 + - deps: qs@6.9.6 + - deps: raw-body@2.4.2 + - deps: safe-buffer@5.2.1 + - deps: type-is@~1.6.18 + * deps: content-disposition@0.5.4 + - deps: safe-buffer@5.2.1 + * deps: cookie@0.4.1 + - Fix `maxAge` option to reject invalid values + * deps: proxy-addr@~2.0.7 + - Use `req.socket` over deprecated `req.connection` + - deps: forwarded@0.2.0 + - deps: ipaddr.js@1.9.1 + * deps: qs@6.9.6 + * deps: safe-buffer@5.2.1 + * deps: send@0.17.2 + - deps: http-errors@1.8.1 + - deps: ms@2.1.3 + - pref: ignore empty http tokens + * deps: serve-static@1.14.2 + - deps: send@0.17.2 + * deps: setprototypeof@1.2.0 + +4.17.1 / 2019-05-25 +=================== + + * Revert "Improve error message for `null`/`undefined` to `res.status`" + +4.17.0 / 2019-05-16 +=================== + + * Add `express.raw` to parse bodies into `Buffer` + * Add `express.text` to parse bodies into string + * Improve error message for non-strings to `res.sendFile` + * Improve error message for `null`/`undefined` to `res.status` + * Support multiple hosts in `X-Forwarded-Host` + * deps: accepts@~1.3.7 + * deps: body-parser@1.19.0 + - Add encoding MIK + - Add petabyte (`pb`) support + - Fix parsing array brackets after index + - deps: bytes@3.1.0 + - deps: http-errors@1.7.2 + - deps: iconv-lite@0.4.24 + - deps: qs@6.7.0 + - deps: raw-body@2.4.0 + - deps: type-is@~1.6.17 + * deps: content-disposition@0.5.3 + * deps: cookie@0.4.0 + - Add `SameSite=None` support + * deps: finalhandler@~1.1.2 + - Set stricter `Content-Security-Policy` header + - deps: parseurl@~1.3.3 + - deps: statuses@~1.5.0 + * deps: parseurl@~1.3.3 + * deps: proxy-addr@~2.0.5 + - deps: ipaddr.js@1.9.0 + * deps: qs@6.7.0 + - Fix parsing array brackets after index + * deps: range-parser@~1.2.1 + * deps: send@0.17.1 + - Set stricter CSP header in redirect & error responses + - deps: http-errors@~1.7.2 + - deps: mime@1.6.0 + - deps: ms@2.1.1 + - deps: range-parser@~1.2.1 + - deps: statuses@~1.5.0 + - perf: remove redundant `path.normalize` call + * deps: serve-static@1.14.1 + - Set stricter CSP header in redirect response + - deps: parseurl@~1.3.3 + - deps: send@0.17.1 + * deps: setprototypeof@1.1.1 + * deps: statuses@~1.5.0 + - Add `103 Early Hints` + * deps: type-is@~1.6.18 + - deps: mime-types@~2.1.24 + - perf: prevent internal `throw` on invalid type + +4.16.4 / 2018-10-10 +=================== + + * Fix issue where `"Request aborted"` may be logged in `res.sendfile` + * Fix JSDoc for `Router` constructor + * deps: body-parser@1.18.3 + - Fix deprecation warnings on Node.js 10+ + - Fix stack trace for strict json parse error + - deps: depd@~1.1.2 + - deps: http-errors@~1.6.3 + - deps: iconv-lite@0.4.23 + - deps: qs@6.5.2 + - deps: raw-body@2.3.3 + - deps: type-is@~1.6.16 + * deps: proxy-addr@~2.0.4 + - deps: ipaddr.js@1.8.0 + * deps: qs@6.5.2 + * deps: safe-buffer@5.1.2 + +4.16.3 / 2018-03-12 +=================== + + * deps: accepts@~1.3.5 + - deps: mime-types@~2.1.18 + * deps: depd@~1.1.2 + - perf: remove argument reassignment + * deps: encodeurl@~1.0.2 + - Fix encoding `%` as last character + * deps: finalhandler@1.1.1 + - Fix 404 output for bad / missing pathnames + - deps: encodeurl@~1.0.2 + - deps: statuses@~1.4.0 + * deps: proxy-addr@~2.0.3 + - deps: ipaddr.js@1.6.0 + * deps: send@0.16.2 + - Fix incorrect end tag in default error & redirects + - deps: depd@~1.1.2 + - deps: encodeurl@~1.0.2 + - deps: statuses@~1.4.0 + * deps: serve-static@1.13.2 + - Fix incorrect end tag in redirects + - deps: encodeurl@~1.0.2 + - deps: send@0.16.2 + * deps: statuses@~1.4.0 + * deps: type-is@~1.6.16 + - deps: mime-types@~2.1.18 + +4.16.2 / 2017-10-09 +=================== + + * Fix `TypeError` in `res.send` when given `Buffer` and `ETag` header set + * perf: skip parsing of entire `X-Forwarded-Proto` header + +4.16.1 / 2017-09-29 +=================== + + * deps: send@0.16.1 + * deps: serve-static@1.13.1 + - Fix regression when `root` is incorrectly set to a file + - deps: send@0.16.1 + +4.16.0 / 2017-09-28 +=================== + + * Add `"json escape"` setting for `res.json` and `res.jsonp` + * Add `express.json` and `express.urlencoded` to parse bodies + * Add `options` argument to `res.download` + * Improve error message when autoloading invalid view engine + * Improve error messages when non-function provided as middleware + * Skip `Buffer` encoding when not generating ETag for small response + * Use `safe-buffer` for improved Buffer API + * deps: accepts@~1.3.4 + - deps: mime-types@~2.1.16 + * deps: content-type@~1.0.4 + - perf: remove argument reassignment + - perf: skip parameter parsing when no parameters + * deps: etag@~1.8.1 + - perf: replace regular expression with substring + * deps: finalhandler@1.1.0 + - Use `res.headersSent` when available + * deps: parseurl@~1.3.2 + - perf: reduce overhead for full URLs + - perf: unroll the "fast-path" `RegExp` + * deps: proxy-addr@~2.0.2 + - Fix trimming leading / trailing OWS in `X-Forwarded-For` + - deps: forwarded@~0.1.2 + - deps: ipaddr.js@1.5.2 + - perf: reduce overhead when no `X-Forwarded-For` header + * deps: qs@6.5.1 + - Fix parsing & compacting very deep objects + * deps: send@0.16.0 + - Add 70 new types for file extensions + - Add `immutable` option + - Fix missing `` in default error & redirects + - Set charset as "UTF-8" for .js and .json + - Use instance methods on steam to check for listeners + - deps: mime@1.4.1 + - perf: improve path validation speed + * deps: serve-static@1.13.0 + - Add 70 new types for file extensions + - Add `immutable` option + - Set charset as "UTF-8" for .js and .json + - deps: send@0.16.0 + * deps: setprototypeof@1.1.0 + * deps: utils-merge@1.0.1 + * deps: vary@~1.1.2 + - perf: improve header token parsing speed + * perf: re-use options object when generating ETags + * perf: remove dead `.charset` set in `res.jsonp` + +4.15.5 / 2017-09-24 +=================== + + * deps: debug@2.6.9 + * deps: finalhandler@~1.0.6 + - deps: debug@2.6.9 + - deps: parseurl@~1.3.2 + * deps: fresh@0.5.2 + - Fix handling of modified headers with invalid dates + - perf: improve ETag match loop + - perf: improve `If-None-Match` token parsing + * deps: send@0.15.6 + - Fix handling of modified headers with invalid dates + - deps: debug@2.6.9 + - deps: etag@~1.8.1 + - deps: fresh@0.5.2 + - perf: improve `If-Match` token parsing + * deps: serve-static@1.12.6 + - deps: parseurl@~1.3.2 + - deps: send@0.15.6 + - perf: improve slash collapsing + +4.15.4 / 2017-08-06 +=================== + + * deps: debug@2.6.8 + * deps: depd@~1.1.1 + - Remove unnecessary `Buffer` loading + * deps: finalhandler@~1.0.4 + - deps: debug@2.6.8 + * deps: proxy-addr@~1.1.5 + - Fix array argument being altered + - deps: ipaddr.js@1.4.0 + * deps: qs@6.5.0 + * deps: send@0.15.4 + - deps: debug@2.6.8 + - deps: depd@~1.1.1 + - deps: http-errors@~1.6.2 + * deps: serve-static@1.12.4 + - deps: send@0.15.4 + +4.15.3 / 2017-05-16 +=================== + + * Fix error when `res.set` cannot add charset to `Content-Type` + * deps: debug@2.6.7 + - Fix `DEBUG_MAX_ARRAY_LENGTH` + - deps: ms@2.0.0 + * deps: finalhandler@~1.0.3 + - Fix missing `` in HTML document + - deps: debug@2.6.7 + * deps: proxy-addr@~1.1.4 + - deps: ipaddr.js@1.3.0 + * deps: send@0.15.3 + - deps: debug@2.6.7 + - deps: ms@2.0.0 + * deps: serve-static@1.12.3 + - deps: send@0.15.3 + * deps: type-is@~1.6.15 + - deps: mime-types@~2.1.15 + * deps: vary@~1.1.1 + - perf: hoist regular expression + +4.15.2 / 2017-03-06 +=================== + + * deps: qs@6.4.0 + - Fix regression parsing keys starting with `[` + +4.15.1 / 2017-03-05 +=================== + + * deps: send@0.15.1 + - Fix issue when `Date.parse` does not return `NaN` on invalid date + - Fix strict violation in broken environments + * deps: serve-static@1.12.1 + - Fix issue when `Date.parse` does not return `NaN` on invalid date + - deps: send@0.15.1 + +4.15.0 / 2017-03-01 +=================== + + * Add debug message when loading view engine + * Add `next("router")` to exit from router + * Fix case where `router.use` skipped requests routes did not + * Remove usage of `res._headers` private field + - Improves compatibility with Node.js 8 nightly + * Skip routing when `req.url` is not set + * Use `%o` in path debug to tell types apart + * Use `Object.create` to setup request & response prototypes + * Use `setprototypeof` module to replace `__proto__` setting + * Use `statuses` instead of `http` module for status messages + * deps: debug@2.6.1 + - Allow colors in workers + - Deprecated `DEBUG_FD` environment variable set to `3` or higher + - Fix error when running under React Native + - Use same color for same namespace + - deps: ms@0.7.2 + * deps: etag@~1.8.0 + - Use SHA1 instead of MD5 for ETag hashing + - Works with FIPS 140-2 OpenSSL configuration + * deps: finalhandler@~1.0.0 + - Fix exception when `err` cannot be converted to a string + - Fully URL-encode the pathname in the 404 + - Only include the pathname in the 404 message + - Send complete HTML document + - Set `Content-Security-Policy: default-src 'self'` header + - deps: debug@2.6.1 + * deps: fresh@0.5.0 + - Fix false detection of `no-cache` request directive + - Fix incorrect result when `If-None-Match` has both `*` and ETags + - Fix weak `ETag` matching to match spec + - perf: delay reading header values until needed + - perf: enable strict mode + - perf: hoist regular expressions + - perf: remove duplicate conditional + - perf: remove unnecessary boolean coercions + - perf: skip checking modified time if ETag check failed + - perf: skip parsing `If-None-Match` when no `ETag` header + - perf: use `Date.parse` instead of `new Date` + * deps: qs@6.3.1 + - Fix array parsing from skipping empty values + - Fix compacting nested arrays + * deps: send@0.15.0 + - Fix false detection of `no-cache` request directive + - Fix incorrect result when `If-None-Match` has both `*` and ETags + - Fix weak `ETag` matching to match spec + - Remove usage of `res._headers` private field + - Support `If-Match` and `If-Unmodified-Since` headers + - Use `res.getHeaderNames()` when available + - Use `res.headersSent` when available + - deps: debug@2.6.1 + - deps: etag@~1.8.0 + - deps: fresh@0.5.0 + - deps: http-errors@~1.6.1 + * deps: serve-static@1.12.0 + - Fix false detection of `no-cache` request directive + - Fix incorrect result when `If-None-Match` has both `*` and ETags + - Fix weak `ETag` matching to match spec + - Remove usage of `res._headers` private field + - Send complete HTML document in redirect response + - Set default CSP header in redirect response + - Support `If-Match` and `If-Unmodified-Since` headers + - Use `res.getHeaderNames()` when available + - Use `res.headersSent` when available + - deps: send@0.15.0 + * perf: add fast match path for `*` route + * perf: improve `req.ips` performance + +4.14.1 / 2017-01-28 +=================== + + * deps: content-disposition@0.5.2 + * deps: finalhandler@0.5.1 + - Fix exception when `err.headers` is not an object + - deps: statuses@~1.3.1 + - perf: hoist regular expressions + - perf: remove duplicate validation path + * deps: proxy-addr@~1.1.3 + - deps: ipaddr.js@1.2.0 + * deps: send@0.14.2 + - deps: http-errors@~1.5.1 + - deps: ms@0.7.2 + - deps: statuses@~1.3.1 + * deps: serve-static@~1.11.2 + - deps: send@0.14.2 + * deps: type-is@~1.6.14 + - deps: mime-types@~2.1.13 + +4.14.0 / 2016-06-16 +=================== + + * Add `acceptRanges` option to `res.sendFile`/`res.sendfile` + * Add `cacheControl` option to `res.sendFile`/`res.sendfile` + * Add `options` argument to `req.range` + - Includes the `combine` option + * Encode URL in `res.location`/`res.redirect` if not already encoded + * Fix some redirect handling in `res.sendFile`/`res.sendfile` + * Fix Windows absolute path check using forward slashes + * Improve error with invalid arguments to `req.get()` + * Improve performance for `res.json`/`res.jsonp` in most cases + * Improve `Range` header handling in `res.sendFile`/`res.sendfile` + * deps: accepts@~1.3.3 + - Fix including type extensions in parameters in `Accept` parsing + - Fix parsing `Accept` parameters with quoted equals + - Fix parsing `Accept` parameters with quoted semicolons + - Many performance improvements + - deps: mime-types@~2.1.11 + - deps: negotiator@0.6.1 + * deps: content-type@~1.0.2 + - perf: enable strict mode + * deps: cookie@0.3.1 + - Add `sameSite` option + - Fix cookie `Max-Age` to never be a floating point number + - Improve error message when `encode` is not a function + - Improve error message when `expires` is not a `Date` + - Throw better error for invalid argument to parse + - Throw on invalid values provided to `serialize` + - perf: enable strict mode + - perf: hoist regular expression + - perf: use for loop in parse + - perf: use string concatenation for serialization + * deps: finalhandler@0.5.0 + - Change invalid or non-numeric status code to 500 + - Overwrite status message to match set status code + - Prefer `err.statusCode` if `err.status` is invalid + - Set response headers from `err.headers` object + - Use `statuses` instead of `http` module for status messages + * deps: proxy-addr@~1.1.2 + - Fix accepting various invalid netmasks + - Fix IPv6-mapped IPv4 validation edge cases + - IPv4 netmasks must be contiguous + - IPv6 addresses cannot be used as a netmask + - deps: ipaddr.js@1.1.1 + * deps: qs@6.2.0 + - Add `decoder` option in `parse` function + * deps: range-parser@~1.2.0 + - Add `combine` option to combine overlapping ranges + - Fix incorrectly returning -1 when there is at least one valid range + - perf: remove internal function + * deps: send@0.14.1 + - Add `acceptRanges` option + - Add `cacheControl` option + - Attempt to combine multiple ranges into single range + - Correctly inherit from `Stream` class + - Fix `Content-Range` header in 416 responses when using `start`/`end` options + - Fix `Content-Range` header missing from default 416 responses + - Fix redirect error when `path` contains raw non-URL characters + - Fix redirect when `path` starts with multiple forward slashes + - Ignore non-byte `Range` headers + - deps: http-errors@~1.5.0 + - deps: range-parser@~1.2.0 + - deps: statuses@~1.3.0 + - perf: remove argument reassignment + * deps: serve-static@~1.11.1 + - Add `acceptRanges` option + - Add `cacheControl` option + - Attempt to combine multiple ranges into single range + - Fix redirect error when `req.url` contains raw non-URL characters + - Ignore non-byte `Range` headers + - Use status code 301 for redirects + - deps: send@0.14.1 + * deps: type-is@~1.6.13 + - Fix type error when given invalid type to match against + - deps: mime-types@~2.1.11 + * deps: vary@~1.1.0 + - Only accept valid field names in the `field` argument + * perf: use strict equality when possible + +4.13.4 / 2016-01-21 +=================== + + * deps: content-disposition@0.5.1 + - perf: enable strict mode + * deps: cookie@0.1.5 + - Throw on invalid values provided to `serialize` + * deps: depd@~1.1.0 + - Support web browser loading + - perf: enable strict mode + * deps: escape-html@~1.0.3 + - perf: enable strict mode + - perf: optimize string replacement + - perf: use faster string coercion + * deps: finalhandler@0.4.1 + - deps: escape-html@~1.0.3 + * deps: merge-descriptors@1.0.1 + - perf: enable strict mode + * deps: methods@~1.1.2 + - perf: enable strict mode + * deps: parseurl@~1.3.1 + - perf: enable strict mode + * deps: proxy-addr@~1.0.10 + - deps: ipaddr.js@1.0.5 + - perf: enable strict mode + * deps: range-parser@~1.0.3 + - perf: enable strict mode + * deps: send@0.13.1 + - deps: depd@~1.1.0 + - deps: destroy@~1.0.4 + - deps: escape-html@~1.0.3 + - deps: range-parser@~1.0.3 + * deps: serve-static@~1.10.2 + - deps: escape-html@~1.0.3 + - deps: parseurl@~1.3.0 + - deps: send@0.13.1 + +4.13.3 / 2015-08-02 +=================== + + * Fix infinite loop condition using `mergeParams: true` + * Fix inner numeric indices incorrectly altering parent `req.params` + +4.13.2 / 2015-07-31 +=================== + + * deps: accepts@~1.2.12 + - deps: mime-types@~2.1.4 + * deps: array-flatten@1.1.1 + - perf: enable strict mode + * deps: path-to-regexp@0.1.7 + - Fix regression with escaped round brackets and matching groups + * deps: type-is@~1.6.6 + - deps: mime-types@~2.1.4 + +4.13.1 / 2015-07-05 +=================== + + * deps: accepts@~1.2.10 + - deps: mime-types@~2.1.2 + * deps: qs@4.0.0 + - Fix dropping parameters like `hasOwnProperty` + - Fix various parsing edge cases + * deps: type-is@~1.6.4 + - deps: mime-types@~2.1.2 + - perf: enable strict mode + - perf: remove argument reassignment + +4.13.0 / 2015-06-20 +=================== + + * Add settings to debug output + * Fix `res.format` error when only `default` provided + * Fix issue where `next('route')` in `app.param` would incorrectly skip values + * Fix hiding platform issues with `decodeURIComponent` + - Only `URIError`s are a 400 + * Fix using `*` before params in routes + * Fix using capture groups before params in routes + * Simplify `res.cookie` to call `res.append` + * Use `array-flatten` module for flattening arrays + * deps: accepts@~1.2.9 + - deps: mime-types@~2.1.1 + - perf: avoid argument reassignment & argument slice + - perf: avoid negotiator recursive construction + - perf: enable strict mode + - perf: remove unnecessary bitwise operator + * deps: cookie@0.1.3 + - perf: deduce the scope of try-catch deopt + - perf: remove argument reassignments + * deps: escape-html@1.0.2 + * deps: etag@~1.7.0 + - Always include entity length in ETags for hash length extensions + - Generate non-Stats ETags using MD5 only (no longer CRC32) + - Improve stat performance by removing hashing + - Improve support for JXcore + - Remove base64 padding in ETags to shorten + - Support "fake" stats objects in environments without fs + - Use MD5 instead of MD4 in weak ETags over 1KB + * deps: finalhandler@0.4.0 + - Fix a false-positive when unpiping in Node.js 0.8 + - Support `statusCode` property on `Error` objects + - Use `unpipe` module for unpiping requests + - deps: escape-html@1.0.2 + - deps: on-finished@~2.3.0 + - perf: enable strict mode + - perf: remove argument reassignment + * deps: fresh@0.3.0 + - Add weak `ETag` matching support + * deps: on-finished@~2.3.0 + - Add defined behavior for HTTP `CONNECT` requests + - Add defined behavior for HTTP `Upgrade` requests + - deps: ee-first@1.1.1 + * deps: path-to-regexp@0.1.6 + * deps: send@0.13.0 + - Allow Node.js HTTP server to set `Date` response header + - Fix incorrectly removing `Content-Location` on 304 response + - Improve the default redirect response headers + - Send appropriate headers on default error response + - Use `http-errors` for standard emitted errors + - Use `statuses` instead of `http` module for status messages + - deps: escape-html@1.0.2 + - deps: etag@~1.7.0 + - deps: fresh@0.3.0 + - deps: on-finished@~2.3.0 + - perf: enable strict mode + - perf: remove unnecessary array allocations + * deps: serve-static@~1.10.0 + - Add `fallthrough` option + - Fix reading options from options prototype + - Improve the default redirect response headers + - Malformed URLs now `next()` instead of 400 + - deps: escape-html@1.0.2 + - deps: send@0.13.0 + - perf: enable strict mode + - perf: remove argument reassignment + * deps: type-is@~1.6.3 + - deps: mime-types@~2.1.1 + - perf: reduce try block size + - perf: remove bitwise operations + * perf: enable strict mode + * perf: isolate `app.render` try block + * perf: remove argument reassignments in application + * perf: remove argument reassignments in request prototype + * perf: remove argument reassignments in response prototype + * perf: remove argument reassignments in routing + * perf: remove argument reassignments in `View` + * perf: skip attempting to decode zero length string + * perf: use saved reference to `http.STATUS_CODES` + +4.12.4 / 2015-05-17 +=================== + + * deps: accepts@~1.2.7 + - deps: mime-types@~2.0.11 + - deps: negotiator@0.5.3 + * deps: debug@~2.2.0 + - deps: ms@0.7.1 + * deps: depd@~1.0.1 + * deps: etag@~1.6.0 + - Improve support for JXcore + - Support "fake" stats objects in environments without `fs` + * deps: finalhandler@0.3.6 + - deps: debug@~2.2.0 + - deps: on-finished@~2.2.1 + * deps: on-finished@~2.2.1 + - Fix `isFinished(req)` when data buffered + * deps: proxy-addr@~1.0.8 + - deps: ipaddr.js@1.0.1 + * deps: qs@2.4.2 + - Fix allowing parameters like `constructor` + * deps: send@0.12.3 + - deps: debug@~2.2.0 + - deps: depd@~1.0.1 + - deps: etag@~1.6.0 + - deps: ms@0.7.1 + - deps: on-finished@~2.2.1 + * deps: serve-static@~1.9.3 + - deps: send@0.12.3 + * deps: type-is@~1.6.2 + - deps: mime-types@~2.0.11 + +4.12.3 / 2015-03-17 +=================== + + * deps: accepts@~1.2.5 + - deps: mime-types@~2.0.10 + * deps: debug@~2.1.3 + - Fix high intensity foreground color for bold + - deps: ms@0.7.0 + * deps: finalhandler@0.3.4 + - deps: debug@~2.1.3 + * deps: proxy-addr@~1.0.7 + - deps: ipaddr.js@0.1.9 + * deps: qs@2.4.1 + - Fix error when parameter `hasOwnProperty` is present + * deps: send@0.12.2 + - Throw errors early for invalid `extensions` or `index` options + - deps: debug@~2.1.3 + * deps: serve-static@~1.9.2 + - deps: send@0.12.2 + * deps: type-is@~1.6.1 + - deps: mime-types@~2.0.10 + +4.12.2 / 2015-03-02 +=================== + + * Fix regression where `"Request aborted"` is logged using `res.sendFile` + +4.12.1 / 2015-03-01 +=================== + + * Fix constructing application with non-configurable prototype properties + * Fix `ECONNRESET` errors from `res.sendFile` usage + * Fix `req.host` when using "trust proxy" hops count + * Fix `req.protocol`/`req.secure` when using "trust proxy" hops count + * Fix wrong `code` on aborted connections from `res.sendFile` + * deps: merge-descriptors@1.0.0 + +4.12.0 / 2015-02-23 +=================== + + * Fix `"trust proxy"` setting to inherit when app is mounted + * Generate `ETag`s for all request responses + - No longer restricted to only responses for `GET` and `HEAD` requests + * Use `content-type` to parse `Content-Type` headers + * deps: accepts@~1.2.4 + - Fix preference sorting to be stable for long acceptable lists + - deps: mime-types@~2.0.9 + - deps: negotiator@0.5.1 + * deps: cookie-signature@1.0.6 + * deps: send@0.12.1 + - Always read the stat size from the file + - Fix mutating passed-in `options` + - deps: mime@1.3.4 + * deps: serve-static@~1.9.1 + - deps: send@0.12.1 + * deps: type-is@~1.6.0 + - fix argument reassignment + - fix false-positives in `hasBody` `Transfer-Encoding` check + - support wildcard for both type and subtype (`*/*`) + - deps: mime-types@~2.0.9 + +4.11.2 / 2015-02-01 +=================== + + * Fix `res.redirect` double-calling `res.end` for `HEAD` requests + * deps: accepts@~1.2.3 + - deps: mime-types@~2.0.8 + * deps: proxy-addr@~1.0.6 + - deps: ipaddr.js@0.1.8 + * deps: type-is@~1.5.6 + - deps: mime-types@~2.0.8 + +4.11.1 / 2015-01-20 +=================== + + * deps: send@0.11.1 + - Fix root path disclosure + * deps: serve-static@~1.8.1 + - Fix redirect loop in Node.js 0.11.14 + - Fix root path disclosure + - deps: send@0.11.1 + +4.11.0 / 2015-01-13 +=================== + + * Add `res.append(field, val)` to append headers + * Deprecate leading `:` in `name` for `app.param(name, fn)` + * Deprecate `req.param()` -- use `req.params`, `req.body`, or `req.query` instead + * Deprecate `app.param(fn)` + * Fix `OPTIONS` responses to include the `HEAD` method properly + * Fix `res.sendFile` not always detecting aborted connection + * Match routes iteratively to prevent stack overflows + * deps: accepts@~1.2.2 + - deps: mime-types@~2.0.7 + - deps: negotiator@0.5.0 + * deps: send@0.11.0 + - deps: debug@~2.1.1 + - deps: etag@~1.5.1 + - deps: ms@0.7.0 + - deps: on-finished@~2.2.0 + * deps: serve-static@~1.8.0 + - deps: send@0.11.0 + +4.10.8 / 2015-01-13 +=================== + + * Fix crash from error within `OPTIONS` response handler + * deps: proxy-addr@~1.0.5 + - deps: ipaddr.js@0.1.6 + +4.10.7 / 2015-01-04 +=================== + + * Fix `Allow` header for `OPTIONS` to not contain duplicate methods + * Fix incorrect "Request aborted" for `res.sendFile` when `HEAD` or 304 + * deps: debug@~2.1.1 + * deps: finalhandler@0.3.3 + - deps: debug@~2.1.1 + - deps: on-finished@~2.2.0 + * deps: methods@~1.1.1 + * deps: on-finished@~2.2.0 + * deps: serve-static@~1.7.2 + - Fix potential open redirect when mounted at root + * deps: type-is@~1.5.5 + - deps: mime-types@~2.0.7 + +4.10.6 / 2014-12-12 +=================== + + * Fix exception in `req.fresh`/`req.stale` without response headers + +4.10.5 / 2014-12-10 +=================== + + * Fix `res.send` double-calling `res.end` for `HEAD` requests + * deps: accepts@~1.1.4 + - deps: mime-types@~2.0.4 + * deps: type-is@~1.5.4 + - deps: mime-types@~2.0.4 + +4.10.4 / 2014-11-24 +=================== + + * Fix `res.sendfile` logging standard write errors + +4.10.3 / 2014-11-23 +=================== + + * Fix `res.sendFile` logging standard write errors + * deps: etag@~1.5.1 + * deps: proxy-addr@~1.0.4 + - deps: ipaddr.js@0.1.5 + * deps: qs@2.3.3 + - Fix `arrayLimit` behavior + +4.10.2 / 2014-11-09 +=================== + + * Correctly invoke async router callback asynchronously + * deps: accepts@~1.1.3 + - deps: mime-types@~2.0.3 + * deps: type-is@~1.5.3 + - deps: mime-types@~2.0.3 + +4.10.1 / 2014-10-28 +=================== + + * Fix handling of URLs containing `://` in the path + * deps: qs@2.3.2 + - Fix parsing of mixed objects and values + +4.10.0 / 2014-10-23 +=================== + + * Add support for `app.set('views', array)` + - Views are looked up in sequence in array of directories + * Fix `res.send(status)` to mention `res.sendStatus(status)` + * Fix handling of invalid empty URLs + * Use `content-disposition` module for `res.attachment`/`res.download` + - Sends standards-compliant `Content-Disposition` header + - Full Unicode support + * Use `path.resolve` in view lookup + * deps: debug@~2.1.0 + - Implement `DEBUG_FD` env variable support + * deps: depd@~1.0.0 + * deps: etag@~1.5.0 + - Improve string performance + - Slightly improve speed for weak ETags over 1KB + * deps: finalhandler@0.3.2 + - Terminate in progress response only on error + - Use `on-finished` to determine request status + - deps: debug@~2.1.0 + - deps: on-finished@~2.1.1 + * deps: on-finished@~2.1.1 + - Fix handling of pipelined requests + * deps: qs@2.3.0 + - Fix parsing of mixed implicit and explicit arrays + * deps: send@0.10.1 + - deps: debug@~2.1.0 + - deps: depd@~1.0.0 + - deps: etag@~1.5.0 + - deps: on-finished@~2.1.1 + * deps: serve-static@~1.7.1 + - deps: send@0.10.1 + +4.9.8 / 2014-10-17 +================== + + * Fix `res.redirect` body when redirect status specified + * deps: accepts@~1.1.2 + - Fix error when media type has invalid parameter + - deps: negotiator@0.4.9 + +4.9.7 / 2014-10-10 +================== + + * Fix using same param name in array of paths + +4.9.6 / 2014-10-08 +================== + + * deps: accepts@~1.1.1 + - deps: mime-types@~2.0.2 + - deps: negotiator@0.4.8 + * deps: serve-static@~1.6.4 + - Fix redirect loop when index file serving disabled + * deps: type-is@~1.5.2 + - deps: mime-types@~2.0.2 + +4.9.5 / 2014-09-24 +================== + + * deps: etag@~1.4.0 + * deps: proxy-addr@~1.0.3 + - Use `forwarded` npm module + * deps: send@0.9.3 + - deps: etag@~1.4.0 + * deps: serve-static@~1.6.3 + - deps: send@0.9.3 + +4.9.4 / 2014-09-19 +================== + + * deps: qs@2.2.4 + - Fix issue with object keys starting with numbers truncated + +4.9.3 / 2014-09-18 +================== + + * deps: proxy-addr@~1.0.2 + - Fix a global leak when multiple subnets are trusted + - deps: ipaddr.js@0.1.3 + +4.9.2 / 2014-09-17 +================== + + * Fix regression for empty string `path` in `app.use` + * Fix `router.use` to accept array of middleware without path + * Improve error message for bad `app.use` arguments + +4.9.1 / 2014-09-16 +================== + + * Fix `app.use` to accept array of middleware without path + * deps: depd@0.4.5 + * deps: etag@~1.3.1 + * deps: send@0.9.2 + - deps: depd@0.4.5 + - deps: etag@~1.3.1 + - deps: range-parser@~1.0.2 + * deps: serve-static@~1.6.2 + - deps: send@0.9.2 + +4.9.0 / 2014-09-08 +================== + + * Add `res.sendStatus` + * Invoke callback for sendfile when client aborts + - Applies to `res.sendFile`, `res.sendfile`, and `res.download` + - `err` will be populated with request aborted error + * Support IP address host in `req.subdomains` + * Use `etag` to generate `ETag` headers + * deps: accepts@~1.1.0 + - update `mime-types` + * deps: cookie-signature@1.0.5 + * deps: debug@~2.0.0 + * deps: finalhandler@0.2.0 + - Set `X-Content-Type-Options: nosniff` header + - deps: debug@~2.0.0 + * deps: fresh@0.2.4 + * deps: media-typer@0.3.0 + - Throw error when parameter format invalid on parse + * deps: qs@2.2.3 + - Fix issue where first empty value in array is discarded + * deps: range-parser@~1.0.2 + * deps: send@0.9.1 + - Add `lastModified` option + - Use `etag` to generate `ETag` header + - deps: debug@~2.0.0 + - deps: fresh@0.2.4 + * deps: serve-static@~1.6.1 + - Add `lastModified` option + - deps: send@0.9.1 + * deps: type-is@~1.5.1 + - fix `hasbody` to be true for `content-length: 0` + - deps: media-typer@0.3.0 + - deps: mime-types@~2.0.1 + * deps: vary@~1.0.0 + - Accept valid `Vary` header string as `field` + +4.8.8 / 2014-09-04 +================== + + * deps: send@0.8.5 + - Fix a path traversal issue when using `root` + - Fix malicious path detection for empty string path + * deps: serve-static@~1.5.4 + - deps: send@0.8.5 + +4.8.7 / 2014-08-29 +================== + + * deps: qs@2.2.2 + - Remove unnecessary cloning + +4.8.6 / 2014-08-27 +================== + + * deps: qs@2.2.0 + - Array parsing fix + - Performance improvements + +4.8.5 / 2014-08-18 +================== + + * deps: send@0.8.3 + - deps: destroy@1.0.3 + - deps: on-finished@2.1.0 + * deps: serve-static@~1.5.3 + - deps: send@0.8.3 + +4.8.4 / 2014-08-14 +================== + + * deps: qs@1.2.2 + * deps: send@0.8.2 + - Work around `fd` leak in Node.js 0.10 for `fs.ReadStream` + * deps: serve-static@~1.5.2 + - deps: send@0.8.2 + +4.8.3 / 2014-08-10 +================== + + * deps: parseurl@~1.3.0 + * deps: qs@1.2.1 + * deps: serve-static@~1.5.1 + - Fix parsing of weird `req.originalUrl` values + - deps: parseurl@~1.3.0 + - deps: utils-merge@1.0.0 + +4.8.2 / 2014-08-07 +================== + + * deps: qs@1.2.0 + - Fix parsing array of objects + +4.8.1 / 2014-08-06 +================== + + * fix incorrect deprecation warnings on `res.download` + * deps: qs@1.1.0 + - Accept urlencoded square brackets + - Accept empty values in implicit array notation + +4.8.0 / 2014-08-05 +================== + + * add `res.sendFile` + - accepts a file system path instead of a URL + - requires an absolute path or `root` option specified + * deprecate `res.sendfile` -- use `res.sendFile` instead + * support mounted app as any argument to `app.use()` + * deps: qs@1.0.2 + - Complete rewrite + - Limits array length to 20 + - Limits object depth to 5 + - Limits parameters to 1,000 + * deps: send@0.8.1 + - Add `extensions` option + * deps: serve-static@~1.5.0 + - Add `extensions` option + - deps: send@0.8.1 + +4.7.4 / 2014-08-04 +================== + + * fix `res.sendfile` regression for serving directory index files + * deps: send@0.7.4 + - Fix incorrect 403 on Windows and Node.js 0.11 + - Fix serving index files without root dir + * deps: serve-static@~1.4.4 + - deps: send@0.7.4 + +4.7.3 / 2014-08-04 +================== + + * deps: send@0.7.3 + - Fix incorrect 403 on Windows and Node.js 0.11 + * deps: serve-static@~1.4.3 + - Fix incorrect 403 on Windows and Node.js 0.11 + - deps: send@0.7.3 + +4.7.2 / 2014-07-27 +================== + + * deps: depd@0.4.4 + - Work-around v8 generating empty stack traces + * deps: send@0.7.2 + - deps: depd@0.4.4 + * deps: serve-static@~1.4.2 + +4.7.1 / 2014-07-26 +================== + + * deps: depd@0.4.3 + - Fix exception when global `Error.stackTraceLimit` is too low + * deps: send@0.7.1 + - deps: depd@0.4.3 + * deps: serve-static@~1.4.1 + +4.7.0 / 2014-07-25 +================== + + * fix `req.protocol` for proxy-direct connections + * configurable query parser with `app.set('query parser', parser)` + - `app.set('query parser', 'extended')` parse with "qs" module + - `app.set('query parser', 'simple')` parse with "querystring" core module + - `app.set('query parser', false)` disable query string parsing + - `app.set('query parser', true)` enable simple parsing + * deprecate `res.json(status, obj)` -- use `res.status(status).json(obj)` instead + * deprecate `res.jsonp(status, obj)` -- use `res.status(status).jsonp(obj)` instead + * deprecate `res.send(status, body)` -- use `res.status(status).send(body)` instead + * deps: debug@1.0.4 + * deps: depd@0.4.2 + - Add `TRACE_DEPRECATION` environment variable + - Remove non-standard grey color from color output + - Support `--no-deprecation` argument + - Support `--trace-deprecation` argument + * deps: finalhandler@0.1.0 + - Respond after request fully read + - deps: debug@1.0.4 + * deps: parseurl@~1.2.0 + - Cache URLs based on original value + - Remove no-longer-needed URL mis-parse work-around + - Simplify the "fast-path" `RegExp` + * deps: send@0.7.0 + - Add `dotfiles` option + - Cap `maxAge` value to 1 year + - deps: debug@1.0.4 + - deps: depd@0.4.2 + * deps: serve-static@~1.4.0 + - deps: parseurl@~1.2.0 + - deps: send@0.7.0 + * perf: prevent multiple `Buffer` creation in `res.send` + +4.6.1 / 2014-07-12 +================== + + * fix `subapp.mountpath` regression for `app.use(subapp)` + +4.6.0 / 2014-07-11 +================== + + * accept multiple callbacks to `app.use()` + * add explicit "Rosetta Flash JSONP abuse" protection + - previous versions are not vulnerable; this is just explicit protection + * catch errors in multiple `req.param(name, fn)` handlers + * deprecate `res.redirect(url, status)` -- use `res.redirect(status, url)` instead + * fix `res.send(status, num)` to send `num` as json (not error) + * remove unnecessary escaping when `res.jsonp` returns JSON response + * support non-string `path` in `app.use(path, fn)` + - supports array of paths + - supports `RegExp` + * router: fix optimization on router exit + * router: refactor location of `try` blocks + * router: speed up standard `app.use(fn)` + * deps: debug@1.0.3 + - Add support for multiple wildcards in namespaces + * deps: finalhandler@0.0.3 + - deps: debug@1.0.3 + * deps: methods@1.1.0 + - add `CONNECT` + * deps: parseurl@~1.1.3 + - faster parsing of href-only URLs + * deps: path-to-regexp@0.1.3 + * deps: send@0.6.0 + - deps: debug@1.0.3 + * deps: serve-static@~1.3.2 + - deps: parseurl@~1.1.3 + - deps: send@0.6.0 + * perf: fix arguments reassign deopt in some `res` methods + +4.5.1 / 2014-07-06 +================== + + * fix routing regression when altering `req.method` + +4.5.0 / 2014-07-04 +================== + + * add deprecation message to non-plural `req.accepts*` + * add deprecation message to `res.send(body, status)` + * add deprecation message to `res.vary()` + * add `headers` option to `res.sendfile` + - use to set headers on successful file transfer + * add `mergeParams` option to `Router` + - merges `req.params` from parent routes + * add `req.hostname` -- correct name for what `req.host` returns + * deprecate things with `depd` module + * deprecate `req.host` -- use `req.hostname` instead + * fix behavior when handling request without routes + * fix handling when `route.all` is only route + * invoke `router.param()` only when route matches + * restore `req.params` after invoking router + * use `finalhandler` for final response handling + * use `media-typer` to alter content-type charset + * deps: accepts@~1.0.7 + * deps: send@0.5.0 + - Accept string for `maxage` (converted by `ms`) + - Include link in default redirect response + * deps: serve-static@~1.3.0 + - Accept string for `maxAge` (converted by `ms`) + - Add `setHeaders` option + - Include HTML link in redirect response + - deps: send@0.5.0 + * deps: type-is@~1.3.2 + +4.4.5 / 2014-06-26 +================== + + * deps: cookie-signature@1.0.4 + - fix for timing attacks + +4.4.4 / 2014-06-20 +================== + + * fix `res.attachment` Unicode filenames in Safari + * fix "trim prefix" debug message in `express:router` + * deps: accepts@~1.0.5 + * deps: buffer-crc32@0.2.3 + +4.4.3 / 2014-06-11 +================== + + * fix persistence of modified `req.params[name]` from `app.param()` + * deps: accepts@1.0.3 + - deps: negotiator@0.4.6 + * deps: debug@1.0.2 + * deps: send@0.4.3 + - Do not throw uncatchable error on file open race condition + - Use `escape-html` for HTML escaping + - deps: debug@1.0.2 + - deps: finished@1.2.2 + - deps: fresh@0.2.2 + * deps: serve-static@1.2.3 + - Do not throw uncatchable error on file open race condition + - deps: send@0.4.3 + +4.4.2 / 2014-06-09 +================== + + * fix catching errors from top-level handlers + * use `vary` module for `res.vary` + * deps: debug@1.0.1 + * deps: proxy-addr@1.0.1 + * deps: send@0.4.2 + - fix "event emitter leak" warnings + - deps: debug@1.0.1 + - deps: finished@1.2.1 + * deps: serve-static@1.2.2 + - fix "event emitter leak" warnings + - deps: send@0.4.2 + * deps: type-is@1.2.1 + +4.4.1 / 2014-06-02 +================== + + * deps: methods@1.0.1 + * deps: send@0.4.1 + - Send `max-age` in `Cache-Control` in correct format + * deps: serve-static@1.2.1 + - use `escape-html` for escaping + - deps: send@0.4.1 + +4.4.0 / 2014-05-30 +================== + + * custom etag control with `app.set('etag', val)` + - `app.set('etag', function(body, encoding){ return '"etag"' })` custom etag generation + - `app.set('etag', 'weak')` weak tag + - `app.set('etag', 'strong')` strong etag + - `app.set('etag', false)` turn off + - `app.set('etag', true)` standard etag + * mark `res.send` ETag as weak and reduce collisions + * update accepts to 1.0.2 + - Fix interpretation when header not in request + * update send to 0.4.0 + - Calculate ETag with md5 for reduced collisions + - Ignore stream errors after request ends + - deps: debug@0.8.1 + * update serve-static to 1.2.0 + - Calculate ETag with md5 for reduced collisions + - Ignore stream errors after request ends + - deps: send@0.4.0 + +4.3.2 / 2014-05-28 +================== + + * fix handling of errors from `router.param()` callbacks + +4.3.1 / 2014-05-23 +================== + + * revert "fix behavior of multiple `app.VERB` for the same path" + - this caused a regression in the order of route execution + +4.3.0 / 2014-05-21 +================== + + * add `req.baseUrl` to access the path stripped from `req.url` in routes + * fix behavior of multiple `app.VERB` for the same path + * fix issue routing requests among sub routers + * invoke `router.param()` only when necessary instead of every match + * proper proxy trust with `app.set('trust proxy', trust)` + - `app.set('trust proxy', 1)` trust first hop + - `app.set('trust proxy', 'loopback')` trust loopback addresses + - `app.set('trust proxy', '10.0.0.1')` trust single IP + - `app.set('trust proxy', '10.0.0.1/16')` trust subnet + - `app.set('trust proxy', '10.0.0.1, 10.0.0.2')` trust list + - `app.set('trust proxy', false)` turn off + - `app.set('trust proxy', true)` trust everything + * set proper `charset` in `Content-Type` for `res.send` + * update type-is to 1.2.0 + - support suffix matching + +4.2.0 / 2014-05-11 +================== + + * deprecate `app.del()` -- use `app.delete()` instead + * deprecate `res.json(obj, status)` -- use `res.json(status, obj)` instead + - the edge-case `res.json(status, num)` requires `res.status(status).json(num)` + * deprecate `res.jsonp(obj, status)` -- use `res.jsonp(status, obj)` instead + - the edge-case `res.jsonp(status, num)` requires `res.status(status).jsonp(num)` + * fix `req.next` when inside router instance + * include `ETag` header in `HEAD` requests + * keep previous `Content-Type` for `res.jsonp` + * support PURGE method + - add `app.purge` + - add `router.purge` + - include PURGE in `app.all` + * update debug to 0.8.0 + - add `enable()` method + - change from stderr to stdout + * update methods to 1.0.0 + - add PURGE + +4.1.2 / 2014-05-08 +================== + + * fix `req.host` for IPv6 literals + * fix `res.jsonp` error if callback param is object + +4.1.1 / 2014-04-27 +================== + + * fix package.json to reflect supported node version + +4.1.0 / 2014-04-24 +================== + + * pass options from `res.sendfile` to `send` + * preserve casing of headers in `res.header` and `res.set` + * support unicode file names in `res.attachment` and `res.download` + * update accepts to 1.0.1 + - deps: negotiator@0.4.0 + * update cookie to 0.1.2 + - Fix for maxAge == 0 + - made compat with expires field + * update send to 0.3.0 + - Accept API options in options object + - Coerce option types + - Control whether to generate etags + - Default directory access to 403 when index disabled + - Fix sending files with dots without root set + - Include file path in etag + - Make "Can't set headers after they are sent." catchable + - Send full entity-body for multi range requests + - Set etags to "weak" + - Support "If-Range" header + - Support multiple index paths + - deps: mime@1.2.11 + * update serve-static to 1.1.0 + - Accept options directly to `send` module + - Resolve relative paths at middleware setup + - Use parseurl to parse the URL from request + - deps: send@0.3.0 + * update type-is to 1.1.0 + - add non-array values support + - add `multipart` as a shorthand + +4.0.0 / 2014-04-09 +================== + + * remove: + - node 0.8 support + - connect and connect's patches except for charset handling + - express(1) - moved to [express-generator](https://github.com/expressjs/generator) + - `express.createServer()` - it has been deprecated for a long time. Use `express()` + - `app.configure` - use logic in your own app code + - `app.router` - is removed + - `req.auth` - use `basic-auth` instead + - `req.accepted*` - use `req.accepts*()` instead + - `res.location` - relative URL resolution is removed + - `res.charset` - include the charset in the content type when using `res.set()` + - all bundled middleware except `static` + * change: + - `app.route` -> `app.mountpath` when mounting an express app in another express app + - `json spaces` no longer enabled by default in development + - `req.accepts*` -> `req.accepts*s` - i.e. `req.acceptsEncoding` -> `req.acceptsEncodings` + - `req.params` is now an object instead of an array + - `res.locals` is no longer a function. It is a plain js object. Treat it as such. + - `res.headerSent` -> `res.headersSent` to match node.js ServerResponse object + * refactor: + - `req.accepts*` with [accepts](https://github.com/expressjs/accepts) + - `req.is` with [type-is](https://github.com/expressjs/type-is) + - [path-to-regexp](https://github.com/component/path-to-regexp) + * add: + - `app.router()` - returns the app Router instance + - `app.route()` - Proxy to the app's `Router#route()` method to create a new route + - Router & Route - public API + +3.21.2 / 2015-07-31 +=================== + + * deps: connect@2.30.2 + - deps: body-parser@~1.13.3 + - deps: compression@~1.5.2 + - deps: errorhandler@~1.4.2 + - deps: method-override@~2.3.5 + - deps: serve-index@~1.7.2 + - deps: type-is@~1.6.6 + - deps: vhost@~3.0.1 + * deps: vary@~1.0.1 + - Fix setting empty header from empty `field` + - perf: enable strict mode + - perf: remove argument reassignments + +3.21.1 / 2015-07-05 +=================== + + * deps: basic-auth@~1.0.3 + * deps: connect@2.30.1 + - deps: body-parser@~1.13.2 + - deps: compression@~1.5.1 + - deps: errorhandler@~1.4.1 + - deps: morgan@~1.6.1 + - deps: pause@0.1.0 + - deps: qs@4.0.0 + - deps: serve-index@~1.7.1 + - deps: type-is@~1.6.4 + +3.21.0 / 2015-06-18 +=================== + + * deps: basic-auth@1.0.2 + - perf: enable strict mode + - perf: hoist regular expression + - perf: parse with regular expressions + - perf: remove argument reassignment + * deps: connect@2.30.0 + - deps: body-parser@~1.13.1 + - deps: bytes@2.1.0 + - deps: compression@~1.5.0 + - deps: cookie@0.1.3 + - deps: cookie-parser@~1.3.5 + - deps: csurf@~1.8.3 + - deps: errorhandler@~1.4.0 + - deps: express-session@~1.11.3 + - deps: finalhandler@0.4.0 + - deps: fresh@0.3.0 + - deps: morgan@~1.6.0 + - deps: serve-favicon@~2.3.0 + - deps: serve-index@~1.7.0 + - deps: serve-static@~1.10.0 + - deps: type-is@~1.6.3 + * deps: cookie@0.1.3 + - perf: deduce the scope of try-catch deopt + - perf: remove argument reassignments + * deps: escape-html@1.0.2 + * deps: etag@~1.7.0 + - Always include entity length in ETags for hash length extensions + - Generate non-Stats ETags using MD5 only (no longer CRC32) + - Improve stat performance by removing hashing + - Improve support for JXcore + - Remove base64 padding in ETags to shorten + - Support "fake" stats objects in environments without fs + - Use MD5 instead of MD4 in weak ETags over 1KB + * deps: fresh@0.3.0 + - Add weak `ETag` matching support + * deps: mkdirp@0.5.1 + - Work in global strict mode + * deps: send@0.13.0 + - Allow Node.js HTTP server to set `Date` response header + - Fix incorrectly removing `Content-Location` on 304 response + - Improve the default redirect response headers + - Send appropriate headers on default error response + - Use `http-errors` for standard emitted errors + - Use `statuses` instead of `http` module for status messages + - deps: escape-html@1.0.2 + - deps: etag@~1.7.0 + - deps: fresh@0.3.0 + - deps: on-finished@~2.3.0 + - perf: enable strict mode + - perf: remove unnecessary array allocations + +3.20.3 / 2015-05-17 +=================== + + * deps: connect@2.29.2 + - deps: body-parser@~1.12.4 + - deps: compression@~1.4.4 + - deps: connect-timeout@~1.6.2 + - deps: debug@~2.2.0 + - deps: depd@~1.0.1 + - deps: errorhandler@~1.3.6 + - deps: finalhandler@0.3.6 + - deps: method-override@~2.3.3 + - deps: morgan@~1.5.3 + - deps: qs@2.4.2 + - deps: response-time@~2.3.1 + - deps: serve-favicon@~2.2.1 + - deps: serve-index@~1.6.4 + - deps: serve-static@~1.9.3 + - deps: type-is@~1.6.2 + * deps: debug@~2.2.0 + - deps: ms@0.7.1 + * deps: depd@~1.0.1 + * deps: proxy-addr@~1.0.8 + - deps: ipaddr.js@1.0.1 + * deps: send@0.12.3 + - deps: debug@~2.2.0 + - deps: depd@~1.0.1 + - deps: etag@~1.6.0 + - deps: ms@0.7.1 + - deps: on-finished@~2.2.1 + +3.20.2 / 2015-03-16 +=================== + + * deps: connect@2.29.1 + - deps: body-parser@~1.12.2 + - deps: compression@~1.4.3 + - deps: connect-timeout@~1.6.1 + - deps: debug@~2.1.3 + - deps: errorhandler@~1.3.5 + - deps: express-session@~1.10.4 + - deps: finalhandler@0.3.4 + - deps: method-override@~2.3.2 + - deps: morgan@~1.5.2 + - deps: qs@2.4.1 + - deps: serve-index@~1.6.3 + - deps: serve-static@~1.9.2 + - deps: type-is@~1.6.1 + * deps: debug@~2.1.3 + - Fix high intensity foreground color for bold + - deps: ms@0.7.0 + * deps: merge-descriptors@1.0.0 + * deps: proxy-addr@~1.0.7 + - deps: ipaddr.js@0.1.9 + * deps: send@0.12.2 + - Throw errors early for invalid `extensions` or `index` options + - deps: debug@~2.1.3 + +3.20.1 / 2015-02-28 +=================== + + * Fix `req.host` when using "trust proxy" hops count + * Fix `req.protocol`/`req.secure` when using "trust proxy" hops count + +3.20.0 / 2015-02-18 +=================== + + * Fix `"trust proxy"` setting to inherit when app is mounted + * Generate `ETag`s for all request responses + - No longer restricted to only responses for `GET` and `HEAD` requests + * Use `content-type` to parse `Content-Type` headers + * deps: connect@2.29.0 + - Use `content-type` to parse `Content-Type` headers + - deps: body-parser@~1.12.0 + - deps: compression@~1.4.1 + - deps: connect-timeout@~1.6.0 + - deps: cookie-parser@~1.3.4 + - deps: cookie-signature@1.0.6 + - deps: csurf@~1.7.0 + - deps: errorhandler@~1.3.4 + - deps: express-session@~1.10.3 + - deps: http-errors@~1.3.1 + - deps: response-time@~2.3.0 + - deps: serve-index@~1.6.2 + - deps: serve-static@~1.9.1 + - deps: type-is@~1.6.0 + * deps: cookie-signature@1.0.6 + * deps: send@0.12.1 + - Always read the stat size from the file + - Fix mutating passed-in `options` + - deps: mime@1.3.4 + +3.19.2 / 2015-02-01 +=================== + + * deps: connect@2.28.3 + - deps: compression@~1.3.1 + - deps: csurf@~1.6.6 + - deps: errorhandler@~1.3.3 + - deps: express-session@~1.10.2 + - deps: serve-index@~1.6.1 + - deps: type-is@~1.5.6 + * deps: proxy-addr@~1.0.6 + - deps: ipaddr.js@0.1.8 + +3.19.1 / 2015-01-20 +=================== + + * deps: connect@2.28.2 + - deps: body-parser@~1.10.2 + - deps: serve-static@~1.8.1 + * deps: send@0.11.1 + - Fix root path disclosure + +3.19.0 / 2015-01-09 +=================== + + * Fix `OPTIONS` responses to include the `HEAD` method property + * Use `readline` for prompt in `express(1)` + * deps: commander@2.6.0 + * deps: connect@2.28.1 + - deps: body-parser@~1.10.1 + - deps: compression@~1.3.0 + - deps: connect-timeout@~1.5.0 + - deps: csurf@~1.6.4 + - deps: debug@~2.1.1 + - deps: errorhandler@~1.3.2 + - deps: express-session@~1.10.1 + - deps: finalhandler@0.3.3 + - deps: method-override@~2.3.1 + - deps: morgan@~1.5.1 + - deps: serve-favicon@~2.2.0 + - deps: serve-index@~1.6.0 + - deps: serve-static@~1.8.0 + - deps: type-is@~1.5.5 + * deps: debug@~2.1.1 + * deps: methods@~1.1.1 + * deps: proxy-addr@~1.0.5 + - deps: ipaddr.js@0.1.6 + * deps: send@0.11.0 + - deps: debug@~2.1.1 + - deps: etag@~1.5.1 + - deps: ms@0.7.0 + - deps: on-finished@~2.2.0 + +3.18.6 / 2014-12-12 +=================== + + * Fix exception in `req.fresh`/`req.stale` without response headers + +3.18.5 / 2014-12-11 +=================== + + * deps: connect@2.27.6 + - deps: compression@~1.2.2 + - deps: express-session@~1.9.3 + - deps: http-errors@~1.2.8 + - deps: serve-index@~1.5.3 + - deps: type-is@~1.5.4 + +3.18.4 / 2014-11-23 +=================== + + * deps: connect@2.27.4 + - deps: body-parser@~1.9.3 + - deps: compression@~1.2.1 + - deps: errorhandler@~1.2.3 + - deps: express-session@~1.9.2 + - deps: qs@2.3.3 + - deps: serve-favicon@~2.1.7 + - deps: serve-static@~1.5.1 + - deps: type-is@~1.5.3 + * deps: etag@~1.5.1 + * deps: proxy-addr@~1.0.4 + - deps: ipaddr.js@0.1.5 + +3.18.3 / 2014-11-09 +=================== + + * deps: connect@2.27.3 + - Correctly invoke async callback asynchronously + - deps: csurf@~1.6.3 + +3.18.2 / 2014-10-28 +=================== + + * deps: connect@2.27.2 + - Fix handling of URLs containing `://` in the path + - deps: body-parser@~1.9.2 + - deps: qs@2.3.2 + +3.18.1 / 2014-10-22 +=================== + + * Fix internal `utils.merge` deprecation warnings + * deps: connect@2.27.1 + - deps: body-parser@~1.9.1 + - deps: express-session@~1.9.1 + - deps: finalhandler@0.3.2 + - deps: morgan@~1.4.1 + - deps: qs@2.3.0 + - deps: serve-static@~1.7.1 + * deps: send@0.10.1 + - deps: on-finished@~2.1.1 + +3.18.0 / 2014-10-17 +=================== + + * Use `content-disposition` module for `res.attachment`/`res.download` + - Sends standards-compliant `Content-Disposition` header + - Full Unicode support + * Use `etag` module to generate `ETag` headers + * deps: connect@2.27.0 + - Use `http-errors` module for creating errors + - Use `utils-merge` module for merging objects + - deps: body-parser@~1.9.0 + - deps: compression@~1.2.0 + - deps: connect-timeout@~1.4.0 + - deps: debug@~2.1.0 + - deps: depd@~1.0.0 + - deps: express-session@~1.9.0 + - deps: finalhandler@0.3.1 + - deps: method-override@~2.3.0 + - deps: morgan@~1.4.0 + - deps: response-time@~2.2.0 + - deps: serve-favicon@~2.1.6 + - deps: serve-index@~1.5.0 + - deps: serve-static@~1.7.0 + * deps: debug@~2.1.0 + - Implement `DEBUG_FD` env variable support + * deps: depd@~1.0.0 + * deps: send@0.10.0 + - deps: debug@~2.1.0 + - deps: depd@~1.0.0 + - deps: etag@~1.5.0 + +3.17.8 / 2014-10-15 +=================== + + * deps: connect@2.26.6 + - deps: compression@~1.1.2 + - deps: csurf@~1.6.2 + - deps: errorhandler@~1.2.2 + +3.17.7 / 2014-10-08 +=================== + + * deps: connect@2.26.5 + - Fix accepting non-object arguments to `logger` + - deps: serve-static@~1.6.4 + +3.17.6 / 2014-10-02 +=================== + + * deps: connect@2.26.4 + - deps: morgan@~1.3.2 + - deps: type-is@~1.5.2 + +3.17.5 / 2014-09-24 +=================== + + * deps: connect@2.26.3 + - deps: body-parser@~1.8.4 + - deps: serve-favicon@~2.1.5 + - deps: serve-static@~1.6.3 + * deps: proxy-addr@~1.0.3 + - Use `forwarded` npm module + * deps: send@0.9.3 + - deps: etag@~1.4.0 + +3.17.4 / 2014-09-19 +=================== + + * deps: connect@2.26.2 + - deps: body-parser@~1.8.3 + - deps: qs@2.2.4 + +3.17.3 / 2014-09-18 +=================== + + * deps: proxy-addr@~1.0.2 + - Fix a global leak when multiple subnets are trusted + - deps: ipaddr.js@0.1.3 + +3.17.2 / 2014-09-15 +=================== + + * Use `crc` instead of `buffer-crc32` for speed + * deps: connect@2.26.1 + - deps: body-parser@~1.8.2 + - deps: depd@0.4.5 + - deps: express-session@~1.8.2 + - deps: morgan@~1.3.1 + - deps: serve-favicon@~2.1.3 + - deps: serve-static@~1.6.2 + * deps: depd@0.4.5 + * deps: send@0.9.2 + - deps: depd@0.4.5 + - deps: etag@~1.3.1 + - deps: range-parser@~1.0.2 + +3.17.1 / 2014-09-08 +=================== + + * Fix error in `req.subdomains` on empty host + +3.17.0 / 2014-09-08 +=================== + + * Support `X-Forwarded-Host` in `req.subdomains` + * Support IP address host in `req.subdomains` + * deps: connect@2.26.0 + - deps: body-parser@~1.8.1 + - deps: compression@~1.1.0 + - deps: connect-timeout@~1.3.0 + - deps: cookie-parser@~1.3.3 + - deps: cookie-signature@1.0.5 + - deps: csurf@~1.6.1 + - deps: debug@~2.0.0 + - deps: errorhandler@~1.2.0 + - deps: express-session@~1.8.1 + - deps: finalhandler@0.2.0 + - deps: fresh@0.2.4 + - deps: media-typer@0.3.0 + - deps: method-override@~2.2.0 + - deps: morgan@~1.3.0 + - deps: qs@2.2.3 + - deps: serve-favicon@~2.1.3 + - deps: serve-index@~1.2.1 + - deps: serve-static@~1.6.1 + - deps: type-is@~1.5.1 + - deps: vhost@~3.0.0 + * deps: cookie-signature@1.0.5 + * deps: debug@~2.0.0 + * deps: fresh@0.2.4 + * deps: media-typer@0.3.0 + - Throw error when parameter format invalid on parse + * deps: range-parser@~1.0.2 + * deps: send@0.9.1 + - Add `lastModified` option + - Use `etag` to generate `ETag` header + - deps: debug@~2.0.0 + - deps: fresh@0.2.4 + * deps: vary@~1.0.0 + - Accept valid `Vary` header string as `field` + +3.16.10 / 2014-09-04 +==================== + + * deps: connect@2.25.10 + - deps: serve-static@~1.5.4 + * deps: send@0.8.5 + - Fix a path traversal issue when using `root` + - Fix malicious path detection for empty string path + +3.16.9 / 2014-08-29 +=================== + + * deps: connect@2.25.9 + - deps: body-parser@~1.6.7 + - deps: qs@2.2.2 + +3.16.8 / 2014-08-27 +=================== + + * deps: connect@2.25.8 + - deps: body-parser@~1.6.6 + - deps: csurf@~1.4.1 + - deps: qs@2.2.0 + +3.16.7 / 2014-08-18 +=================== + + * deps: connect@2.25.7 + - deps: body-parser@~1.6.5 + - deps: express-session@~1.7.6 + - deps: morgan@~1.2.3 + - deps: serve-static@~1.5.3 + * deps: send@0.8.3 + - deps: destroy@1.0.3 + - deps: on-finished@2.1.0 + +3.16.6 / 2014-08-14 +=================== + + * deps: connect@2.25.6 + - deps: body-parser@~1.6.4 + - deps: qs@1.2.2 + - deps: serve-static@~1.5.2 + * deps: send@0.8.2 + - Work around `fd` leak in Node.js 0.10 for `fs.ReadStream` + +3.16.5 / 2014-08-11 +=================== + + * deps: connect@2.25.5 + - Fix backwards compatibility in `logger` + +3.16.4 / 2014-08-10 +=================== + + * Fix original URL parsing in `res.location` + * deps: connect@2.25.4 + - Fix `query` middleware breaking with argument + - deps: body-parser@~1.6.3 + - deps: compression@~1.0.11 + - deps: connect-timeout@~1.2.2 + - deps: express-session@~1.7.5 + - deps: method-override@~2.1.3 + - deps: on-headers@~1.0.0 + - deps: parseurl@~1.3.0 + - deps: qs@1.2.1 + - deps: response-time@~2.0.1 + - deps: serve-index@~1.1.6 + - deps: serve-static@~1.5.1 + * deps: parseurl@~1.3.0 + +3.16.3 / 2014-08-07 +=================== + + * deps: connect@2.25.3 + - deps: multiparty@3.3.2 + +3.16.2 / 2014-08-07 +=================== + + * deps: connect@2.25.2 + - deps: body-parser@~1.6.2 + - deps: qs@1.2.0 + +3.16.1 / 2014-08-06 +=================== + + * deps: connect@2.25.1 + - deps: body-parser@~1.6.1 + - deps: qs@1.1.0 + +3.16.0 / 2014-08-05 +=================== + + * deps: connect@2.25.0 + - deps: body-parser@~1.6.0 + - deps: compression@~1.0.10 + - deps: csurf@~1.4.0 + - deps: express-session@~1.7.4 + - deps: qs@1.0.2 + - deps: serve-static@~1.5.0 + * deps: send@0.8.1 + - Add `extensions` option + +3.15.3 / 2014-08-04 +=================== + + * fix `res.sendfile` regression for serving directory index files + * deps: connect@2.24.3 + - deps: serve-index@~1.1.5 + - deps: serve-static@~1.4.4 + * deps: send@0.7.4 + - Fix incorrect 403 on Windows and Node.js 0.11 + - Fix serving index files without root dir + +3.15.2 / 2014-07-27 +=================== + + * deps: connect@2.24.2 + - deps: body-parser@~1.5.2 + - deps: depd@0.4.4 + - deps: express-session@~1.7.2 + - deps: morgan@~1.2.2 + - deps: serve-static@~1.4.2 + * deps: depd@0.4.4 + - Work-around v8 generating empty stack traces + * deps: send@0.7.2 + - deps: depd@0.4.4 + +3.15.1 / 2014-07-26 +=================== + + * deps: connect@2.24.1 + - deps: body-parser@~1.5.1 + - deps: depd@0.4.3 + - deps: express-session@~1.7.1 + - deps: morgan@~1.2.1 + - deps: serve-index@~1.1.4 + - deps: serve-static@~1.4.1 + * deps: depd@0.4.3 + - Fix exception when global `Error.stackTraceLimit` is too low + * deps: send@0.7.1 + - deps: depd@0.4.3 + +3.15.0 / 2014-07-22 +=================== + + * Fix `req.protocol` for proxy-direct connections + * Pass options from `res.sendfile` to `send` + * deps: connect@2.24.0 + - deps: body-parser@~1.5.0 + - deps: compression@~1.0.9 + - deps: connect-timeout@~1.2.1 + - deps: debug@1.0.4 + - deps: depd@0.4.2 + - deps: express-session@~1.7.0 + - deps: finalhandler@0.1.0 + - deps: method-override@~2.1.2 + - deps: morgan@~1.2.0 + - deps: multiparty@3.3.1 + - deps: parseurl@~1.2.0 + - deps: serve-static@~1.4.0 + * deps: debug@1.0.4 + * deps: depd@0.4.2 + - Add `TRACE_DEPRECATION` environment variable + - Remove non-standard grey color from color output + - Support `--no-deprecation` argument + - Support `--trace-deprecation` argument + * deps: parseurl@~1.2.0 + - Cache URLs based on original value + - Remove no-longer-needed URL mis-parse work-around + - Simplify the "fast-path" `RegExp` + * deps: send@0.7.0 + - Add `dotfiles` option + - Cap `maxAge` value to 1 year + - deps: debug@1.0.4 + - deps: depd@0.4.2 + +3.14.0 / 2014-07-11 +=================== + + * add explicit "Rosetta Flash JSONP abuse" protection + - previous versions are not vulnerable; this is just explicit protection + * deprecate `res.redirect(url, status)` -- use `res.redirect(status, url)` instead + * fix `res.send(status, num)` to send `num` as json (not error) + * remove unnecessary escaping when `res.jsonp` returns JSON response + * deps: basic-auth@1.0.0 + - support empty password + - support empty username + * deps: connect@2.23.0 + - deps: debug@1.0.3 + - deps: express-session@~1.6.4 + - deps: method-override@~2.1.0 + - deps: parseurl@~1.1.3 + - deps: serve-static@~1.3.1 + * deps: debug@1.0.3 + - Add support for multiple wildcards in namespaces + * deps: methods@1.1.0 + - add `CONNECT` + * deps: parseurl@~1.1.3 + - faster parsing of href-only URLs + +3.13.0 / 2014-07-03 +=================== + + * add deprecation message to `app.configure` + * add deprecation message to `req.auth` + * use `basic-auth` to parse `Authorization` header + * deps: connect@2.22.0 + - deps: csurf@~1.3.0 + - deps: express-session@~1.6.1 + - deps: multiparty@3.3.0 + - deps: serve-static@~1.3.0 + * deps: send@0.5.0 + - Accept string for `maxage` (converted by `ms`) + - Include link in default redirect response + +3.12.1 / 2014-06-26 +=================== + + * deps: connect@2.21.1 + - deps: cookie-parser@1.3.2 + - deps: cookie-signature@1.0.4 + - deps: express-session@~1.5.2 + - deps: type-is@~1.3.2 + * deps: cookie-signature@1.0.4 + - fix for timing attacks + +3.12.0 / 2014-06-21 +=================== + + * use `media-typer` to alter content-type charset + * deps: connect@2.21.0 + - deprecate `connect(middleware)` -- use `app.use(middleware)` instead + - deprecate `connect.createServer()` -- use `connect()` instead + - fix `res.setHeader()` patch to work with get -> append -> set pattern + - deps: compression@~1.0.8 + - deps: errorhandler@~1.1.1 + - deps: express-session@~1.5.0 + - deps: serve-index@~1.1.3 + +3.11.0 / 2014-06-19 +=================== + + * deprecate things with `depd` module + * deps: buffer-crc32@0.2.3 + * deps: connect@2.20.2 + - deprecate `verify` option to `json` -- use `body-parser` npm module instead + - deprecate `verify` option to `urlencoded` -- use `body-parser` npm module instead + - deprecate things with `depd` module + - use `finalhandler` for final response handling + - use `media-typer` to parse `content-type` for charset + - deps: body-parser@1.4.3 + - deps: connect-timeout@1.1.1 + - deps: cookie-parser@1.3.1 + - deps: csurf@1.2.2 + - deps: errorhandler@1.1.0 + - deps: express-session@1.4.0 + - deps: multiparty@3.2.9 + - deps: serve-index@1.1.2 + - deps: type-is@1.3.1 + - deps: vhost@2.0.0 + +3.10.5 / 2014-06-11 +=================== + + * deps: connect@2.19.6 + - deps: body-parser@1.3.1 + - deps: compression@1.0.7 + - deps: debug@1.0.2 + - deps: serve-index@1.1.1 + - deps: serve-static@1.2.3 + * deps: debug@1.0.2 + * deps: send@0.4.3 + - Do not throw uncatchable error on file open race condition + - Use `escape-html` for HTML escaping + - deps: debug@1.0.2 + - deps: finished@1.2.2 + - deps: fresh@0.2.2 + +3.10.4 / 2014-06-09 +=================== + + * deps: connect@2.19.5 + - fix "event emitter leak" warnings + - deps: csurf@1.2.1 + - deps: debug@1.0.1 + - deps: serve-static@1.2.2 + - deps: type-is@1.2.1 + * deps: debug@1.0.1 + * deps: send@0.4.2 + - fix "event emitter leak" warnings + - deps: finished@1.2.1 + - deps: debug@1.0.1 + +3.10.3 / 2014-06-05 +=================== + + * use `vary` module for `res.vary` + * deps: connect@2.19.4 + - deps: errorhandler@1.0.2 + - deps: method-override@2.0.2 + - deps: serve-favicon@2.0.1 + * deps: debug@1.0.0 + +3.10.2 / 2014-06-03 +=================== + + * deps: connect@2.19.3 + - deps: compression@1.0.6 + +3.10.1 / 2014-06-03 +=================== + + * deps: connect@2.19.2 + - deps: compression@1.0.4 + * deps: proxy-addr@1.0.1 + +3.10.0 / 2014-06-02 +=================== + + * deps: connect@2.19.1 + - deprecate `methodOverride()` -- use `method-override` npm module instead + - deps: body-parser@1.3.0 + - deps: method-override@2.0.1 + - deps: multiparty@3.2.8 + - deps: response-time@2.0.0 + - deps: serve-static@1.2.1 + * deps: methods@1.0.1 + * deps: send@0.4.1 + - Send `max-age` in `Cache-Control` in correct format + +3.9.0 / 2014-05-30 +================== + + * custom etag control with `app.set('etag', val)` + - `app.set('etag', function(body, encoding){ return '"etag"' })` custom etag generation + - `app.set('etag', 'weak')` weak tag + - `app.set('etag', 'strong')` strong etag + - `app.set('etag', false)` turn off + - `app.set('etag', true)` standard etag + * Include ETag in HEAD requests + * mark `res.send` ETag as weak and reduce collisions + * update connect to 2.18.0 + - deps: compression@1.0.3 + - deps: serve-index@1.1.0 + - deps: serve-static@1.2.0 + * update send to 0.4.0 + - Calculate ETag with md5 for reduced collisions + - Ignore stream errors after request ends + - deps: debug@0.8.1 + +3.8.1 / 2014-05-27 +================== + + * update connect to 2.17.3 + - deps: body-parser@1.2.2 + - deps: express-session@1.2.1 + - deps: method-override@1.0.2 + +3.8.0 / 2014-05-21 +================== + + * keep previous `Content-Type` for `res.jsonp` + * set proper `charset` in `Content-Type` for `res.send` + * update connect to 2.17.1 + - fix `res.charset` appending charset when `content-type` has one + - deps: express-session@1.2.0 + - deps: morgan@1.1.1 + - deps: serve-index@1.0.3 + +3.7.0 / 2014-05-18 +================== + + * proper proxy trust with `app.set('trust proxy', trust)` + - `app.set('trust proxy', 1)` trust first hop + - `app.set('trust proxy', 'loopback')` trust loopback addresses + - `app.set('trust proxy', '10.0.0.1')` trust single IP + - `app.set('trust proxy', '10.0.0.1/16')` trust subnet + - `app.set('trust proxy', '10.0.0.1, 10.0.0.2')` trust list + - `app.set('trust proxy', false)` turn off + - `app.set('trust proxy', true)` trust everything + * update connect to 2.16.2 + - deprecate `res.headerSent` -- use `res.headersSent` + - deprecate `res.on("header")` -- use on-headers module instead + - fix edge-case in `res.appendHeader` that would append in wrong order + - json: use body-parser + - urlencoded: use body-parser + - dep: bytes@1.0.0 + - dep: cookie-parser@1.1.0 + - dep: csurf@1.2.0 + - dep: express-session@1.1.0 + - dep: method-override@1.0.1 + +3.6.0 / 2014-05-09 +================== + + * deprecate `app.del()` -- use `app.delete()` instead + * deprecate `res.json(obj, status)` -- use `res.json(status, obj)` instead + - the edge-case `res.json(status, num)` requires `res.status(status).json(num)` + * deprecate `res.jsonp(obj, status)` -- use `res.jsonp(status, obj)` instead + - the edge-case `res.jsonp(status, num)` requires `res.status(status).jsonp(num)` + * support PURGE method + - add `app.purge` + - add `router.purge` + - include PURGE in `app.all` + * update connect to 2.15.0 + * Add `res.appendHeader` + * Call error stack even when response has been sent + * Patch `res.headerSent` to return Boolean + * Patch `res.headersSent` for node.js 0.8 + * Prevent default 404 handler after response sent + * dep: compression@1.0.2 + * dep: connect-timeout@1.1.0 + * dep: debug@^0.8.0 + * dep: errorhandler@1.0.1 + * dep: express-session@1.0.4 + * dep: morgan@1.0.1 + * dep: serve-favicon@2.0.0 + * dep: serve-index@1.0.2 + * update debug to 0.8.0 + * add `enable()` method + * change from stderr to stdout + * update methods to 1.0.0 + - add PURGE + * update mkdirp to 0.5.0 + +3.5.3 / 2014-05-08 +================== + + * fix `req.host` for IPv6 literals + * fix `res.jsonp` error if callback param is object + +3.5.2 / 2014-04-24 +================== + + * update connect to 2.14.5 + * update cookie to 0.1.2 + * update mkdirp to 0.4.0 + * update send to 0.3.0 + +3.5.1 / 2014-03-25 +================== + + * pin less-middleware in generated app + +3.5.0 / 2014-03-06 +================== + + * bump deps + +3.4.8 / 2014-01-13 +================== + + * prevent incorrect automatic OPTIONS responses #1868 @dpatti + * update binary and examples for jade 1.0 #1876 @yossi, #1877 @reqshark, #1892 @matheusazzi + * throw 400 in case of malformed paths @rlidwka + +3.4.7 / 2013-12-10 +================== + + * update connect + +3.4.6 / 2013-12-01 +================== + + * update connect (raw-body) + +3.4.5 / 2013-11-27 +================== + + * update connect + * res.location: remove leading ./ #1802 @kapouer + * res.redirect: fix `res.redirect('toString') #1829 @michaelficarra + * res.send: always send ETag when content-length > 0 + * router: add Router.all() method + +3.4.4 / 2013-10-29 +================== + + * update connect + * update supertest + * update methods + * express(1): replace bodyParser() with urlencoded() and json() #1795 @chirag04 + +3.4.3 / 2013-10-23 +================== + + * update connect + +3.4.2 / 2013-10-18 +================== + + * update connect + * downgrade commander + +3.4.1 / 2013-10-15 +================== + + * update connect + * update commander + * jsonp: check if callback is a function + * router: wrap encodeURIComponent in a try/catch #1735 (@lxe) + * res.format: now includes charset @1747 (@sorribas) + * res.links: allow multiple calls @1746 (@sorribas) + +3.4.0 / 2013-09-07 +================== + + * add res.vary(). Closes #1682 + * update connect + +3.3.8 / 2013-09-02 +================== + + * update connect + +3.3.7 / 2013-08-28 +================== + + * update connect + +3.3.6 / 2013-08-27 +================== + + * Revert "remove charset from json responses. Closes #1631" (causes issues in some clients) + * add: req.accepts take an argument list + +3.3.4 / 2013-07-08 +================== + + * update send and connect + +3.3.3 / 2013-07-04 +================== + + * update connect + +3.3.2 / 2013-07-03 +================== + + * update connect + * update send + * remove .version export + +3.3.1 / 2013-06-27 +================== + + * update connect + +3.3.0 / 2013-06-26 +================== + + * update connect + * add support for multiple X-Forwarded-Proto values. Closes #1646 + * change: remove charset from json responses. Closes #1631 + * change: return actual booleans from req.accept* functions + * fix jsonp callback array throw + +3.2.6 / 2013-06-02 +================== + + * update connect + +3.2.5 / 2013-05-21 +================== + + * update connect + * update node-cookie + * add: throw a meaningful error when there is no default engine + * change generation of ETags with res.send() to GET requests only. Closes #1619 + +3.2.4 / 2013-05-09 +================== + + * fix `req.subdomains` when no Host is present + * fix `req.host` when no Host is present, return undefined + +3.2.3 / 2013-05-07 +================== + + * update connect / qs + +3.2.2 / 2013-05-03 +================== + + * update qs + +3.2.1 / 2013-04-29 +================== + + * add app.VERB() paths array deprecation warning + * update connect + * update qs and remove all ~ semver crap + * fix: accept number as value of Signed Cookie + +3.2.0 / 2013-04-15 +================== + + * add "view" constructor setting to override view behaviour + * add req.acceptsEncoding(name) + * add req.acceptedEncodings + * revert cookie signature change causing session race conditions + * fix sorting of Accept values of the same quality + +3.1.2 / 2013-04-12 +================== + + * add support for custom Accept parameters + * update cookie-signature + +3.1.1 / 2013-04-01 +================== + + * add X-Forwarded-Host support to `req.host` + * fix relative redirects + * update mkdirp + * update buffer-crc32 + * remove legacy app.configure() method from app template. + +3.1.0 / 2013-01-25 +================== + + * add support for leading "." in "view engine" setting + * add array support to `res.set()` + * add node 0.8.x to travis.yml + * add "subdomain offset" setting for tweaking `req.subdomains` + * add `res.location(url)` implementing `res.redirect()`-like setting of Location + * use app.get() for x-powered-by setting for inheritance + * fix colons in passwords for `req.auth` + +3.0.6 / 2013-01-04 +================== + + * add http verb methods to Router + * update connect + * fix mangling of the `res.cookie()` options object + * fix jsonp whitespace escape. Closes #1132 + +3.0.5 / 2012-12-19 +================== + + * add throwing when a non-function is passed to a route + * fix: explicitly remove Transfer-Encoding header from 204 and 304 responses + * revert "add 'etag' option" + +3.0.4 / 2012-12-05 +================== + + * add 'etag' option to disable `res.send()` Etags + * add escaping of urls in text/plain in `res.redirect()` + for old browsers interpreting as html + * change crc32 module for a more liberal license + * update connect + +3.0.3 / 2012-11-13 +================== + + * update connect + * update cookie module + * fix cookie max-age + +3.0.2 / 2012-11-08 +================== + + * add OPTIONS to cors example. Closes #1398 + * fix route chaining regression. Closes #1397 + +3.0.1 / 2012-11-01 +================== + + * update connect + +3.0.0 / 2012-10-23 +================== + + * add `make clean` + * add "Basic" check to req.auth + * add `req.auth` test coverage + * add cb && cb(payload) to `res.jsonp()`. Closes #1374 + * add backwards compat for `res.redirect()` status. Closes #1336 + * add support for `res.json()` to retain previously defined Content-Types. Closes #1349 + * update connect + * change `res.redirect()` to utilize a pathname-relative Location again. Closes #1382 + * remove non-primitive string support for `res.send()` + * fix view-locals example. Closes #1370 + * fix route-separation example + +3.0.0rc5 / 2012-09-18 +================== + + * update connect + * add redis search example + * add static-files example + * add "x-powered-by" setting (`app.disable('x-powered-by')`) + * add "application/octet-stream" redirect Accept test case. Closes #1317 + +3.0.0rc4 / 2012-08-30 +================== + + * add `res.jsonp()`. Closes #1307 + * add "verbose errors" option to error-pages example + * add another route example to express(1) so people are not so confused + * add redis online user activity tracking example + * update connect dep + * fix etag quoting. Closes #1310 + * fix error-pages 404 status + * fix jsonp callback char restrictions + * remove old OPTIONS default response + +3.0.0rc3 / 2012-08-13 +================== + + * update connect dep + * fix signed cookies to work with `connect.cookieParser()` ("s:" prefix was missing) [tnydwrds] + * fix `res.render()` clobbering of "locals" + +3.0.0rc2 / 2012-08-03 +================== + + * add CORS example + * update connect dep + * deprecate `.createServer()` & remove old stale examples + * fix: escape `res.redirect()` link + * fix vhost example + +3.0.0rc1 / 2012-07-24 +================== + + * add more examples to view-locals + * add scheme-relative redirects (`res.redirect("//foo.com")`) support + * update cookie dep + * update connect dep + * update send dep + * fix `express(1)` -h flag, use -H for hogan. Closes #1245 + * fix `res.sendfile()` socket error handling regression + +3.0.0beta7 / 2012-07-16 +================== + + * update connect dep for `send()` root normalization regression + +3.0.0beta6 / 2012-07-13 +================== + + * add `err.view` property for view errors. Closes #1226 + * add "jsonp callback name" setting + * add support for "/foo/:bar*" non-greedy matches + * change `res.sendfile()` to use `send()` module + * change `res.send` to use "response-send" module + * remove `app.locals.use` and `res.locals.use`, use regular middleware + +3.0.0beta5 / 2012-07-03 +================== + + * add "make check" support + * add route-map example + * add `res.json(obj, status)` support back for BC + * add "methods" dep, remove internal methods module + * update connect dep + * update auth example to utilize cores pbkdf2 + * updated tests to use "supertest" + +3.0.0beta4 / 2012-06-25 +================== + + * Added `req.auth` + * Added `req.range(size)` + * Added `res.links(obj)` + * Added `res.send(body, status)` support back for backwards compat + * Added `.default()` support to `res.format()` + * Added 2xx / 304 check to `req.fresh` + * Revert "Added + support to the router" + * Fixed `res.send()` freshness check, respect res.statusCode + +3.0.0beta3 / 2012-06-15 +================== + + * Added hogan `--hjs` to express(1) [nullfirm] + * Added another example to content-negotiation + * Added `fresh` dep + * Changed: `res.send()` always checks freshness + * Fixed: expose connects mime module. Closes #1165 + +3.0.0beta2 / 2012-06-06 +================== + + * Added `+` support to the router + * Added `req.host` + * Changed `req.param()` to check route first + * Update connect dep + +3.0.0beta1 / 2012-06-01 +================== + + * Added `res.format()` callback to override default 406 behaviour + * Fixed `res.redirect()` 406. Closes #1154 + +3.0.0alpha5 / 2012-05-30 +================== + + * Added `req.ip` + * Added `{ signed: true }` option to `res.cookie()` + * Removed `res.signedCookie()` + * Changed: dont reverse `req.ips` + * Fixed "trust proxy" setting check for `req.ips` + +3.0.0alpha4 / 2012-05-09 +================== + + * Added: allow `[]` in jsonp callback. Closes #1128 + * Added `PORT` env var support in generated template. Closes #1118 [benatkin] + * Updated: connect 2.2.2 + +3.0.0alpha3 / 2012-05-04 +================== + + * Added public `app.routes`. Closes #887 + * Added _view-locals_ example + * Added _mvc_ example + * Added `res.locals.use()`. Closes #1120 + * Added conditional-GET support to `res.send()` + * Added: coerce `res.set()` values to strings + * Changed: moved `static()` in generated apps below router + * Changed: `res.send()` only set ETag when not previously set + * Changed connect 2.2.1 dep + * Changed: `make test` now runs unit / acceptance tests + * Fixed req/res proto inheritance + +3.0.0alpha2 / 2012-04-26 +================== + + * Added `make benchmark` back + * Added `res.send()` support for `String` objects + * Added client-side data exposing example + * Added `res.header()` and `req.header()` aliases for BC + * Added `express.createServer()` for BC + * Perf: memoize parsed urls + * Perf: connect 2.2.0 dep + * Changed: make `expressInit()` middleware self-aware + * Fixed: use app.get() for all core settings + * Fixed redis session example + * Fixed session example. Closes #1105 + * Fixed generated express dep. Closes #1078 + +3.0.0alpha1 / 2012-04-15 +================== + + * Added `app.locals.use(callback)` + * Added `app.locals` object + * Added `app.locals(obj)` + * Added `res.locals` object + * Added `res.locals(obj)` + * Added `res.format()` for content-negotiation + * Added `app.engine()` + * Added `res.cookie()` JSON cookie support + * Added "trust proxy" setting + * Added `req.subdomains` + * Added `req.protocol` + * Added `req.secure` + * Added `req.path` + * Added `req.ips` + * Added `req.fresh` + * Added `req.stale` + * Added comma-delimited / array support for `req.accepts()` + * Added debug instrumentation + * Added `res.set(obj)` + * Added `res.set(field, value)` + * Added `res.get(field)` + * Added `app.get(setting)`. Closes #842 + * Added `req.acceptsLanguage()` + * Added `req.acceptsCharset()` + * Added `req.accepted` + * Added `req.acceptedLanguages` + * Added `req.acceptedCharsets` + * Added "json replacer" setting + * Added "json spaces" setting + * Added X-Forwarded-Proto support to `res.redirect()`. Closes #92 + * Added `--less` support to express(1) + * Added `express.response` prototype + * Added `express.request` prototype + * Added `express.application` prototype + * Added `app.path()` + * Added `app.render()` + * Added `res.type()` to replace `res.contentType()` + * Changed: `res.redirect()` to add relative support + * Changed: enable "jsonp callback" by default + * Changed: renamed "case sensitive routes" to "case sensitive routing" + * Rewrite of all tests with mocha + * Removed "root" setting + * Removed `res.redirect('home')` support + * Removed `req.notify()` + * Removed `app.register()` + * Removed `app.redirect()` + * Removed `app.is()` + * Removed `app.helpers()` + * Removed `app.dynamicHelpers()` + * Fixed `res.sendfile()` with non-GET. Closes #723 + * Fixed express(1) public dir for windows. Closes #866 + +2.5.9/ 2012-04-02 +================== + + * Added support for PURGE request method [pbuyle] + * Fixed `express(1)` generated app `app.address()` before `listening` [mmalecki] + +2.5.8 / 2012-02-08 +================== + + * Update mkdirp dep. Closes #991 + +2.5.7 / 2012-02-06 +================== + + * Fixed `app.all` duplicate DELETE requests [mscdex] + +2.5.6 / 2012-01-13 +================== + + * Updated hamljs dev dep. Closes #953 + +2.5.5 / 2012-01-08 +================== + + * Fixed: set `filename` on cached templates [matthewleon] + +2.5.4 / 2012-01-02 +================== + + * Fixed `express(1)` eol on 0.4.x. Closes #947 + +2.5.3 / 2011-12-30 +================== + + * Fixed `req.is()` when a charset is present + +2.5.2 / 2011-12-10 +================== + + * Fixed: express(1) LF -> CRLF for windows + +2.5.1 / 2011-11-17 +================== + + * Changed: updated connect to 1.8.x + * Removed sass.js support from express(1) + +2.5.0 / 2011-10-24 +================== + + * Added ./routes dir for generated app by default + * Added npm install reminder to express(1) app gen + * Added 0.5.x support + * Removed `make test-cov` since it wont work with node 0.5.x + * Fixed express(1) public dir for windows. Closes #866 + +2.4.7 / 2011-10-05 +================== + + * Added mkdirp to express(1). Closes #795 + * Added simple _json-config_ example + * Added shorthand for the parsed request's pathname via `req.path` + * Changed connect dep to 1.7.x to fix npm issue... + * Fixed `res.redirect()` __HEAD__ support. [reported by xerox] + * Fixed `req.flash()`, only escape args + * Fixed absolute path checking on windows. Closes #829 [reported by andrewpmckenzie] + +2.4.6 / 2011-08-22 +================== + + * Fixed multiple param callback regression. Closes #824 [reported by TroyGoode] + +2.4.5 / 2011-08-19 +================== + + * Added support for routes to handle errors. Closes #809 + * Added `app.routes.all()`. Closes #803 + * Added "basepath" setting to work in conjunction with reverse proxies etc. + * Refactored `Route` to use a single array of callbacks + * Added support for multiple callbacks for `app.param()`. Closes #801 +Closes #805 + * Changed: removed .call(self) for route callbacks + * Dependency: `qs >= 0.3.1` + * Fixed `res.redirect()` on windows due to `join()` usage. Closes #808 + +2.4.4 / 2011-08-05 +================== + + * Fixed `res.header()` intention of a set, even when `undefined` + * Fixed `*`, value no longer required + * Fixed `res.send(204)` support. Closes #771 + +2.4.3 / 2011-07-14 +================== + + * Added docs for `status` option special-case. Closes #739 + * Fixed `options.filename`, exposing the view path to template engines + +2.4.2. / 2011-07-06 +================== + + * Revert "removed jsonp stripping" for XSS + +2.4.1 / 2011-07-06 +================== + + * Added `res.json()` JSONP support. Closes #737 + * Added _extending-templates_ example. Closes #730 + * Added "strict routing" setting for trailing slashes + * Added support for multiple envs in `app.configure()` calls. Closes #735 + * Changed: `res.send()` using `res.json()` + * Changed: when cookie `path === null` don't default it + * Changed; default cookie path to "home" setting. Closes #731 + * Removed _pids/logs_ creation from express(1) + +2.4.0 / 2011-06-28 +================== + + * Added chainable `res.status(code)` + * Added `res.json()`, an explicit version of `res.send(obj)` + * Added simple web-service example + +2.3.12 / 2011-06-22 +================== + + * \#express is now on freenode! come join! + * Added `req.get(field, param)` + * Added links to Japanese documentation, thanks @hideyukisaito! + * Added; the `express(1)` generated app outputs the env + * Added `content-negotiation` example + * Dependency: connect >= 1.5.1 < 2.0.0 + * Fixed view layout bug. Closes #720 + * Fixed; ignore body on 304. Closes #701 + +2.3.11 / 2011-06-04 +================== + + * Added `npm test` + * Removed generation of dummy test file from `express(1)` + * Fixed; `express(1)` adds express as a dep + * Fixed; prune on `prepublish` + +2.3.10 / 2011-05-27 +================== + + * Added `req.route`, exposing the current route + * Added _package.json_ generation support to `express(1)` + * Fixed call to `app.param()` function for optional params. Closes #682 + +2.3.9 / 2011-05-25 +================== + + * Fixed bug-ish with `../' in `res.partial()` calls + +2.3.8 / 2011-05-24 +================== + + * Fixed `app.options()` + +2.3.7 / 2011-05-23 +================== + + * Added route `Collection`, ex: `app.get('/user/:id').remove();` + * Added support for `app.param(fn)` to define param logic + * Removed `app.param()` support for callback with return value + * Removed module.parent check from express(1) generated app. Closes #670 + * Refactored router. Closes #639 + +2.3.6 / 2011-05-20 +================== + + * Changed; using devDependencies instead of git submodules + * Fixed redis session example + * Fixed markdown example + * Fixed view caching, should not be enabled in development + +2.3.5 / 2011-05-20 +================== + + * Added export `.view` as alias for `.View` + +2.3.4 / 2011-05-08 +================== + + * Added `./examples/say` + * Fixed `res.sendfile()` bug preventing the transfer of files with spaces + +2.3.3 / 2011-05-03 +================== + + * Added "case sensitive routes" option. + * Changed; split methods supported per rfc [slaskis] + * Fixed route-specific middleware when using the same callback function several times + +2.3.2 / 2011-04-27 +================== + + * Fixed view hints + +2.3.1 / 2011-04-26 +================== + + * Added `app.match()` as `app.match.all()` + * Added `app.lookup()` as `app.lookup.all()` + * Added `app.remove()` for `app.remove.all()` + * Added `app.remove.VERB()` + * Fixed template caching collision issue. Closes #644 + * Moved router over from connect and started refactor + +2.3.0 / 2011-04-25 +================== + + * Added options support to `res.clearCookie()` + * Added `res.helpers()` as alias of `res.locals()` + * Added; json defaults to UTF-8 with `res.send()`. Closes #632. [Daniel * Dependency `connect >= 1.4.0` + * Changed; auto set Content-Type in res.attachement [Aaron Heckmann] + * Renamed "cache views" to "view cache". Closes #628 + * Fixed caching of views when using several apps. Closes #637 + * Fixed gotcha invoking `app.param()` callbacks once per route middleware. +Closes #638 + * Fixed partial lookup precedence. Closes #631 +Shaw] + +2.2.2 / 2011-04-12 +================== + + * Added second callback support for `res.download()` connection errors + * Fixed `filename` option passing to template engine + +2.2.1 / 2011-04-04 +================== + + * Added `layout(path)` helper to change the layout within a view. Closes #610 + * Fixed `partial()` collection object support. + Previously only anything with `.length` would work. + When `.length` is present one must still be aware of holes, + however now `{ collection: {foo: 'bar'}}` is valid, exposes + `keyInCollection` and `keysInCollection`. + + * Performance improved with better view caching + * Removed `request` and `response` locals + * Changed; errorHandler page title is now `Express` instead of `Connect` + +2.2.0 / 2011-03-30 +================== + + * Added `app.lookup.VERB()`, ex `app.lookup.put('/user/:id')`. Closes #606 + * Added `app.match.VERB()`, ex `app.match.put('/user/12')`. Closes #606 + * Added `app.VERB(path)` as alias of `app.lookup.VERB()`. + * Dependency `connect >= 1.2.0` + +2.1.1 / 2011-03-29 +================== + + * Added; expose `err.view` object when failing to locate a view + * Fixed `res.partial()` call `next(err)` when no callback is given [reported by aheckmann] + * Fixed; `res.send(undefined)` responds with 204 [aheckmann] + +2.1.0 / 2011-03-24 +================== + + * Added `/_?` partial lookup support. Closes #447 + * Added `request`, `response`, and `app` local variables + * Added `settings` local variable, containing the app's settings + * Added `req.flash()` exception if `req.session` is not available + * Added `res.send(bool)` support (json response) + * Fixed stylus example for latest version + * Fixed; wrap try/catch around `res.render()` + +2.0.0 / 2011-03-17 +================== + + * Fixed up index view path alternative. + * Changed; `res.locals()` without object returns the locals + +2.0.0rc3 / 2011-03-17 +================== + + * Added `res.locals(obj)` to compliment `res.local(key, val)` + * Added `res.partial()` callback support + * Fixed recursive error reporting issue in `res.render()` + +2.0.0rc2 / 2011-03-17 +================== + + * Changed; `partial()` "locals" are now optional + * Fixed `SlowBuffer` support. Closes #584 [reported by tyrda01] + * Fixed .filename view engine option [reported by drudge] + * Fixed blog example + * Fixed `{req,res}.app` reference when mounting [Ben Weaver] + +2.0.0rc / 2011-03-14 +================== + + * Fixed; expose `HTTPSServer` constructor + * Fixed express(1) default test charset. Closes #579 [reported by secoif] + * Fixed; default charset to utf-8 instead of utf8 for lame IE [reported by NickP] + +2.0.0beta3 / 2011-03-09 +================== + + * Added support for `res.contentType()` literal + The original `res.contentType('.json')`, + `res.contentType('application/json')`, and `res.contentType('json')` + will work now. + * Added `res.render()` status option support back + * Added charset option for `res.render()` + * Added `.charset` support (via connect 1.0.4) + * Added view resolution hints when in development and a lookup fails + * Added layout lookup support relative to the page view. + For example while rendering `./views/user/index.jade` if you create + `./views/user/layout.jade` it will be used in favour of the root layout. + * Fixed `res.redirect()`. RFC states absolute url [reported by unlink] + * Fixed; default `res.send()` string charset to utf8 + * Removed `Partial` constructor (not currently used) + +2.0.0beta2 / 2011-03-07 +================== + + * Added res.render() `.locals` support back to aid in migration process + * Fixed flash example + +2.0.0beta / 2011-03-03 +================== + + * Added HTTPS support + * Added `res.cookie()` maxAge support + * Added `req.header()` _Referrer_ / _Referer_ special-case, either works + * Added mount support for `res.redirect()`, now respects the mount-point + * Added `union()` util, taking place of `merge(clone())` combo + * Added stylus support to express(1) generated app + * Added secret to session middleware used in examples and generated app + * Added `res.local(name, val)` for progressive view locals + * Added default param support to `req.param(name, default)` + * Added `app.disabled()` and `app.enabled()` + * Added `app.register()` support for omitting leading ".", either works + * Added `res.partial()`, using the same interface as `partial()` within a view. Closes #539 + * Added `app.param()` to map route params to async/sync logic + * Added; aliased `app.helpers()` as `app.locals()`. Closes #481 + * Added extname with no leading "." support to `res.contentType()` + * Added `cache views` setting, defaulting to enabled in "production" env + * Added index file partial resolution, eg: partial('user') may try _views/user/index.jade_. + * Added `req.accepts()` support for extensions + * Changed; `res.download()` and `res.sendfile()` now utilize Connect's + static file server `connect.static.send()`. + * Changed; replaced `connect.utils.mime()` with npm _mime_ module + * Changed; allow `req.query` to be pre-defined (via middleware or other parent + * Changed view partial resolution, now relative to parent view + * Changed view engine signature. no longer `engine.render(str, options, callback)`, now `engine.compile(str, options) -> Function`, the returned function accepts `fn(locals)`. + * Fixed `req.param()` bug returning Array.prototype methods. Closes #552 + * Fixed; using `Stream#pipe()` instead of `sys.pump()` in `res.sendfile()` + * Fixed; using _qs_ module instead of _querystring_ + * Fixed; strip unsafe chars from jsonp callbacks + * Removed "stream threshold" setting + +1.0.8 / 2011-03-01 +================== + + * Allow `req.query` to be pre-defined (via middleware or other parent app) + * "connect": ">= 0.5.0 < 1.0.0". Closes #547 + * Removed the long deprecated __EXPRESS_ENV__ support + +1.0.7 / 2011-02-07 +================== + + * Fixed `render()` setting inheritance. + Mounted apps would not inherit "view engine" + +1.0.6 / 2011-02-07 +================== + + * Fixed `view engine` setting bug when period is in dirname + +1.0.5 / 2011-02-05 +================== + + * Added secret to generated app `session()` call + +1.0.4 / 2011-02-05 +================== + + * Added `qs` dependency to _package.json_ + * Fixed namespaced `require()`s for latest connect support + +1.0.3 / 2011-01-13 +================== + + * Remove unsafe characters from JSONP callback names [Ryan Grove] + +1.0.2 / 2011-01-10 +================== + + * Removed nested require, using `connect.router` + +1.0.1 / 2010-12-29 +================== + + * Fixed for middleware stacked via `createServer()` + previously the `foo` middleware passed to `createServer(foo)` + would not have access to Express methods such as `res.send()` + or props like `req.query` etc. + +1.0.0 / 2010-11-16 +================== + + * Added; deduce partial object names from the last segment. + For example by default `partial('forum/post', postObject)` will + give you the _post_ object, providing a meaningful default. + * Added http status code string representation to `res.redirect()` body + * Added; `res.redirect()` supporting _text/plain_ and _text/html_ via __Accept__. + * Added `req.is()` to aid in content negotiation + * Added partial local inheritance [suggested by masylum]. Closes #102 + providing access to parent template locals. + * Added _-s, --session[s]_ flag to express(1) to add session related middleware + * Added _--template_ flag to express(1) to specify the + template engine to use. + * Added _--css_ flag to express(1) to specify the + stylesheet engine to use (or just plain css by default). + * Added `app.all()` support [thanks aheckmann] + * Added partial direct object support. + You may now `partial('user', user)` providing the "user" local, + vs previously `partial('user', { object: user })`. + * Added _route-separation_ example since many people question ways + to do this with CommonJS modules. Also view the _blog_ example for + an alternative. + * Performance; caching view path derived partial object names + * Fixed partial local inheritance precedence. [reported by Nick Poulden] Closes #454 + * Fixed jsonp support; _text/javascript_ as per mailinglist discussion + +1.0.0rc4 / 2010-10-14 +================== + + * Added _NODE_ENV_ support, _EXPRESS_ENV_ is deprecated and will be removed in 1.0.0 + * Added route-middleware support (very helpful, see the [docs](http://expressjs.com/guide.html#Route-Middleware)) + * Added _jsonp callback_ setting to enable/disable jsonp autowrapping [Dav Glass] + * Added callback query check on response.send to autowrap JSON objects for simple webservice implementations [Dav Glass] + * Added `partial()` support for array-like collections. Closes #434 + * Added support for swappable querystring parsers + * Added session usage docs. Closes #443 + * Added dynamic helper caching. Closes #439 [suggested by maritz] + * Added authentication example + * Added basic Range support to `res.sendfile()` (and `res.download()` etc) + * Changed; `express(1)` generated app using 2 spaces instead of 4 + * Default env to "development" again [aheckmann] + * Removed _context_ option is no more, use "scope" + * Fixed; exposing _./support_ libs to examples so they can run without installs + * Fixed mvc example + +1.0.0rc3 / 2010-09-20 +================== + + * Added confirmation for `express(1)` app generation. Closes #391 + * Added extending of flash formatters via `app.flashFormatters` + * Added flash formatter support. Closes #411 + * Added streaming support to `res.sendfile()` using `sys.pump()` when >= "stream threshold" + * Added _stream threshold_ setting for `res.sendfile()` + * Added `res.send()` __HEAD__ support + * Added `res.clearCookie()` + * Added `res.cookie()` + * Added `res.render()` headers option + * Added `res.redirect()` response bodies + * Added `res.render()` status option support. Closes #425 [thanks aheckmann] + * Fixed `res.sendfile()` responding with 403 on malicious path + * Fixed `res.download()` bug; when an error occurs remove _Content-Disposition_ + * Fixed; mounted apps settings now inherit from parent app [aheckmann] + * Fixed; stripping Content-Length / Content-Type when 204 + * Fixed `res.send()` 204. Closes #419 + * Fixed multiple _Set-Cookie_ headers via `res.header()`. Closes #402 + * Fixed bug messing with error handlers when `listenFD()` is called instead of `listen()`. [thanks guillermo] + + +1.0.0rc2 / 2010-08-17 +================== + + * Added `app.register()` for template engine mapping. Closes #390 + * Added `res.render()` callback support as second argument (no options) + * Added callback support to `res.download()` + * Added callback support for `res.sendfile()` + * Added support for middleware access via `express.middlewareName()` vs `connect.middlewareName()` + * Added "partials" setting to docs + * Added default expresso tests to `express(1)` generated app. Closes #384 + * Fixed `res.sendfile()` error handling, defer via `next()` + * Fixed `res.render()` callback when a layout is used [thanks guillermo] + * Fixed; `make install` creating ~/.node_libraries when not present + * Fixed issue preventing error handlers from being defined anywhere. Closes #387 + +1.0.0rc / 2010-07-28 +================== + + * Added mounted hook. Closes #369 + * Added connect dependency to _package.json_ + + * Removed "reload views" setting and support code + development env never caches, production always caches. + + * Removed _param_ in route callbacks, signature is now + simply (req, res, next), previously (req, res, params, next). + Use _req.params_ for path captures, _req.query_ for GET params. + + * Fixed "home" setting + * Fixed middleware/router precedence issue. Closes #366 + * Fixed; _configure()_ callbacks called immediately. Closes #368 + +1.0.0beta2 / 2010-07-23 +================== + + * Added more examples + * Added; exporting `Server` constructor + * Added `Server#helpers()` for view locals + * Added `Server#dynamicHelpers()` for dynamic view locals. Closes #349 + * Added support for absolute view paths + * Added; _home_ setting defaults to `Server#route` for mounted apps. Closes #363 + * Added Guillermo Rauch to the contributor list + * Added support for "as" for non-collection partials. Closes #341 + * Fixed _install.sh_, ensuring _~/.node_libraries_ exists. Closes #362 [thanks jf] + * Fixed `res.render()` exceptions, now passed to `next()` when no callback is given [thanks guillermo] + * Fixed instanceof `Array` checks, now `Array.isArray()` + * Fixed express(1) expansion of public dirs. Closes #348 + * Fixed middleware precedence. Closes #345 + * Fixed view watcher, now async [thanks aheckmann] + +1.0.0beta / 2010-07-15 +================== + + * Re-write + - much faster + - much lighter + - Check [ExpressJS.com](http://expressjs.com) for migration guide and updated docs + +0.14.0 / 2010-06-15 +================== + + * Utilize relative requires + * Added Static bufferSize option [aheckmann] + * Fixed caching of view and partial subdirectories [aheckmann] + * Fixed mime.type() comments now that ".ext" is not supported + * Updated haml submodule + * Updated class submodule + * Removed bin/express + +0.13.0 / 2010-06-01 +================== + + * Added node v0.1.97 compatibility + * Added support for deleting cookies via Request#cookie('key', null) + * Updated haml submodule + * Fixed not-found page, now using charset utf-8 + * Fixed show-exceptions page, now using charset utf-8 + * Fixed view support due to fs.readFile Buffers + * Changed; mime.type() no longer accepts ".type" due to node extname() changes + +0.12.0 / 2010-05-22 +================== + + * Added node v0.1.96 compatibility + * Added view `helpers` export which act as additional local variables + * Updated haml submodule + * Changed ETag; removed inode, modified time only + * Fixed LF to CRLF for setting multiple cookies + * Fixed cookie compilation; values are now urlencoded + * Fixed cookies parsing; accepts quoted values and url escaped cookies + +0.11.0 / 2010-05-06 +================== + + * Added support for layouts using different engines + - this.render('page.html.haml', { layout: 'super-cool-layout.html.ejs' }) + - this.render('page.html.haml', { layout: 'foo' }) // assumes 'foo.html.haml' + - this.render('page.html.haml', { layout: false }) // no layout + * Updated ext submodule + * Updated haml submodule + * Fixed EJS partial support by passing along the context. Issue #307 + +0.10.1 / 2010-05-03 +================== + + * Fixed binary uploads. + +0.10.0 / 2010-04-30 +================== + + * Added charset support via Request#charset (automatically assigned to 'UTF-8' when respond()'s + encoding is set to 'utf8' or 'utf-8'). + * Added "encoding" option to Request#render(). Closes #299 + * Added "dump exceptions" setting, which is enabled by default. + * Added simple ejs template engine support + * Added error response support for text/plain, application/json. Closes #297 + * Added callback function param to Request#error() + * Added Request#sendHead() + * Added Request#stream() + * Added support for Request#respond(304, null) for empty response bodies + * Added ETag support to Request#sendfile() + * Added options to Request#sendfile(), passed to fs.createReadStream() + * Added filename arg to Request#download() + * Performance enhanced due to pre-reversing plugins so that plugins.reverse() is not called on each request + * Performance enhanced by preventing several calls to toLowerCase() in Router#match() + * Changed; Request#sendfile() now streams + * Changed; Renamed Request#halt() to Request#respond(). Closes #289 + * Changed; Using sys.inspect() instead of JSON.encode() for error output + * Changed; run() returns the http.Server instance. Closes #298 + * Changed; Defaulting Server#host to null (INADDR_ANY) + * Changed; Logger "common" format scale of 0.4f + * Removed Logger "request" format + * Fixed; Catching ENOENT in view caching, preventing error when "views/partials" is not found + * Fixed several issues with http client + * Fixed Logger Content-Length output + * Fixed bug preventing Opera from retaining the generated session id. Closes #292 + +0.9.0 / 2010-04-14 +================== + + * Added DSL level error() route support + * Added DSL level notFound() route support + * Added Request#error() + * Added Request#notFound() + * Added Request#render() callback function. Closes #258 + * Added "max upload size" setting + * Added "magic" variables to collection partials (\_\_index\_\_, \_\_length\_\_, \_\_isFirst\_\_, \_\_isLast\_\_). Closes #254 + * Added [haml.js](http://github.com/visionmedia/haml.js) submodule; removed haml-js + * Added callback function support to Request#halt() as 3rd/4th arg + * Added preprocessing of route param wildcards using param(). Closes #251 + * Added view partial support (with collections etc.) + * Fixed bug preventing falsey params (such as ?page=0). Closes #286 + * Fixed setting of multiple cookies. Closes #199 + * Changed; view naming convention is now NAME.TYPE.ENGINE (for example page.html.haml) + * Changed; session cookie is now httpOnly + * Changed; Request is no longer global + * Changed; Event is no longer global + * Changed; "sys" module is no longer global + * Changed; moved Request#download to Static plugin where it belongs + * Changed; Request instance created before body parsing. Closes #262 + * Changed; Pre-caching views in memory when "cache view contents" is enabled. Closes #253 + * Changed; Pre-caching view partials in memory when "cache view partials" is enabled + * Updated support to node --version 0.1.90 + * Updated dependencies + * Removed set("session cookie") in favour of use(Session, { cookie: { ... }}) + * Removed utils.mixin(); use Object#mergeDeep() + +0.8.0 / 2010-03-19 +================== + + * Added coffeescript example app. Closes #242 + * Changed; cache api now async friendly. Closes #240 + * Removed deprecated 'express/static' support. Use 'express/plugins/static' + +0.7.6 / 2010-03-19 +================== + + * Added Request#isXHR. Closes #229 + * Added `make install` (for the executable) + * Added `express` executable for setting up simple app templates + * Added "GET /public/*" to Static plugin, defaulting to /public + * Added Static plugin + * Fixed; Request#render() only calls cache.get() once + * Fixed; Namespacing View caches with "view:" + * Fixed; Namespacing Static caches with "static:" + * Fixed; Both example apps now use the Static plugin + * Fixed set("views"). Closes #239 + * Fixed missing space for combined log format + * Deprecated Request#sendfile() and 'express/static' + * Removed Server#running + +0.7.5 / 2010-03-16 +================== + + * Added Request#flash() support without args, now returns all flashes + * Updated ext submodule + +0.7.4 / 2010-03-16 +================== + + * Fixed session reaper + * Changed; class.js replacing js-oo Class implementation (quite a bit faster, no browser cruft) + +0.7.3 / 2010-03-16 +================== + + * Added package.json + * Fixed requiring of haml / sass due to kiwi removal + +0.7.2 / 2010-03-16 +================== + + * Fixed GIT submodules (HAH!) + +0.7.1 / 2010-03-16 +================== + + * Changed; Express now using submodules again until a PM is adopted + * Changed; chat example using millisecond conversions from ext + +0.7.0 / 2010-03-15 +================== + + * Added Request#pass() support (finds the next matching route, or the given path) + * Added Logger plugin (default "common" format replaces CommonLogger) + * Removed Profiler plugin + * Removed CommonLogger plugin + +0.6.0 / 2010-03-11 +================== + + * Added seed.yml for kiwi package management support + * Added HTTP client query string support when method is GET. Closes #205 + + * Added support for arbitrary view engines. + For example "foo.engine.html" will now require('engine'), + the exports from this module are cached after the first require(). + + * Added async plugin support + + * Removed usage of RESTful route funcs as http client + get() etc, use http.get() and friends + + * Removed custom exceptions + +0.5.0 / 2010-03-10 +================== + + * Added ext dependency (library of js extensions) + * Removed extname() / basename() utils. Use path module + * Removed toArray() util. Use arguments.values + * Removed escapeRegexp() util. Use RegExp.escape() + * Removed process.mixin() dependency. Use utils.mixin() + * Removed Collection + * Removed ElementCollection + * Shameless self promotion of ebook "Advanced JavaScript" (http://dev-mag.com) ;) + +0.4.0 / 2010-02-11 +================== + + * Added flash() example to sample upload app + * Added high level restful http client module (express/http) + * Changed; RESTful route functions double as HTTP clients. Closes #69 + * Changed; throwing error when routes are added at runtime + * Changed; defaulting render() context to the current Request. Closes #197 + * Updated haml submodule + +0.3.0 / 2010-02-11 +================== + + * Updated haml / sass submodules. Closes #200 + * Added flash message support. Closes #64 + * Added accepts() now allows multiple args. fixes #117 + * Added support for plugins to halt. Closes #189 + * Added alternate layout support. Closes #119 + * Removed Route#run(). Closes #188 + * Fixed broken specs due to use(Cookie) missing + +0.2.1 / 2010-02-05 +================== + + * Added "plot" format option for Profiler (for gnuplot processing) + * Added request number to Profiler plugin + * Fixed binary encoding for multipart file uploads, was previously defaulting to UTF8 + * Fixed issue with routes not firing when not files are present. Closes #184 + * Fixed process.Promise -> events.Promise + +0.2.0 / 2010-02-03 +================== + + * Added parseParam() support for name[] etc. (allows for file inputs with "multiple" attr) Closes #180 + * Added Both Cache and Session option "reapInterval" may be "reapEvery". Closes #174 + * Added expiration support to cache api with reaper. Closes #133 + * Added cache Store.Memory#reap() + * Added Cache; cache api now uses first class Cache instances + * Added abstract session Store. Closes #172 + * Changed; cache Memory.Store#get() utilizing Collection + * Renamed MemoryStore -> Store.Memory + * Fixed use() of the same plugin several time will always use latest options. Closes #176 + +0.1.0 / 2010-02-03 +================== + + * Changed; Hooks (before / after) pass request as arg as well as evaluated in their context + * Updated node support to 0.1.27 Closes #169 + * Updated dirname(__filename) -> __dirname + * Updated libxmljs support to v0.2.0 + * Added session support with memory store / reaping + * Added quick uid() helper + * Added multi-part upload support + * Added Sass.js support / submodule + * Added production env caching view contents and static files + * Added static file caching. Closes #136 + * Added cache plugin with memory stores + * Added support to StaticFile so that it works with non-textual files. + * Removed dirname() helper + * Removed several globals (now their modules must be required) + +0.0.2 / 2010-01-10 +================== + + * Added view benchmarks; currently haml vs ejs + * Added Request#attachment() specs. Closes #116 + * Added use of node's parseQuery() util. Closes #123 + * Added `make init` for submodules + * Updated Haml + * Updated sample chat app to show messages on load + * Updated libxmljs parseString -> parseHtmlString + * Fixed `make init` to work with older versions of git + * Fixed specs can now run independent specs for those who can't build deps. Closes #127 + * Fixed issues introduced by the node url module changes. Closes 126. + * Fixed two assertions failing due to Collection#keys() returning strings + * Fixed faulty Collection#toArray() spec due to keys() returning strings + * Fixed `make test` now builds libxmljs.node before testing + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/gun-server/node_modules/express/LICENSE b/gun-server/node_modules/express/LICENSE new file mode 100644 index 0000000..aa927e4 --- /dev/null +++ b/gun-server/node_modules/express/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2009-2014 TJ Holowaychuk +Copyright (c) 2013-2014 Roman Shtylman +Copyright (c) 2014-2015 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/gun-server/node_modules/express/Readme.md b/gun-server/node_modules/express/Readme.md new file mode 100644 index 0000000..d0f3cf5 --- /dev/null +++ b/gun-server/node_modules/express/Readme.md @@ -0,0 +1,166 @@ +[![Express Logo](https://i.cloudup.com/zfY6lL7eFa-3000x3000.png)](http://expressjs.com/) + + Fast, unopinionated, minimalist web framework for [Node.js](http://nodejs.org). + + [![NPM Version][npm-version-image]][npm-url] + [![NPM Install Size][npm-install-size-image]][npm-install-size-url] + [![NPM Downloads][npm-downloads-image]][npm-downloads-url] + +```js +const express = require('express') +const app = express() + +app.get('/', function (req, res) { + res.send('Hello World') +}) + +app.listen(3000) +``` + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). + +Before installing, [download and install Node.js](https://nodejs.org/en/download/). +Node.js 0.10 or higher is required. + +If this is a brand new project, make sure to create a `package.json` first with +the [`npm init` command](https://docs.npmjs.com/creating-a-package-json-file). + +Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```console +$ npm install express +``` + +Follow [our installing guide](http://expressjs.com/en/starter/installing.html) +for more information. + +## Features + + * Robust routing + * Focus on high performance + * Super-high test coverage + * HTTP helpers (redirection, caching, etc) + * View system supporting 14+ template engines + * Content negotiation + * Executable for generating applications quickly + +## Docs & Community + + * [Website and Documentation](http://expressjs.com/) - [[website repo](https://github.com/expressjs/expressjs.com)] + * [#express](https://web.libera.chat/#express) on [Libera Chat](https://libera.chat) IRC + * [GitHub Organization](https://github.com/expressjs) for Official Middleware & Modules + * Visit the [Wiki](https://github.com/expressjs/express/wiki) + * [Google Group](https://groups.google.com/group/express-js) for discussion + * [Gitter](https://gitter.im/expressjs/express) for support and discussion + +**PROTIP** Be sure to read [Migrating from 3.x to 4.x](https://github.com/expressjs/express/wiki/Migrating-from-3.x-to-4.x) as well as [New features in 4.x](https://github.com/expressjs/express/wiki/New-features-in-4.x). + +## Quick Start + + The quickest way to get started with express is to utilize the executable [`express(1)`](https://github.com/expressjs/generator) to generate an application as shown below: + + Install the executable. The executable's major version will match Express's: + +```console +$ npm install -g express-generator@4 +``` + + Create the app: + +```console +$ express /tmp/foo && cd /tmp/foo +``` + + Install dependencies: + +```console +$ npm install +``` + + Start the server: + +```console +$ npm start +``` + + View the website at: http://localhost:3000 + +## Philosophy + + The Express philosophy is to provide small, robust tooling for HTTP servers, making + it a great solution for single page applications, websites, hybrids, or public + HTTP APIs. + + Express does not force you to use any specific ORM or template engine. With support for over + 14 template engines via [Consolidate.js](https://github.com/tj/consolidate.js), + you can quickly craft your perfect framework. + +## Examples + + To view the examples, clone the Express repo and install the dependencies: + +```console +$ git clone https://github.com/expressjs/express.git --depth 1 +$ cd express +$ npm install +``` + + Then run whichever example you want: + +```console +$ node examples/content-negotiation +``` + +## Contributing + + [![Linux Build][github-actions-ci-image]][github-actions-ci-url] + [![Windows Build][appveyor-image]][appveyor-url] + [![Test Coverage][coveralls-image]][coveralls-url] + +The Express.js project welcomes all constructive contributions. Contributions take many forms, +from code for bug fixes and enhancements, to additions and fixes to documentation, additional +tests, triaging incoming pull requests and issues, and more! + +See the [Contributing Guide](Contributing.md) for more technical details on contributing. + +### Security Issues + +If you discover a security vulnerability in Express, please see [Security Policies and Procedures](Security.md). + +### Running Tests + +To run the test suite, first install the dependencies, then run `npm test`: + +```console +$ npm install +$ npm test +``` + +## People + +The original author of Express is [TJ Holowaychuk](https://github.com/tj) + +The current lead maintainer is [Douglas Christopher Wilson](https://github.com/dougwilson) + +[List of all contributors](https://github.com/expressjs/express/graphs/contributors) + +## License + + [MIT](LICENSE) + +[appveyor-image]: https://badgen.net/appveyor/ci/dougwilson/express/master?label=windows +[appveyor-url]: https://ci.appveyor.com/project/dougwilson/express +[coveralls-image]: https://badgen.net/coveralls/c/github/expressjs/express/master +[coveralls-url]: https://coveralls.io/r/expressjs/express?branch=master +[github-actions-ci-image]: https://badgen.net/github/checks/expressjs/express/master?label=linux +[github-actions-ci-url]: https://github.com/expressjs/express/actions/workflows/ci.yml +[npm-downloads-image]: https://badgen.net/npm/dm/express +[npm-downloads-url]: https://npmcharts.com/compare/express?minimal=true +[npm-install-size-image]: https://badgen.net/packagephobia/install/express +[npm-install-size-url]: https://packagephobia.com/result?p=express +[npm-url]: https://npmjs.org/package/express +[npm-version-image]: https://badgen.net/npm/v/express diff --git a/gun-server/node_modules/express/index.js b/gun-server/node_modules/express/index.js new file mode 100644 index 0000000..d219b0c --- /dev/null +++ b/gun-server/node_modules/express/index.js @@ -0,0 +1,11 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +module.exports = require('./lib/express'); diff --git a/gun-server/node_modules/express/lib/application.js b/gun-server/node_modules/express/lib/application.js new file mode 100644 index 0000000..ebb30b5 --- /dev/null +++ b/gun-server/node_modules/express/lib/application.js @@ -0,0 +1,661 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var finalhandler = require('finalhandler'); +var Router = require('./router'); +var methods = require('methods'); +var middleware = require('./middleware/init'); +var query = require('./middleware/query'); +var debug = require('debug')('express:application'); +var View = require('./view'); +var http = require('http'); +var compileETag = require('./utils').compileETag; +var compileQueryParser = require('./utils').compileQueryParser; +var compileTrust = require('./utils').compileTrust; +var deprecate = require('depd')('express'); +var flatten = require('array-flatten'); +var merge = require('utils-merge'); +var resolve = require('path').resolve; +var setPrototypeOf = require('setprototypeof') + +/** + * Module variables. + * @private + */ + +var hasOwnProperty = Object.prototype.hasOwnProperty +var slice = Array.prototype.slice; + +/** + * Application prototype. + */ + +var app = exports = module.exports = {}; + +/** + * Variable for trust proxy inheritance back-compat + * @private + */ + +var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default'; + +/** + * Initialize the server. + * + * - setup default configuration + * - setup default middleware + * - setup route reflection methods + * + * @private + */ + +app.init = function init() { + this.cache = {}; + this.engines = {}; + this.settings = {}; + + this.defaultConfiguration(); +}; + +/** + * Initialize application configuration. + * @private + */ + +app.defaultConfiguration = function defaultConfiguration() { + var env = process.env.NODE_ENV || 'development'; + + // default settings + this.enable('x-powered-by'); + this.set('etag', 'weak'); + this.set('env', env); + this.set('query parser', 'extended'); + this.set('subdomain offset', 2); + this.set('trust proxy', false); + + // trust proxy inherit back-compat + Object.defineProperty(this.settings, trustProxyDefaultSymbol, { + configurable: true, + value: true + }); + + debug('booting in %s mode', env); + + this.on('mount', function onmount(parent) { + // inherit trust proxy + if (this.settings[trustProxyDefaultSymbol] === true + && typeof parent.settings['trust proxy fn'] === 'function') { + delete this.settings['trust proxy']; + delete this.settings['trust proxy fn']; + } + + // inherit protos + setPrototypeOf(this.request, parent.request) + setPrototypeOf(this.response, parent.response) + setPrototypeOf(this.engines, parent.engines) + setPrototypeOf(this.settings, parent.settings) + }); + + // setup locals + this.locals = Object.create(null); + + // top-most app is mounted at / + this.mountpath = '/'; + + // default locals + this.locals.settings = this.settings; + + // default configuration + this.set('view', View); + this.set('views', resolve('views')); + this.set('jsonp callback name', 'callback'); + + if (env === 'production') { + this.enable('view cache'); + } + + Object.defineProperty(this, 'router', { + get: function() { + throw new Error('\'app.router\' is deprecated!\nPlease see the 3.x to 4.x migration guide for details on how to update your app.'); + } + }); +}; + +/** + * lazily adds the base router if it has not yet been added. + * + * We cannot add the base router in the defaultConfiguration because + * it reads app settings which might be set after that has run. + * + * @private + */ +app.lazyrouter = function lazyrouter() { + if (!this._router) { + this._router = new Router({ + caseSensitive: this.enabled('case sensitive routing'), + strict: this.enabled('strict routing') + }); + + this._router.use(query(this.get('query parser fn'))); + this._router.use(middleware.init(this)); + } +}; + +/** + * Dispatch a req, res pair into the application. Starts pipeline processing. + * + * If no callback is provided, then default error handlers will respond + * in the event of an error bubbling through the stack. + * + * @private + */ + +app.handle = function handle(req, res, callback) { + var router = this._router; + + // final handler + var done = callback || finalhandler(req, res, { + env: this.get('env'), + onerror: logerror.bind(this) + }); + + // no routes + if (!router) { + debug('no routes defined on app'); + done(); + return; + } + + router.handle(req, res, done); +}; + +/** + * Proxy `Router#use()` to add middleware to the app router. + * See Router#use() documentation for details. + * + * If the _fn_ parameter is an express app, then it will be + * mounted at the _route_ specified. + * + * @public + */ + +app.use = function use(fn) { + var offset = 0; + var path = '/'; + + // default path to '/' + // disambiguate app.use([fn]) + if (typeof fn !== 'function') { + var arg = fn; + + while (Array.isArray(arg) && arg.length !== 0) { + arg = arg[0]; + } + + // first arg is the path + if (typeof arg !== 'function') { + offset = 1; + path = fn; + } + } + + var fns = flatten(slice.call(arguments, offset)); + + if (fns.length === 0) { + throw new TypeError('app.use() requires a middleware function') + } + + // setup router + this.lazyrouter(); + var router = this._router; + + fns.forEach(function (fn) { + // non-express app + if (!fn || !fn.handle || !fn.set) { + return router.use(path, fn); + } + + debug('.use app under %s', path); + fn.mountpath = path; + fn.parent = this; + + // restore .app property on req and res + router.use(path, function mounted_app(req, res, next) { + var orig = req.app; + fn.handle(req, res, function (err) { + setPrototypeOf(req, orig.request) + setPrototypeOf(res, orig.response) + next(err); + }); + }); + + // mounted an app + fn.emit('mount', this); + }, this); + + return this; +}; + +/** + * Proxy to the app `Router#route()` + * Returns a new `Route` instance for the _path_. + * + * Routes are isolated middleware stacks for specific paths. + * See the Route api docs for details. + * + * @public + */ + +app.route = function route(path) { + this.lazyrouter(); + return this._router.route(path); +}; + +/** + * Register the given template engine callback `fn` + * as `ext`. + * + * By default will `require()` the engine based on the + * file extension. For example if you try to render + * a "foo.ejs" file Express will invoke the following internally: + * + * app.engine('ejs', require('ejs').__express); + * + * For engines that do not provide `.__express` out of the box, + * or if you wish to "map" a different extension to the template engine + * you may use this method. For example mapping the EJS template engine to + * ".html" files: + * + * app.engine('html', require('ejs').renderFile); + * + * In this case EJS provides a `.renderFile()` method with + * the same signature that Express expects: `(path, options, callback)`, + * though note that it aliases this method as `ejs.__express` internally + * so if you're using ".ejs" extensions you don't need to do anything. + * + * Some template engines do not follow this convention, the + * [Consolidate.js](https://github.com/tj/consolidate.js) + * library was created to map all of node's popular template + * engines to follow this convention, thus allowing them to + * work seamlessly within Express. + * + * @param {String} ext + * @param {Function} fn + * @return {app} for chaining + * @public + */ + +app.engine = function engine(ext, fn) { + if (typeof fn !== 'function') { + throw new Error('callback function required'); + } + + // get file extension + var extension = ext[0] !== '.' + ? '.' + ext + : ext; + + // store engine + this.engines[extension] = fn; + + return this; +}; + +/** + * Proxy to `Router#param()` with one added api feature. The _name_ parameter + * can be an array of names. + * + * See the Router#param() docs for more details. + * + * @param {String|Array} name + * @param {Function} fn + * @return {app} for chaining + * @public + */ + +app.param = function param(name, fn) { + this.lazyrouter(); + + if (Array.isArray(name)) { + for (var i = 0; i < name.length; i++) { + this.param(name[i], fn); + } + + return this; + } + + this._router.param(name, fn); + + return this; +}; + +/** + * Assign `setting` to `val`, or return `setting`'s value. + * + * app.set('foo', 'bar'); + * app.set('foo'); + * // => "bar" + * + * Mounted servers inherit their parent server's settings. + * + * @param {String} setting + * @param {*} [val] + * @return {Server} for chaining + * @public + */ + +app.set = function set(setting, val) { + if (arguments.length === 1) { + // app.get(setting) + var settings = this.settings + + while (settings && settings !== Object.prototype) { + if (hasOwnProperty.call(settings, setting)) { + return settings[setting] + } + + settings = Object.getPrototypeOf(settings) + } + + return undefined + } + + debug('set "%s" to %o', setting, val); + + // set value + this.settings[setting] = val; + + // trigger matched settings + switch (setting) { + case 'etag': + this.set('etag fn', compileETag(val)); + break; + case 'query parser': + this.set('query parser fn', compileQueryParser(val)); + break; + case 'trust proxy': + this.set('trust proxy fn', compileTrust(val)); + + // trust proxy inherit back-compat + Object.defineProperty(this.settings, trustProxyDefaultSymbol, { + configurable: true, + value: false + }); + + break; + } + + return this; +}; + +/** + * Return the app's absolute pathname + * based on the parent(s) that have + * mounted it. + * + * For example if the application was + * mounted as "/admin", which itself + * was mounted as "/blog" then the + * return value would be "/blog/admin". + * + * @return {String} + * @private + */ + +app.path = function path() { + return this.parent + ? this.parent.path() + this.mountpath + : ''; +}; + +/** + * Check if `setting` is enabled (truthy). + * + * app.enabled('foo') + * // => false + * + * app.enable('foo') + * app.enabled('foo') + * // => true + * + * @param {String} setting + * @return {Boolean} + * @public + */ + +app.enabled = function enabled(setting) { + return Boolean(this.set(setting)); +}; + +/** + * Check if `setting` is disabled. + * + * app.disabled('foo') + * // => true + * + * app.enable('foo') + * app.disabled('foo') + * // => false + * + * @param {String} setting + * @return {Boolean} + * @public + */ + +app.disabled = function disabled(setting) { + return !this.set(setting); +}; + +/** + * Enable `setting`. + * + * @param {String} setting + * @return {app} for chaining + * @public + */ + +app.enable = function enable(setting) { + return this.set(setting, true); +}; + +/** + * Disable `setting`. + * + * @param {String} setting + * @return {app} for chaining + * @public + */ + +app.disable = function disable(setting) { + return this.set(setting, false); +}; + +/** + * Delegate `.VERB(...)` calls to `router.VERB(...)`. + */ + +methods.forEach(function(method){ + app[method] = function(path){ + if (method === 'get' && arguments.length === 1) { + // app.get(setting) + return this.set(path); + } + + this.lazyrouter(); + + var route = this._router.route(path); + route[method].apply(route, slice.call(arguments, 1)); + return this; + }; +}); + +/** + * Special-cased "all" method, applying the given route `path`, + * middleware, and callback to _every_ HTTP method. + * + * @param {String} path + * @param {Function} ... + * @return {app} for chaining + * @public + */ + +app.all = function all(path) { + this.lazyrouter(); + + var route = this._router.route(path); + var args = slice.call(arguments, 1); + + for (var i = 0; i < methods.length; i++) { + route[methods[i]].apply(route, args); + } + + return this; +}; + +// del -> delete alias + +app.del = deprecate.function(app.delete, 'app.del: Use app.delete instead'); + +/** + * Render the given view `name` name with `options` + * and a callback accepting an error and the + * rendered template string. + * + * Example: + * + * app.render('email', { name: 'Tobi' }, function(err, html){ + * // ... + * }) + * + * @param {String} name + * @param {Object|Function} options or fn + * @param {Function} callback + * @public + */ + +app.render = function render(name, options, callback) { + var cache = this.cache; + var done = callback; + var engines = this.engines; + var opts = options; + var renderOptions = {}; + var view; + + // support callback function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } + + // merge app.locals + merge(renderOptions, this.locals); + + // merge options._locals + if (opts._locals) { + merge(renderOptions, opts._locals); + } + + // merge options + merge(renderOptions, opts); + + // set .cache unless explicitly provided + if (renderOptions.cache == null) { + renderOptions.cache = this.enabled('view cache'); + } + + // primed cache + if (renderOptions.cache) { + view = cache[name]; + } + + // view + if (!view) { + var View = this.get('view'); + + view = new View(name, { + defaultEngine: this.get('view engine'), + root: this.get('views'), + engines: engines + }); + + if (!view.path) { + var dirs = Array.isArray(view.root) && view.root.length > 1 + ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"' + : 'directory "' + view.root + '"' + var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs); + err.view = view; + return done(err); + } + + // prime the cache + if (renderOptions.cache) { + cache[name] = view; + } + } + + // render + tryRender(view, renderOptions, done); +}; + +/** + * Listen for connections. + * + * A node `http.Server` is returned, with this + * application (which is a `Function`) as its + * callback. If you wish to create both an HTTP + * and HTTPS server you may do so with the "http" + * and "https" modules as shown here: + * + * var http = require('http') + * , https = require('https') + * , express = require('express') + * , app = express(); + * + * http.createServer(app).listen(80); + * https.createServer({ ... }, app).listen(443); + * + * @return {http.Server} + * @public + */ + +app.listen = function listen() { + var server = http.createServer(this); + return server.listen.apply(server, arguments); +}; + +/** + * Log error using console.error. + * + * @param {Error} err + * @private + */ + +function logerror(err) { + /* istanbul ignore next */ + if (this.get('env') !== 'test') console.error(err.stack || err.toString()); +} + +/** + * Try rendering a view. + * @private + */ + +function tryRender(view, options, callback) { + try { + view.render(options, callback); + } catch (err) { + callback(err); + } +} diff --git a/gun-server/node_modules/express/lib/express.js b/gun-server/node_modules/express/lib/express.js new file mode 100644 index 0000000..d188a16 --- /dev/null +++ b/gun-server/node_modules/express/lib/express.js @@ -0,0 +1,116 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + */ + +var bodyParser = require('body-parser') +var EventEmitter = require('events').EventEmitter; +var mixin = require('merge-descriptors'); +var proto = require('./application'); +var Route = require('./router/route'); +var Router = require('./router'); +var req = require('./request'); +var res = require('./response'); + +/** + * Expose `createApplication()`. + */ + +exports = module.exports = createApplication; + +/** + * Create an express application. + * + * @return {Function} + * @api public + */ + +function createApplication() { + var app = function(req, res, next) { + app.handle(req, res, next); + }; + + mixin(app, EventEmitter.prototype, false); + mixin(app, proto, false); + + // expose the prototype that will get set on requests + app.request = Object.create(req, { + app: { configurable: true, enumerable: true, writable: true, value: app } + }) + + // expose the prototype that will get set on responses + app.response = Object.create(res, { + app: { configurable: true, enumerable: true, writable: true, value: app } + }) + + app.init(); + return app; +} + +/** + * Expose the prototypes. + */ + +exports.application = proto; +exports.request = req; +exports.response = res; + +/** + * Expose constructors. + */ + +exports.Route = Route; +exports.Router = Router; + +/** + * Expose middleware + */ + +exports.json = bodyParser.json +exports.query = require('./middleware/query'); +exports.raw = bodyParser.raw +exports.static = require('serve-static'); +exports.text = bodyParser.text +exports.urlencoded = bodyParser.urlencoded + +/** + * Replace removed middleware with an appropriate error message. + */ + +var removedMiddlewares = [ + 'bodyParser', + 'compress', + 'cookieSession', + 'session', + 'logger', + 'cookieParser', + 'favicon', + 'responseTime', + 'errorHandler', + 'timeout', + 'methodOverride', + 'vhost', + 'csrf', + 'directory', + 'limit', + 'multipart', + 'staticCache' +] + +removedMiddlewares.forEach(function (name) { + Object.defineProperty(exports, name, { + get: function () { + throw new Error('Most middleware (like ' + name + ') is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.'); + }, + configurable: true + }); +}); diff --git a/gun-server/node_modules/express/lib/middleware/init.js b/gun-server/node_modules/express/lib/middleware/init.js new file mode 100644 index 0000000..dfd0427 --- /dev/null +++ b/gun-server/node_modules/express/lib/middleware/init.js @@ -0,0 +1,43 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var setPrototypeOf = require('setprototypeof') + +/** + * Initialization middleware, exposing the + * request and response to each other, as well + * as defaulting the X-Powered-By header field. + * + * @param {Function} app + * @return {Function} + * @api private + */ + +exports.init = function(app){ + return function expressInit(req, res, next){ + if (app.enabled('x-powered-by')) res.setHeader('X-Powered-By', 'Express'); + req.res = res; + res.req = req; + req.next = next; + + setPrototypeOf(req, app.request) + setPrototypeOf(res, app.response) + + res.locals = res.locals || Object.create(null); + + next(); + }; +}; + diff --git a/gun-server/node_modules/express/lib/middleware/query.js b/gun-server/node_modules/express/lib/middleware/query.js new file mode 100644 index 0000000..7e91669 --- /dev/null +++ b/gun-server/node_modules/express/lib/middleware/query.js @@ -0,0 +1,47 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + */ + +var merge = require('utils-merge') +var parseUrl = require('parseurl'); +var qs = require('qs'); + +/** + * @param {Object} options + * @return {Function} + * @api public + */ + +module.exports = function query(options) { + var opts = merge({}, options) + var queryparse = qs.parse; + + if (typeof options === 'function') { + queryparse = options; + opts = undefined; + } + + if (opts !== undefined && opts.allowPrototypes === undefined) { + // back-compat for qs module + opts.allowPrototypes = true; + } + + return function query(req, res, next){ + if (!req.query) { + var val = parseUrl(req).query; + req.query = queryparse(val, opts); + } + + next(); + }; +}; diff --git a/gun-server/node_modules/express/lib/request.js b/gun-server/node_modules/express/lib/request.js new file mode 100644 index 0000000..3f1eeca --- /dev/null +++ b/gun-server/node_modules/express/lib/request.js @@ -0,0 +1,525 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var accepts = require('accepts'); +var deprecate = require('depd')('express'); +var isIP = require('net').isIP; +var typeis = require('type-is'); +var http = require('http'); +var fresh = require('fresh'); +var parseRange = require('range-parser'); +var parse = require('parseurl'); +var proxyaddr = require('proxy-addr'); + +/** + * Request prototype. + * @public + */ + +var req = Object.create(http.IncomingMessage.prototype) + +/** + * Module exports. + * @public + */ + +module.exports = req + +/** + * Return request header. + * + * The `Referrer` header field is special-cased, + * both `Referrer` and `Referer` are interchangeable. + * + * Examples: + * + * req.get('Content-Type'); + * // => "text/plain" + * + * req.get('content-type'); + * // => "text/plain" + * + * req.get('Something'); + * // => undefined + * + * Aliased as `req.header()`. + * + * @param {String} name + * @return {String} + * @public + */ + +req.get = +req.header = function header(name) { + if (!name) { + throw new TypeError('name argument is required to req.get'); + } + + if (typeof name !== 'string') { + throw new TypeError('name must be a string to req.get'); + } + + var lc = name.toLowerCase(); + + switch (lc) { + case 'referer': + case 'referrer': + return this.headers.referrer + || this.headers.referer; + default: + return this.headers[lc]; + } +}; + +/** + * To do: update docs. + * + * Check if the given `type(s)` is acceptable, returning + * the best match when true, otherwise `undefined`, in which + * case you should respond with 406 "Not Acceptable". + * + * The `type` value may be a single MIME type string + * such as "application/json", an extension name + * such as "json", a comma-delimited list such as "json, html, text/plain", + * an argument list such as `"json", "html", "text/plain"`, + * or an array `["json", "html", "text/plain"]`. When a list + * or array is given, the _best_ match, if any is returned. + * + * Examples: + * + * // Accept: text/html + * req.accepts('html'); + * // => "html" + * + * // Accept: text/*, application/json + * req.accepts('html'); + * // => "html" + * req.accepts('text/html'); + * // => "text/html" + * req.accepts('json, text'); + * // => "json" + * req.accepts('application/json'); + * // => "application/json" + * + * // Accept: text/*, application/json + * req.accepts('image/png'); + * req.accepts('png'); + * // => undefined + * + * // Accept: text/*;q=.5, application/json + * req.accepts(['html', 'json']); + * req.accepts('html', 'json'); + * req.accepts('html, json'); + * // => "json" + * + * @param {String|Array} type(s) + * @return {String|Array|Boolean} + * @public + */ + +req.accepts = function(){ + var accept = accepts(this); + return accept.types.apply(accept, arguments); +}; + +/** + * Check if the given `encoding`s are accepted. + * + * @param {String} ...encoding + * @return {String|Array} + * @public + */ + +req.acceptsEncodings = function(){ + var accept = accepts(this); + return accept.encodings.apply(accept, arguments); +}; + +req.acceptsEncoding = deprecate.function(req.acceptsEncodings, + 'req.acceptsEncoding: Use acceptsEncodings instead'); + +/** + * Check if the given `charset`s are acceptable, + * otherwise you should respond with 406 "Not Acceptable". + * + * @param {String} ...charset + * @return {String|Array} + * @public + */ + +req.acceptsCharsets = function(){ + var accept = accepts(this); + return accept.charsets.apply(accept, arguments); +}; + +req.acceptsCharset = deprecate.function(req.acceptsCharsets, + 'req.acceptsCharset: Use acceptsCharsets instead'); + +/** + * Check if the given `lang`s are acceptable, + * otherwise you should respond with 406 "Not Acceptable". + * + * @param {String} ...lang + * @return {String|Array} + * @public + */ + +req.acceptsLanguages = function(){ + var accept = accepts(this); + return accept.languages.apply(accept, arguments); +}; + +req.acceptsLanguage = deprecate.function(req.acceptsLanguages, + 'req.acceptsLanguage: Use acceptsLanguages instead'); + +/** + * Parse Range header field, capping to the given `size`. + * + * Unspecified ranges such as "0-" require knowledge of your resource length. In + * the case of a byte range this is of course the total number of bytes. If the + * Range header field is not given `undefined` is returned, `-1` when unsatisfiable, + * and `-2` when syntactically invalid. + * + * When ranges are returned, the array has a "type" property which is the type of + * range that is required (most commonly, "bytes"). Each array element is an object + * with a "start" and "end" property for the portion of the range. + * + * The "combine" option can be set to `true` and overlapping & adjacent ranges + * will be combined into a single range. + * + * NOTE: remember that ranges are inclusive, so for example "Range: users=0-3" + * should respond with 4 users when available, not 3. + * + * @param {number} size + * @param {object} [options] + * @param {boolean} [options.combine=false] + * @return {number|array} + * @public + */ + +req.range = function range(size, options) { + var range = this.get('Range'); + if (!range) return; + return parseRange(size, range, options); +}; + +/** + * Return the value of param `name` when present or `defaultValue`. + * + * - Checks route placeholders, ex: _/user/:id_ + * - Checks body params, ex: id=12, {"id":12} + * - Checks query string params, ex: ?id=12 + * + * To utilize request bodies, `req.body` + * should be an object. This can be done by using + * the `bodyParser()` middleware. + * + * @param {String} name + * @param {Mixed} [defaultValue] + * @return {String} + * @public + */ + +req.param = function param(name, defaultValue) { + var params = this.params || {}; + var body = this.body || {}; + var query = this.query || {}; + + var args = arguments.length === 1 + ? 'name' + : 'name, default'; + deprecate('req.param(' + args + '): Use req.params, req.body, or req.query instead'); + + if (null != params[name] && params.hasOwnProperty(name)) return params[name]; + if (null != body[name]) return body[name]; + if (null != query[name]) return query[name]; + + return defaultValue; +}; + +/** + * Check if the incoming request contains the "Content-Type" + * header field, and it contains the given mime `type`. + * + * Examples: + * + * // With Content-Type: text/html; charset=utf-8 + * req.is('html'); + * req.is('text/html'); + * req.is('text/*'); + * // => true + * + * // When Content-Type is application/json + * req.is('json'); + * req.is('application/json'); + * req.is('application/*'); + * // => true + * + * req.is('html'); + * // => false + * + * @param {String|Array} types... + * @return {String|false|null} + * @public + */ + +req.is = function is(types) { + var arr = types; + + // support flattened arguments + if (!Array.isArray(types)) { + arr = new Array(arguments.length); + for (var i = 0; i < arr.length; i++) { + arr[i] = arguments[i]; + } + } + + return typeis(this, arr); +}; + +/** + * Return the protocol string "http" or "https" + * when requested with TLS. When the "trust proxy" + * setting trusts the socket address, the + * "X-Forwarded-Proto" header field will be trusted + * and used if present. + * + * If you're running behind a reverse proxy that + * supplies https for you this may be enabled. + * + * @return {String} + * @public + */ + +defineGetter(req, 'protocol', function protocol(){ + var proto = this.connection.encrypted + ? 'https' + : 'http'; + var trust = this.app.get('trust proxy fn'); + + if (!trust(this.connection.remoteAddress, 0)) { + return proto; + } + + // Note: X-Forwarded-Proto is normally only ever a + // single value, but this is to be safe. + var header = this.get('X-Forwarded-Proto') || proto + var index = header.indexOf(',') + + return index !== -1 + ? header.substring(0, index).trim() + : header.trim() +}); + +/** + * Short-hand for: + * + * req.protocol === 'https' + * + * @return {Boolean} + * @public + */ + +defineGetter(req, 'secure', function secure(){ + return this.protocol === 'https'; +}); + +/** + * Return the remote address from the trusted proxy. + * + * The is the remote address on the socket unless + * "trust proxy" is set. + * + * @return {String} + * @public + */ + +defineGetter(req, 'ip', function ip(){ + var trust = this.app.get('trust proxy fn'); + return proxyaddr(this, trust); +}); + +/** + * When "trust proxy" is set, trusted proxy addresses + client. + * + * For example if the value were "client, proxy1, proxy2" + * you would receive the array `["client", "proxy1", "proxy2"]` + * where "proxy2" is the furthest down-stream and "proxy1" and + * "proxy2" were trusted. + * + * @return {Array} + * @public + */ + +defineGetter(req, 'ips', function ips() { + var trust = this.app.get('trust proxy fn'); + var addrs = proxyaddr.all(this, trust); + + // reverse the order (to farthest -> closest) + // and remove socket address + addrs.reverse().pop() + + return addrs +}); + +/** + * Return subdomains as an array. + * + * Subdomains are the dot-separated parts of the host before the main domain of + * the app. By default, the domain of the app is assumed to be the last two + * parts of the host. This can be changed by setting "subdomain offset". + * + * For example, if the domain is "tobi.ferrets.example.com": + * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`. + * If "subdomain offset" is 3, req.subdomains is `["tobi"]`. + * + * @return {Array} + * @public + */ + +defineGetter(req, 'subdomains', function subdomains() { + var hostname = this.hostname; + + if (!hostname) return []; + + var offset = this.app.get('subdomain offset'); + var subdomains = !isIP(hostname) + ? hostname.split('.').reverse() + : [hostname]; + + return subdomains.slice(offset); +}); + +/** + * Short-hand for `url.parse(req.url).pathname`. + * + * @return {String} + * @public + */ + +defineGetter(req, 'path', function path() { + return parse(this).pathname; +}); + +/** + * Parse the "Host" header field to a hostname. + * + * When the "trust proxy" setting trusts the socket + * address, the "X-Forwarded-Host" header field will + * be trusted. + * + * @return {String} + * @public + */ + +defineGetter(req, 'hostname', function hostname(){ + var trust = this.app.get('trust proxy fn'); + var host = this.get('X-Forwarded-Host'); + + if (!host || !trust(this.connection.remoteAddress, 0)) { + host = this.get('Host'); + } else if (host.indexOf(',') !== -1) { + // Note: X-Forwarded-Host is normally only ever a + // single value, but this is to be safe. + host = host.substring(0, host.indexOf(',')).trimRight() + } + + if (!host) return; + + // IPv6 literal support + var offset = host[0] === '[' + ? host.indexOf(']') + 1 + : 0; + var index = host.indexOf(':', offset); + + return index !== -1 + ? host.substring(0, index) + : host; +}); + +// TODO: change req.host to return host in next major + +defineGetter(req, 'host', deprecate.function(function host(){ + return this.hostname; +}, 'req.host: Use req.hostname instead')); + +/** + * Check if the request is fresh, aka + * Last-Modified and/or the ETag + * still match. + * + * @return {Boolean} + * @public + */ + +defineGetter(req, 'fresh', function(){ + var method = this.method; + var res = this.res + var status = res.statusCode + + // GET or HEAD for weak freshness validation only + if ('GET' !== method && 'HEAD' !== method) return false; + + // 2xx or 304 as per rfc2616 14.26 + if ((status >= 200 && status < 300) || 304 === status) { + return fresh(this.headers, { + 'etag': res.get('ETag'), + 'last-modified': res.get('Last-Modified') + }) + } + + return false; +}); + +/** + * Check if the request is stale, aka + * "Last-Modified" and / or the "ETag" for the + * resource has changed. + * + * @return {Boolean} + * @public + */ + +defineGetter(req, 'stale', function stale(){ + return !this.fresh; +}); + +/** + * Check if the request was an _XMLHttpRequest_. + * + * @return {Boolean} + * @public + */ + +defineGetter(req, 'xhr', function xhr(){ + var val = this.get('X-Requested-With') || ''; + return val.toLowerCase() === 'xmlhttprequest'; +}); + +/** + * Helper function for creating a getter on an object. + * + * @param {Object} obj + * @param {String} name + * @param {Function} getter + * @private + */ +function defineGetter(obj, name, getter) { + Object.defineProperty(obj, name, { + configurable: true, + enumerable: true, + get: getter + }); +} diff --git a/gun-server/node_modules/express/lib/response.js b/gun-server/node_modules/express/lib/response.js new file mode 100644 index 0000000..dd7b3c8 --- /dev/null +++ b/gun-server/node_modules/express/lib/response.js @@ -0,0 +1,1178 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var Buffer = require('safe-buffer').Buffer +var contentDisposition = require('content-disposition'); +var createError = require('http-errors') +var deprecate = require('depd')('express'); +var encodeUrl = require('encodeurl'); +var escapeHtml = require('escape-html'); +var http = require('http'); +var isAbsolute = require('./utils').isAbsolute; +var onFinished = require('on-finished'); +var path = require('path'); +var statuses = require('statuses') +var merge = require('utils-merge'); +var sign = require('cookie-signature').sign; +var normalizeType = require('./utils').normalizeType; +var normalizeTypes = require('./utils').normalizeTypes; +var setCharset = require('./utils').setCharset; +var cookie = require('cookie'); +var send = require('send'); +var extname = path.extname; +var mime = send.mime; +var resolve = path.resolve; +var vary = require('vary'); + +/** + * Response prototype. + * @public + */ + +var res = Object.create(http.ServerResponse.prototype) + +/** + * Module exports. + * @public + */ + +module.exports = res + +/** + * Module variables. + * @private + */ + +var charsetRegExp = /;\s*charset\s*=/; +var schemaAndHostRegExp = /^(?:[a-zA-Z][a-zA-Z0-9+.-]*:)?\/\/[^\\\/\?]+/; + +/** + * Set status `code`. + * + * @param {Number} code + * @return {ServerResponse} + * @public + */ + +res.status = function status(code) { + if ((typeof code === 'string' || Math.floor(code) !== code) && code > 99 && code < 1000) { + deprecate('res.status(' + JSON.stringify(code) + '): use res.status(' + Math.floor(code) + ') instead') + } + this.statusCode = code; + return this; +}; + +/** + * Set Link header field with the given `links`. + * + * Examples: + * + * res.links({ + * next: 'http://api.example.com/users?page=2', + * last: 'http://api.example.com/users?page=5' + * }); + * + * @param {Object} links + * @return {ServerResponse} + * @public + */ + +res.links = function(links){ + var link = this.get('Link') || ''; + if (link) link += ', '; + return this.set('Link', link + Object.keys(links).map(function(rel){ + return '<' + links[rel] + '>; rel="' + rel + '"'; + }).join(', ')); +}; + +/** + * Send a response. + * + * Examples: + * + * res.send(Buffer.from('wahoo')); + * res.send({ some: 'json' }); + * res.send('

      some html

      '); + * + * @param {string|number|boolean|object|Buffer} body + * @public + */ + +res.send = function send(body) { + var chunk = body; + var encoding; + var req = this.req; + var type; + + // settings + var app = this.app; + + // allow status / body + if (arguments.length === 2) { + // res.send(body, status) backwards compat + if (typeof arguments[0] !== 'number' && typeof arguments[1] === 'number') { + deprecate('res.send(body, status): Use res.status(status).send(body) instead'); + this.statusCode = arguments[1]; + } else { + deprecate('res.send(status, body): Use res.status(status).send(body) instead'); + this.statusCode = arguments[0]; + chunk = arguments[1]; + } + } + + // disambiguate res.send(status) and res.send(status, num) + if (typeof chunk === 'number' && arguments.length === 1) { + // res.send(status) will set status message as text string + if (!this.get('Content-Type')) { + this.type('txt'); + } + + deprecate('res.send(status): Use res.sendStatus(status) instead'); + this.statusCode = chunk; + chunk = statuses.message[chunk] + } + + switch (typeof chunk) { + // string defaulting to html + case 'string': + if (!this.get('Content-Type')) { + this.type('html'); + } + break; + case 'boolean': + case 'number': + case 'object': + if (chunk === null) { + chunk = ''; + } else if (Buffer.isBuffer(chunk)) { + if (!this.get('Content-Type')) { + this.type('bin'); + } + } else { + return this.json(chunk); + } + break; + } + + // write strings in utf-8 + if (typeof chunk === 'string') { + encoding = 'utf8'; + type = this.get('Content-Type'); + + // reflect this in content-type + if (typeof type === 'string') { + this.set('Content-Type', setCharset(type, 'utf-8')); + } + } + + // determine if ETag should be generated + var etagFn = app.get('etag fn') + var generateETag = !this.get('ETag') && typeof etagFn === 'function' + + // populate Content-Length + var len + if (chunk !== undefined) { + if (Buffer.isBuffer(chunk)) { + // get length of Buffer + len = chunk.length + } else if (!generateETag && chunk.length < 1000) { + // just calculate length when no ETag + small chunk + len = Buffer.byteLength(chunk, encoding) + } else { + // convert chunk to Buffer and calculate + chunk = Buffer.from(chunk, encoding) + encoding = undefined; + len = chunk.length + } + + this.set('Content-Length', len); + } + + // populate ETag + var etag; + if (generateETag && len !== undefined) { + if ((etag = etagFn(chunk, encoding))) { + this.set('ETag', etag); + } + } + + // freshness + if (req.fresh) this.statusCode = 304; + + // strip irrelevant headers + if (204 === this.statusCode || 304 === this.statusCode) { + this.removeHeader('Content-Type'); + this.removeHeader('Content-Length'); + this.removeHeader('Transfer-Encoding'); + chunk = ''; + } + + // alter headers for 205 + if (this.statusCode === 205) { + this.set('Content-Length', '0') + this.removeHeader('Transfer-Encoding') + chunk = '' + } + + if (req.method === 'HEAD') { + // skip body for HEAD + this.end(); + } else { + // respond + this.end(chunk, encoding); + } + + return this; +}; + +/** + * Send JSON response. + * + * Examples: + * + * res.json(null); + * res.json({ user: 'tj' }); + * + * @param {string|number|boolean|object} obj + * @public + */ + +res.json = function json(obj) { + var val = obj; + + // allow status / body + if (arguments.length === 2) { + // res.json(body, status) backwards compat + if (typeof arguments[1] === 'number') { + deprecate('res.json(obj, status): Use res.status(status).json(obj) instead'); + this.statusCode = arguments[1]; + } else { + deprecate('res.json(status, obj): Use res.status(status).json(obj) instead'); + this.statusCode = arguments[0]; + val = arguments[1]; + } + } + + // settings + var app = this.app; + var escape = app.get('json escape') + var replacer = app.get('json replacer'); + var spaces = app.get('json spaces'); + var body = stringify(val, replacer, spaces, escape) + + // content-type + if (!this.get('Content-Type')) { + this.set('Content-Type', 'application/json'); + } + + return this.send(body); +}; + +/** + * Send JSON response with JSONP callback support. + * + * Examples: + * + * res.jsonp(null); + * res.jsonp({ user: 'tj' }); + * + * @param {string|number|boolean|object} obj + * @public + */ + +res.jsonp = function jsonp(obj) { + var val = obj; + + // allow status / body + if (arguments.length === 2) { + // res.jsonp(body, status) backwards compat + if (typeof arguments[1] === 'number') { + deprecate('res.jsonp(obj, status): Use res.status(status).jsonp(obj) instead'); + this.statusCode = arguments[1]; + } else { + deprecate('res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead'); + this.statusCode = arguments[0]; + val = arguments[1]; + } + } + + // settings + var app = this.app; + var escape = app.get('json escape') + var replacer = app.get('json replacer'); + var spaces = app.get('json spaces'); + var body = stringify(val, replacer, spaces, escape) + var callback = this.req.query[app.get('jsonp callback name')]; + + // content-type + if (!this.get('Content-Type')) { + this.set('X-Content-Type-Options', 'nosniff'); + this.set('Content-Type', 'application/json'); + } + + // fixup callback + if (Array.isArray(callback)) { + callback = callback[0]; + } + + // jsonp + if (typeof callback === 'string' && callback.length !== 0) { + this.set('X-Content-Type-Options', 'nosniff'); + this.set('Content-Type', 'text/javascript'); + + // restrict callback charset + callback = callback.replace(/[^\[\]\w$.]/g, ''); + + if (body === undefined) { + // empty argument + body = '' + } else if (typeof body === 'string') { + // replace chars not allowed in JavaScript that are in JSON + body = body + .replace(/\u2028/g, '\\u2028') + .replace(/\u2029/g, '\\u2029') + } + + // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse" + // the typeof check is just to reduce client error noise + body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');'; + } + + return this.send(body); +}; + +/** + * Send given HTTP status code. + * + * Sets the response status to `statusCode` and the body of the + * response to the standard description from node's http.STATUS_CODES + * or the statusCode number if no description. + * + * Examples: + * + * res.sendStatus(200); + * + * @param {number} statusCode + * @public + */ + +res.sendStatus = function sendStatus(statusCode) { + var body = statuses.message[statusCode] || String(statusCode) + + this.statusCode = statusCode; + this.type('txt'); + + return this.send(body); +}; + +/** + * Transfer the file at the given `path`. + * + * Automatically sets the _Content-Type_ response header field. + * The callback `callback(err)` is invoked when the transfer is complete + * or when an error occurs. Be sure to check `res.headersSent` + * if you wish to attempt responding, as the header and some data + * may have already been transferred. + * + * Options: + * + * - `maxAge` defaulting to 0 (can be string converted by `ms`) + * - `root` root directory for relative filenames + * - `headers` object of headers to serve with file + * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them + * + * Other options are passed along to `send`. + * + * Examples: + * + * The following example illustrates how `res.sendFile()` may + * be used as an alternative for the `static()` middleware for + * dynamic situations. The code backing `res.sendFile()` is actually + * the same code, so HTTP cache support etc is identical. + * + * app.get('/user/:uid/photos/:file', function(req, res){ + * var uid = req.params.uid + * , file = req.params.file; + * + * req.user.mayViewFilesFrom(uid, function(yes){ + * if (yes) { + * res.sendFile('/uploads/' + uid + '/' + file); + * } else { + * res.send(403, 'Sorry! you cant see that.'); + * } + * }); + * }); + * + * @public + */ + +res.sendFile = function sendFile(path, options, callback) { + var done = callback; + var req = this.req; + var res = this; + var next = req.next; + var opts = options || {}; + + if (!path) { + throw new TypeError('path argument is required to res.sendFile'); + } + + if (typeof path !== 'string') { + throw new TypeError('path must be a string to res.sendFile') + } + + // support function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } + + if (!opts.root && !isAbsolute(path)) { + throw new TypeError('path must be absolute or specify root to res.sendFile'); + } + + // create file stream + var pathname = encodeURI(path); + var file = send(req, pathname, opts); + + // transfer + sendfile(res, file, opts, function (err) { + if (done) return done(err); + if (err && err.code === 'EISDIR') return next(); + + // next() all but write errors + if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') { + next(err); + } + }); +}; + +/** + * Transfer the file at the given `path`. + * + * Automatically sets the _Content-Type_ response header field. + * The callback `callback(err)` is invoked when the transfer is complete + * or when an error occurs. Be sure to check `res.headersSent` + * if you wish to attempt responding, as the header and some data + * may have already been transferred. + * + * Options: + * + * - `maxAge` defaulting to 0 (can be string converted by `ms`) + * - `root` root directory for relative filenames + * - `headers` object of headers to serve with file + * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them + * + * Other options are passed along to `send`. + * + * Examples: + * + * The following example illustrates how `res.sendfile()` may + * be used as an alternative for the `static()` middleware for + * dynamic situations. The code backing `res.sendfile()` is actually + * the same code, so HTTP cache support etc is identical. + * + * app.get('/user/:uid/photos/:file', function(req, res){ + * var uid = req.params.uid + * , file = req.params.file; + * + * req.user.mayViewFilesFrom(uid, function(yes){ + * if (yes) { + * res.sendfile('/uploads/' + uid + '/' + file); + * } else { + * res.send(403, 'Sorry! you cant see that.'); + * } + * }); + * }); + * + * @public + */ + +res.sendfile = function (path, options, callback) { + var done = callback; + var req = this.req; + var res = this; + var next = req.next; + var opts = options || {}; + + // support function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } + + // create file stream + var file = send(req, path, opts); + + // transfer + sendfile(res, file, opts, function (err) { + if (done) return done(err); + if (err && err.code === 'EISDIR') return next(); + + // next() all but write errors + if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') { + next(err); + } + }); +}; + +res.sendfile = deprecate.function(res.sendfile, + 'res.sendfile: Use res.sendFile instead'); + +/** + * Transfer the file at the given `path` as an attachment. + * + * Optionally providing an alternate attachment `filename`, + * and optional callback `callback(err)`. The callback is invoked + * when the data transfer is complete, or when an error has + * occurred. Be sure to check `res.headersSent` if you plan to respond. + * + * Optionally providing an `options` object to use with `res.sendFile()`. + * This function will set the `Content-Disposition` header, overriding + * any `Content-Disposition` header passed as header options in order + * to set the attachment and filename. + * + * This method uses `res.sendFile()`. + * + * @public + */ + +res.download = function download (path, filename, options, callback) { + var done = callback; + var name = filename; + var opts = options || null + + // support function as second or third arg + if (typeof filename === 'function') { + done = filename; + name = null; + opts = null + } else if (typeof options === 'function') { + done = options + opts = null + } + + // support optional filename, where options may be in it's place + if (typeof filename === 'object' && + (typeof options === 'function' || options === undefined)) { + name = null + opts = filename + } + + // set Content-Disposition when file is sent + var headers = { + 'Content-Disposition': contentDisposition(name || path) + }; + + // merge user-provided headers + if (opts && opts.headers) { + var keys = Object.keys(opts.headers) + for (var i = 0; i < keys.length; i++) { + var key = keys[i] + if (key.toLowerCase() !== 'content-disposition') { + headers[key] = opts.headers[key] + } + } + } + + // merge user-provided options + opts = Object.create(opts) + opts.headers = headers + + // Resolve the full path for sendFile + var fullPath = !opts.root + ? resolve(path) + : path + + // send file + return this.sendFile(fullPath, opts, done) +}; + +/** + * Set _Content-Type_ response header with `type` through `mime.lookup()` + * when it does not contain "/", or set the Content-Type to `type` otherwise. + * + * Examples: + * + * res.type('.html'); + * res.type('html'); + * res.type('json'); + * res.type('application/json'); + * res.type('png'); + * + * @param {String} type + * @return {ServerResponse} for chaining + * @public + */ + +res.contentType = +res.type = function contentType(type) { + var ct = type.indexOf('/') === -1 + ? mime.lookup(type) + : type; + + return this.set('Content-Type', ct); +}; + +/** + * Respond to the Acceptable formats using an `obj` + * of mime-type callbacks. + * + * This method uses `req.accepted`, an array of + * acceptable types ordered by their quality values. + * When "Accept" is not present the _first_ callback + * is invoked, otherwise the first match is used. When + * no match is performed the server responds with + * 406 "Not Acceptable". + * + * Content-Type is set for you, however if you choose + * you may alter this within the callback using `res.type()` + * or `res.set('Content-Type', ...)`. + * + * res.format({ + * 'text/plain': function(){ + * res.send('hey'); + * }, + * + * 'text/html': function(){ + * res.send('

      hey

      '); + * }, + * + * 'application/json': function () { + * res.send({ message: 'hey' }); + * } + * }); + * + * In addition to canonicalized MIME types you may + * also use extnames mapped to these types: + * + * res.format({ + * text: function(){ + * res.send('hey'); + * }, + * + * html: function(){ + * res.send('

      hey

      '); + * }, + * + * json: function(){ + * res.send({ message: 'hey' }); + * } + * }); + * + * By default Express passes an `Error` + * with a `.status` of 406 to `next(err)` + * if a match is not made. If you provide + * a `.default` callback it will be invoked + * instead. + * + * @param {Object} obj + * @return {ServerResponse} for chaining + * @public + */ + +res.format = function(obj){ + var req = this.req; + var next = req.next; + + var keys = Object.keys(obj) + .filter(function (v) { return v !== 'default' }) + + var key = keys.length > 0 + ? req.accepts(keys) + : false; + + this.vary("Accept"); + + if (key) { + this.set('Content-Type', normalizeType(key).value); + obj[key](req, this, next); + } else if (obj.default) { + obj.default(req, this, next) + } else { + next(createError(406, { + types: normalizeTypes(keys).map(function (o) { return o.value }) + })) + } + + return this; +}; + +/** + * Set _Content-Disposition_ header to _attachment_ with optional `filename`. + * + * @param {String} filename + * @return {ServerResponse} + * @public + */ + +res.attachment = function attachment(filename) { + if (filename) { + this.type(extname(filename)); + } + + this.set('Content-Disposition', contentDisposition(filename)); + + return this; +}; + +/** + * Append additional header `field` with value `val`. + * + * Example: + * + * res.append('Link', ['', '']); + * res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly'); + * res.append('Warning', '199 Miscellaneous warning'); + * + * @param {String} field + * @param {String|Array} val + * @return {ServerResponse} for chaining + * @public + */ + +res.append = function append(field, val) { + var prev = this.get(field); + var value = val; + + if (prev) { + // concat the new and prev vals + value = Array.isArray(prev) ? prev.concat(val) + : Array.isArray(val) ? [prev].concat(val) + : [prev, val] + } + + return this.set(field, value); +}; + +/** + * Set header `field` to `val`, or pass + * an object of header fields. + * + * Examples: + * + * res.set('Foo', ['bar', 'baz']); + * res.set('Accept', 'application/json'); + * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' }); + * + * Aliased as `res.header()`. + * + * @param {String|Object} field + * @param {String|Array} val + * @return {ServerResponse} for chaining + * @public + */ + +res.set = +res.header = function header(field, val) { + if (arguments.length === 2) { + var value = Array.isArray(val) + ? val.map(String) + : String(val); + + // add charset to content-type + if (field.toLowerCase() === 'content-type') { + if (Array.isArray(value)) { + throw new TypeError('Content-Type cannot be set to an Array'); + } + if (!charsetRegExp.test(value)) { + var charset = mime.charsets.lookup(value.split(';')[0]); + if (charset) value += '; charset=' + charset.toLowerCase(); + } + } + + this.setHeader(field, value); + } else { + for (var key in field) { + this.set(key, field[key]); + } + } + return this; +}; + +/** + * Get value for header `field`. + * + * @param {String} field + * @return {String} + * @public + */ + +res.get = function(field){ + return this.getHeader(field); +}; + +/** + * Clear cookie `name`. + * + * @param {String} name + * @param {Object} [options] + * @return {ServerResponse} for chaining + * @public + */ + +res.clearCookie = function clearCookie(name, options) { + var opts = merge({ expires: new Date(1), path: '/' }, options); + + return this.cookie(name, '', opts); +}; + +/** + * Set cookie `name` to `value`, with the given `options`. + * + * Options: + * + * - `maxAge` max-age in milliseconds, converted to `expires` + * - `signed` sign the cookie + * - `path` defaults to "/" + * + * Examples: + * + * // "Remember Me" for 15 minutes + * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }); + * + * // same as above + * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }) + * + * @param {String} name + * @param {String|Object} value + * @param {Object} [options] + * @return {ServerResponse} for chaining + * @public + */ + +res.cookie = function (name, value, options) { + var opts = merge({}, options); + var secret = this.req.secret; + var signed = opts.signed; + + if (signed && !secret) { + throw new Error('cookieParser("secret") required for signed cookies'); + } + + var val = typeof value === 'object' + ? 'j:' + JSON.stringify(value) + : String(value); + + if (signed) { + val = 's:' + sign(val, secret); + } + + if (opts.maxAge != null) { + var maxAge = opts.maxAge - 0 + + if (!isNaN(maxAge)) { + opts.expires = new Date(Date.now() + maxAge) + opts.maxAge = Math.floor(maxAge / 1000) + } + } + + if (opts.path == null) { + opts.path = '/'; + } + + this.append('Set-Cookie', cookie.serialize(name, String(val), opts)); + + return this; +}; + +/** + * Set the location header to `url`. + * + * The given `url` can also be "back", which redirects + * to the _Referrer_ or _Referer_ headers or "/". + * + * Examples: + * + * res.location('/foo/bar').; + * res.location('http://example.com'); + * res.location('../login'); + * + * @param {String} url + * @return {ServerResponse} for chaining + * @public + */ + +res.location = function location(url) { + var loc; + + // "back" is an alias for the referrer + if (url === 'back') { + loc = this.req.get('Referrer') || '/'; + } else { + loc = String(url); + } + + var m = schemaAndHostRegExp.exec(loc); + var pos = m ? m[0].length + 1 : 0; + + // Only encode after host to avoid invalid encoding which can introduce + // vulnerabilities (e.g. `\\` to `%5C`). + loc = loc.slice(0, pos) + encodeUrl(loc.slice(pos)); + + return this.set('Location', loc); +}; + +/** + * Redirect to the given `url` with optional response `status` + * defaulting to 302. + * + * The resulting `url` is determined by `res.location()`, so + * it will play nicely with mounted apps, relative paths, + * `"back"` etc. + * + * Examples: + * + * res.redirect('/foo/bar'); + * res.redirect('http://example.com'); + * res.redirect(301, 'http://example.com'); + * res.redirect('../login'); // /blog/post/1 -> /blog/login + * + * @public + */ + +res.redirect = function redirect(url) { + var address = url; + var body; + var status = 302; + + // allow status / url + if (arguments.length === 2) { + if (typeof arguments[0] === 'number') { + status = arguments[0]; + address = arguments[1]; + } else { + deprecate('res.redirect(url, status): Use res.redirect(status, url) instead'); + status = arguments[1]; + } + } + + // Set location header + address = this.location(address).get('Location'); + + // Support text/{plain,html} by default + this.format({ + text: function(){ + body = statuses.message[status] + '. Redirecting to ' + address + }, + + html: function(){ + var u = escapeHtml(address); + body = '

      ' + statuses.message[status] + '. Redirecting to ' + u + '

      ' + }, + + default: function(){ + body = ''; + } + }); + + // Respond + this.statusCode = status; + this.set('Content-Length', Buffer.byteLength(body)); + + if (this.req.method === 'HEAD') { + this.end(); + } else { + this.end(body); + } +}; + +/** + * Add `field` to Vary. If already present in the Vary set, then + * this call is simply ignored. + * + * @param {Array|String} field + * @return {ServerResponse} for chaining + * @public + */ + +res.vary = function(field){ + // checks for back-compat + if (!field || (Array.isArray(field) && !field.length)) { + deprecate('res.vary(): Provide a field name'); + return this; + } + + vary(this, field); + + return this; +}; + +/** + * Render `view` with the given `options` and optional callback `fn`. + * When a callback function is given a response will _not_ be made + * automatically, otherwise a response of _200_ and _text/html_ is given. + * + * Options: + * + * - `cache` boolean hinting to the engine it should cache + * - `filename` filename of the view being rendered + * + * @public + */ + +res.render = function render(view, options, callback) { + var app = this.req.app; + var done = callback; + var opts = options || {}; + var req = this.req; + var self = this; + + // support callback function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } + + // merge res.locals + opts._locals = self.locals; + + // default callback to respond + done = done || function (err, str) { + if (err) return req.next(err); + self.send(str); + }; + + // render + app.render(view, opts, done); +}; + +// pipe the send file stream +function sendfile(res, file, options, callback) { + var done = false; + var streaming; + + // request aborted + function onaborted() { + if (done) return; + done = true; + + var err = new Error('Request aborted'); + err.code = 'ECONNABORTED'; + callback(err); + } + + // directory + function ondirectory() { + if (done) return; + done = true; + + var err = new Error('EISDIR, read'); + err.code = 'EISDIR'; + callback(err); + } + + // errors + function onerror(err) { + if (done) return; + done = true; + callback(err); + } + + // ended + function onend() { + if (done) return; + done = true; + callback(); + } + + // file + function onfile() { + streaming = false; + } + + // finished + function onfinish(err) { + if (err && err.code === 'ECONNRESET') return onaborted(); + if (err) return onerror(err); + if (done) return; + + setImmediate(function () { + if (streaming !== false && !done) { + onaborted(); + return; + } + + if (done) return; + done = true; + callback(); + }); + } + + // streaming + function onstream() { + streaming = true; + } + + file.on('directory', ondirectory); + file.on('end', onend); + file.on('error', onerror); + file.on('file', onfile); + file.on('stream', onstream); + onFinished(res, onfinish); + + if (options.headers) { + // set headers on successful transfer + file.on('headers', function headers(res) { + var obj = options.headers; + var keys = Object.keys(obj); + + for (var i = 0; i < keys.length; i++) { + var k = keys[i]; + res.setHeader(k, obj[k]); + } + }); + } + + // pipe + file.pipe(res); +} + +/** + * Stringify JSON, like JSON.stringify, but v8 optimized, with the + * ability to escape characters that can trigger HTML sniffing. + * + * @param {*} value + * @param {function} replacer + * @param {number} spaces + * @param {boolean} escape + * @returns {string} + * @private + */ + +function stringify (value, replacer, spaces, escape) { + // v8 checks arguments.length for optimizing simple call + // https://bugs.chromium.org/p/v8/issues/detail?id=4730 + var json = replacer || spaces + ? JSON.stringify(value, replacer, spaces) + : JSON.stringify(value); + + if (escape && typeof json === 'string') { + json = json.replace(/[<>&]/g, function (c) { + switch (c.charCodeAt(0)) { + case 0x3c: + return '\\u003c' + case 0x3e: + return '\\u003e' + case 0x26: + return '\\u0026' + /* istanbul ignore next: unreachable default */ + default: + return c + } + }) + } + + return json +} diff --git a/gun-server/node_modules/express/lib/router/index.js b/gun-server/node_modules/express/lib/router/index.js new file mode 100644 index 0000000..abb3a6f --- /dev/null +++ b/gun-server/node_modules/express/lib/router/index.js @@ -0,0 +1,673 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var Route = require('./route'); +var Layer = require('./layer'); +var methods = require('methods'); +var mixin = require('utils-merge'); +var debug = require('debug')('express:router'); +var deprecate = require('depd')('express'); +var flatten = require('array-flatten'); +var parseUrl = require('parseurl'); +var setPrototypeOf = require('setprototypeof') + +/** + * Module variables. + * @private + */ + +var objectRegExp = /^\[object (\S+)\]$/; +var slice = Array.prototype.slice; +var toString = Object.prototype.toString; + +/** + * Initialize a new `Router` with the given `options`. + * + * @param {Object} [options] + * @return {Router} which is a callable function + * @public + */ + +var proto = module.exports = function(options) { + var opts = options || {}; + + function router(req, res, next) { + router.handle(req, res, next); + } + + // mixin Router class functions + setPrototypeOf(router, proto) + + router.params = {}; + router._params = []; + router.caseSensitive = opts.caseSensitive; + router.mergeParams = opts.mergeParams; + router.strict = opts.strict; + router.stack = []; + + return router; +}; + +/** + * Map the given param placeholder `name`(s) to the given callback. + * + * Parameter mapping is used to provide pre-conditions to routes + * which use normalized placeholders. For example a _:user_id_ parameter + * could automatically load a user's information from the database without + * any additional code, + * + * The callback uses the same signature as middleware, the only difference + * being that the value of the placeholder is passed, in this case the _id_ + * of the user. Once the `next()` function is invoked, just like middleware + * it will continue on to execute the route, or subsequent parameter functions. + * + * Just like in middleware, you must either respond to the request or call next + * to avoid stalling the request. + * + * app.param('user_id', function(req, res, next, id){ + * User.find(id, function(err, user){ + * if (err) { + * return next(err); + * } else if (!user) { + * return next(new Error('failed to load user')); + * } + * req.user = user; + * next(); + * }); + * }); + * + * @param {String} name + * @param {Function} fn + * @return {app} for chaining + * @public + */ + +proto.param = function param(name, fn) { + // param logic + if (typeof name === 'function') { + deprecate('router.param(fn): Refactor to use path params'); + this._params.push(name); + return; + } + + // apply param functions + var params = this._params; + var len = params.length; + var ret; + + if (name[0] === ':') { + deprecate('router.param(' + JSON.stringify(name) + ', fn): Use router.param(' + JSON.stringify(name.slice(1)) + ', fn) instead') + name = name.slice(1) + } + + for (var i = 0; i < len; ++i) { + if (ret = params[i](name, fn)) { + fn = ret; + } + } + + // ensure we end up with a + // middleware function + if ('function' !== typeof fn) { + throw new Error('invalid param() call for ' + name + ', got ' + fn); + } + + (this.params[name] = this.params[name] || []).push(fn); + return this; +}; + +/** + * Dispatch a req, res into the router. + * @private + */ + +proto.handle = function handle(req, res, out) { + var self = this; + + debug('dispatching %s %s', req.method, req.url); + + var idx = 0; + var protohost = getProtohost(req.url) || '' + var removed = ''; + var slashAdded = false; + var sync = 0 + var paramcalled = {}; + + // store options for OPTIONS request + // only used if OPTIONS request + var options = []; + + // middleware and routes + var stack = self.stack; + + // manage inter-router variables + var parentParams = req.params; + var parentUrl = req.baseUrl || ''; + var done = restore(out, req, 'baseUrl', 'next', 'params'); + + // setup next layer + req.next = next; + + // for options requests, respond with a default if nothing else responds + if (req.method === 'OPTIONS') { + done = wrap(done, function(old, err) { + if (err || options.length === 0) return old(err); + sendOptionsResponse(res, options, old); + }); + } + + // setup basic req values + req.baseUrl = parentUrl; + req.originalUrl = req.originalUrl || req.url; + + next(); + + function next(err) { + var layerError = err === 'route' + ? null + : err; + + // remove added slash + if (slashAdded) { + req.url = req.url.slice(1) + slashAdded = false; + } + + // restore altered req.url + if (removed.length !== 0) { + req.baseUrl = parentUrl; + req.url = protohost + removed + req.url.slice(protohost.length) + removed = ''; + } + + // signal to exit router + if (layerError === 'router') { + setImmediate(done, null) + return + } + + // no more matching layers + if (idx >= stack.length) { + setImmediate(done, layerError); + return; + } + + // max sync stack + if (++sync > 100) { + return setImmediate(next, err) + } + + // get pathname of request + var path = getPathname(req); + + if (path == null) { + return done(layerError); + } + + // find next matching layer + var layer; + var match; + var route; + + while (match !== true && idx < stack.length) { + layer = stack[idx++]; + match = matchLayer(layer, path); + route = layer.route; + + if (typeof match !== 'boolean') { + // hold on to layerError + layerError = layerError || match; + } + + if (match !== true) { + continue; + } + + if (!route) { + // process non-route handlers normally + continue; + } + + if (layerError) { + // routes do not match with a pending error + match = false; + continue; + } + + var method = req.method; + var has_method = route._handles_method(method); + + // build up automatic options response + if (!has_method && method === 'OPTIONS') { + appendMethods(options, route._options()); + } + + // don't even bother matching route + if (!has_method && method !== 'HEAD') { + match = false; + } + } + + // no match + if (match !== true) { + return done(layerError); + } + + // store route for dispatch on change + if (route) { + req.route = route; + } + + // Capture one-time layer values + req.params = self.mergeParams + ? mergeParams(layer.params, parentParams) + : layer.params; + var layerPath = layer.path; + + // this should be done for the layer + self.process_params(layer, paramcalled, req, res, function (err) { + if (err) { + next(layerError || err) + } else if (route) { + layer.handle_request(req, res, next) + } else { + trim_prefix(layer, layerError, layerPath, path) + } + + sync = 0 + }); + } + + function trim_prefix(layer, layerError, layerPath, path) { + if (layerPath.length !== 0) { + // Validate path is a prefix match + if (layerPath !== path.slice(0, layerPath.length)) { + next(layerError) + return + } + + // Validate path breaks on a path separator + var c = path[layerPath.length] + if (c && c !== '/' && c !== '.') return next(layerError) + + // Trim off the part of the url that matches the route + // middleware (.use stuff) needs to have the path stripped + debug('trim prefix (%s) from url %s', layerPath, req.url); + removed = layerPath; + req.url = protohost + req.url.slice(protohost.length + removed.length) + + // Ensure leading slash + if (!protohost && req.url[0] !== '/') { + req.url = '/' + req.url; + slashAdded = true; + } + + // Setup base URL (no trailing slash) + req.baseUrl = parentUrl + (removed[removed.length - 1] === '/' + ? removed.substring(0, removed.length - 1) + : removed); + } + + debug('%s %s : %s', layer.name, layerPath, req.originalUrl); + + if (layerError) { + layer.handle_error(layerError, req, res, next); + } else { + layer.handle_request(req, res, next); + } + } +}; + +/** + * Process any parameters for the layer. + * @private + */ + +proto.process_params = function process_params(layer, called, req, res, done) { + var params = this.params; + + // captured parameters from the layer, keys and values + var keys = layer.keys; + + // fast track + if (!keys || keys.length === 0) { + return done(); + } + + var i = 0; + var name; + var paramIndex = 0; + var key; + var paramVal; + var paramCallbacks; + var paramCalled; + + // process params in order + // param callbacks can be async + function param(err) { + if (err) { + return done(err); + } + + if (i >= keys.length ) { + return done(); + } + + paramIndex = 0; + key = keys[i++]; + name = key.name; + paramVal = req.params[name]; + paramCallbacks = params[name]; + paramCalled = called[name]; + + if (paramVal === undefined || !paramCallbacks) { + return param(); + } + + // param previously called with same value or error occurred + if (paramCalled && (paramCalled.match === paramVal + || (paramCalled.error && paramCalled.error !== 'route'))) { + // restore value + req.params[name] = paramCalled.value; + + // next param + return param(paramCalled.error); + } + + called[name] = paramCalled = { + error: null, + match: paramVal, + value: paramVal + }; + + paramCallback(); + } + + // single param callbacks + function paramCallback(err) { + var fn = paramCallbacks[paramIndex++]; + + // store updated value + paramCalled.value = req.params[key.name]; + + if (err) { + // store error + paramCalled.error = err; + param(err); + return; + } + + if (!fn) return param(); + + try { + fn(req, res, paramCallback, paramVal, key.name); + } catch (e) { + paramCallback(e); + } + } + + param(); +}; + +/** + * Use the given middleware function, with optional path, defaulting to "/". + * + * Use (like `.all`) will run for any http METHOD, but it will not add + * handlers for those methods so OPTIONS requests will not consider `.use` + * functions even if they could respond. + * + * The other difference is that _route_ path is stripped and not visible + * to the handler function. The main effect of this feature is that mounted + * handlers can operate without any code changes regardless of the "prefix" + * pathname. + * + * @public + */ + +proto.use = function use(fn) { + var offset = 0; + var path = '/'; + + // default path to '/' + // disambiguate router.use([fn]) + if (typeof fn !== 'function') { + var arg = fn; + + while (Array.isArray(arg) && arg.length !== 0) { + arg = arg[0]; + } + + // first arg is the path + if (typeof arg !== 'function') { + offset = 1; + path = fn; + } + } + + var callbacks = flatten(slice.call(arguments, offset)); + + if (callbacks.length === 0) { + throw new TypeError('Router.use() requires a middleware function') + } + + for (var i = 0; i < callbacks.length; i++) { + var fn = callbacks[i]; + + if (typeof fn !== 'function') { + throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn)) + } + + // add the middleware + debug('use %o %s', path, fn.name || '') + + var layer = new Layer(path, { + sensitive: this.caseSensitive, + strict: false, + end: false + }, fn); + + layer.route = undefined; + + this.stack.push(layer); + } + + return this; +}; + +/** + * Create a new Route for the given path. + * + * Each route contains a separate middleware stack and VERB handlers. + * + * See the Route api documentation for details on adding handlers + * and middleware to routes. + * + * @param {String} path + * @return {Route} + * @public + */ + +proto.route = function route(path) { + var route = new Route(path); + + var layer = new Layer(path, { + sensitive: this.caseSensitive, + strict: this.strict, + end: true + }, route.dispatch.bind(route)); + + layer.route = route; + + this.stack.push(layer); + return route; +}; + +// create Router#VERB functions +methods.concat('all').forEach(function(method){ + proto[method] = function(path){ + var route = this.route(path) + route[method].apply(route, slice.call(arguments, 1)); + return this; + }; +}); + +// append methods to a list of methods +function appendMethods(list, addition) { + for (var i = 0; i < addition.length; i++) { + var method = addition[i]; + if (list.indexOf(method) === -1) { + list.push(method); + } + } +} + +// get pathname of request +function getPathname(req) { + try { + return parseUrl(req).pathname; + } catch (err) { + return undefined; + } +} + +// Get get protocol + host for a URL +function getProtohost(url) { + if (typeof url !== 'string' || url.length === 0 || url[0] === '/') { + return undefined + } + + var searchIndex = url.indexOf('?') + var pathLength = searchIndex !== -1 + ? searchIndex + : url.length + var fqdnIndex = url.slice(0, pathLength).indexOf('://') + + return fqdnIndex !== -1 + ? url.substring(0, url.indexOf('/', 3 + fqdnIndex)) + : undefined +} + +// get type for error message +function gettype(obj) { + var type = typeof obj; + + if (type !== 'object') { + return type; + } + + // inspect [[Class]] for objects + return toString.call(obj) + .replace(objectRegExp, '$1'); +} + +/** + * Match path to a layer. + * + * @param {Layer} layer + * @param {string} path + * @private + */ + +function matchLayer(layer, path) { + try { + return layer.match(path); + } catch (err) { + return err; + } +} + +// merge params with parent params +function mergeParams(params, parent) { + if (typeof parent !== 'object' || !parent) { + return params; + } + + // make copy of parent for base + var obj = mixin({}, parent); + + // simple non-numeric merging + if (!(0 in params) || !(0 in parent)) { + return mixin(obj, params); + } + + var i = 0; + var o = 0; + + // determine numeric gaps + while (i in params) { + i++; + } + + while (o in parent) { + o++; + } + + // offset numeric indices in params before merge + for (i--; i >= 0; i--) { + params[i + o] = params[i]; + + // create holes for the merge when necessary + if (i < o) { + delete params[i]; + } + } + + return mixin(obj, params); +} + +// restore obj props after function +function restore(fn, obj) { + var props = new Array(arguments.length - 2); + var vals = new Array(arguments.length - 2); + + for (var i = 0; i < props.length; i++) { + props[i] = arguments[i + 2]; + vals[i] = obj[props[i]]; + } + + return function () { + // restore vals + for (var i = 0; i < props.length; i++) { + obj[props[i]] = vals[i]; + } + + return fn.apply(this, arguments); + }; +} + +// send an OPTIONS response +function sendOptionsResponse(res, options, next) { + try { + var body = options.join(','); + res.set('Allow', body); + res.send(body); + } catch (err) { + next(err); + } +} + +// wrap a function +function wrap(old, fn) { + return function proxy() { + var args = new Array(arguments.length + 1); + + args[0] = old; + for (var i = 0, len = arguments.length; i < len; i++) { + args[i + 1] = arguments[i]; + } + + fn.apply(this, args); + }; +} diff --git a/gun-server/node_modules/express/lib/router/layer.js b/gun-server/node_modules/express/lib/router/layer.js new file mode 100644 index 0000000..4dc8e86 --- /dev/null +++ b/gun-server/node_modules/express/lib/router/layer.js @@ -0,0 +1,181 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var pathRegexp = require('path-to-regexp'); +var debug = require('debug')('express:router:layer'); + +/** + * Module variables. + * @private + */ + +var hasOwnProperty = Object.prototype.hasOwnProperty; + +/** + * Module exports. + * @public + */ + +module.exports = Layer; + +function Layer(path, options, fn) { + if (!(this instanceof Layer)) { + return new Layer(path, options, fn); + } + + debug('new %o', path) + var opts = options || {}; + + this.handle = fn; + this.name = fn.name || ''; + this.params = undefined; + this.path = undefined; + this.regexp = pathRegexp(path, this.keys = [], opts); + + // set fast path flags + this.regexp.fast_star = path === '*' + this.regexp.fast_slash = path === '/' && opts.end === false +} + +/** + * Handle the error for the layer. + * + * @param {Error} error + * @param {Request} req + * @param {Response} res + * @param {function} next + * @api private + */ + +Layer.prototype.handle_error = function handle_error(error, req, res, next) { + var fn = this.handle; + + if (fn.length !== 4) { + // not a standard error handler + return next(error); + } + + try { + fn(error, req, res, next); + } catch (err) { + next(err); + } +}; + +/** + * Handle the request for the layer. + * + * @param {Request} req + * @param {Response} res + * @param {function} next + * @api private + */ + +Layer.prototype.handle_request = function handle(req, res, next) { + var fn = this.handle; + + if (fn.length > 3) { + // not a standard request handler + return next(); + } + + try { + fn(req, res, next); + } catch (err) { + next(err); + } +}; + +/** + * Check if this route matches `path`, if so + * populate `.params`. + * + * @param {String} path + * @return {Boolean} + * @api private + */ + +Layer.prototype.match = function match(path) { + var match + + if (path != null) { + // fast path non-ending match for / (any path matches) + if (this.regexp.fast_slash) { + this.params = {} + this.path = '' + return true + } + + // fast path for * (everything matched in a param) + if (this.regexp.fast_star) { + this.params = {'0': decode_param(path)} + this.path = path + return true + } + + // match the path + match = this.regexp.exec(path) + } + + if (!match) { + this.params = undefined; + this.path = undefined; + return false; + } + + // store values + this.params = {}; + this.path = match[0] + + var keys = this.keys; + var params = this.params; + + for (var i = 1; i < match.length; i++) { + var key = keys[i - 1]; + var prop = key.name; + var val = decode_param(match[i]) + + if (val !== undefined || !(hasOwnProperty.call(params, prop))) { + params[prop] = val; + } + } + + return true; +}; + +/** + * Decode param value. + * + * @param {string} val + * @return {string} + * @private + */ + +function decode_param(val) { + if (typeof val !== 'string' || val.length === 0) { + return val; + } + + try { + return decodeURIComponent(val); + } catch (err) { + if (err instanceof URIError) { + err.message = 'Failed to decode param \'' + val + '\''; + err.status = err.statusCode = 400; + } + + throw err; + } +} diff --git a/gun-server/node_modules/express/lib/router/route.js b/gun-server/node_modules/express/lib/router/route.js new file mode 100644 index 0000000..a65756d --- /dev/null +++ b/gun-server/node_modules/express/lib/router/route.js @@ -0,0 +1,230 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var debug = require('debug')('express:router:route'); +var flatten = require('array-flatten'); +var Layer = require('./layer'); +var methods = require('methods'); + +/** + * Module variables. + * @private + */ + +var slice = Array.prototype.slice; +var toString = Object.prototype.toString; + +/** + * Module exports. + * @public + */ + +module.exports = Route; + +/** + * Initialize `Route` with the given `path`, + * + * @param {String} path + * @public + */ + +function Route(path) { + this.path = path; + this.stack = []; + + debug('new %o', path) + + // route handlers for various http methods + this.methods = {}; +} + +/** + * Determine if the route handles a given method. + * @private + */ + +Route.prototype._handles_method = function _handles_method(method) { + if (this.methods._all) { + return true; + } + + // normalize name + var name = typeof method === 'string' + ? method.toLowerCase() + : method + + if (name === 'head' && !this.methods['head']) { + name = 'get'; + } + + return Boolean(this.methods[name]); +}; + +/** + * @return {Array} supported HTTP methods + * @private + */ + +Route.prototype._options = function _options() { + var methods = Object.keys(this.methods); + + // append automatic head + if (this.methods.get && !this.methods.head) { + methods.push('head'); + } + + for (var i = 0; i < methods.length; i++) { + // make upper case + methods[i] = methods[i].toUpperCase(); + } + + return methods; +}; + +/** + * dispatch req, res into this route + * @private + */ + +Route.prototype.dispatch = function dispatch(req, res, done) { + var idx = 0; + var stack = this.stack; + var sync = 0 + + if (stack.length === 0) { + return done(); + } + var method = typeof req.method === 'string' + ? req.method.toLowerCase() + : req.method + + if (method === 'head' && !this.methods['head']) { + method = 'get'; + } + + req.route = this; + + next(); + + function next(err) { + // signal to exit route + if (err && err === 'route') { + return done(); + } + + // signal to exit router + if (err && err === 'router') { + return done(err) + } + + // max sync stack + if (++sync > 100) { + return setImmediate(next, err) + } + + var layer = stack[idx++] + + // end of layers + if (!layer) { + return done(err) + } + + if (layer.method && layer.method !== method) { + next(err) + } else if (err) { + layer.handle_error(err, req, res, next); + } else { + layer.handle_request(req, res, next); + } + + sync = 0 + } +}; + +/** + * Add a handler for all HTTP verbs to this route. + * + * Behaves just like middleware and can respond or call `next` + * to continue processing. + * + * You can use multiple `.all` call to add multiple handlers. + * + * function check_something(req, res, next){ + * next(); + * }; + * + * function validate_user(req, res, next){ + * next(); + * }; + * + * route + * .all(validate_user) + * .all(check_something) + * .get(function(req, res, next){ + * res.send('hello world'); + * }); + * + * @param {function} handler + * @return {Route} for chaining + * @api public + */ + +Route.prototype.all = function all() { + var handles = flatten(slice.call(arguments)); + + for (var i = 0; i < handles.length; i++) { + var handle = handles[i]; + + if (typeof handle !== 'function') { + var type = toString.call(handle); + var msg = 'Route.all() requires a callback function but got a ' + type + throw new TypeError(msg); + } + + var layer = Layer('/', {}, handle); + layer.method = undefined; + + this.methods._all = true; + this.stack.push(layer); + } + + return this; +}; + +methods.forEach(function(method){ + Route.prototype[method] = function(){ + var handles = flatten(slice.call(arguments)); + + for (var i = 0; i < handles.length; i++) { + var handle = handles[i]; + + if (typeof handle !== 'function') { + var type = toString.call(handle); + var msg = 'Route.' + method + '() requires a callback function but got a ' + type + throw new Error(msg); + } + + debug('%s %o', method, this.path) + + var layer = Layer('/', {}, handle); + layer.method = method; + + this.methods[method] = true; + this.stack.push(layer); + } + + return this; + }; +}); diff --git a/gun-server/node_modules/express/lib/utils.js b/gun-server/node_modules/express/lib/utils.js new file mode 100644 index 0000000..56e12b9 --- /dev/null +++ b/gun-server/node_modules/express/lib/utils.js @@ -0,0 +1,303 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @api private + */ + +var Buffer = require('safe-buffer').Buffer +var contentDisposition = require('content-disposition'); +var contentType = require('content-type'); +var deprecate = require('depd')('express'); +var flatten = require('array-flatten'); +var mime = require('send').mime; +var etag = require('etag'); +var proxyaddr = require('proxy-addr'); +var qs = require('qs'); +var querystring = require('querystring'); + +/** + * Return strong ETag for `body`. + * + * @param {String|Buffer} body + * @param {String} [encoding] + * @return {String} + * @api private + */ + +exports.etag = createETagGenerator({ weak: false }) + +/** + * Return weak ETag for `body`. + * + * @param {String|Buffer} body + * @param {String} [encoding] + * @return {String} + * @api private + */ + +exports.wetag = createETagGenerator({ weak: true }) + +/** + * Check if `path` looks absolute. + * + * @param {String} path + * @return {Boolean} + * @api private + */ + +exports.isAbsolute = function(path){ + if ('/' === path[0]) return true; + if (':' === path[1] && ('\\' === path[2] || '/' === path[2])) return true; // Windows device path + if ('\\\\' === path.substring(0, 2)) return true; // Microsoft Azure absolute path +}; + +/** + * Flatten the given `arr`. + * + * @param {Array} arr + * @return {Array} + * @api private + */ + +exports.flatten = deprecate.function(flatten, + 'utils.flatten: use array-flatten npm module instead'); + +/** + * Normalize the given `type`, for example "html" becomes "text/html". + * + * @param {String} type + * @return {Object} + * @api private + */ + +exports.normalizeType = function(type){ + return ~type.indexOf('/') + ? acceptParams(type) + : { value: mime.lookup(type), params: {} }; +}; + +/** + * Normalize `types`, for example "html" becomes "text/html". + * + * @param {Array} types + * @return {Array} + * @api private + */ + +exports.normalizeTypes = function(types){ + var ret = []; + + for (var i = 0; i < types.length; ++i) { + ret.push(exports.normalizeType(types[i])); + } + + return ret; +}; + +/** + * Generate Content-Disposition header appropriate for the filename. + * non-ascii filenames are urlencoded and a filename* parameter is added + * + * @param {String} filename + * @return {String} + * @api private + */ + +exports.contentDisposition = deprecate.function(contentDisposition, + 'utils.contentDisposition: use content-disposition npm module instead'); + +/** + * Parse accept params `str` returning an + * object with `.value`, `.quality` and `.params`. + * + * @param {String} str + * @return {Object} + * @api private + */ + +function acceptParams (str) { + var parts = str.split(/ *; */); + var ret = { value: parts[0], quality: 1, params: {} } + + for (var i = 1; i < parts.length; ++i) { + var pms = parts[i].split(/ *= */); + if ('q' === pms[0]) { + ret.quality = parseFloat(pms[1]); + } else { + ret.params[pms[0]] = pms[1]; + } + } + + return ret; +} + +/** + * Compile "etag" value to function. + * + * @param {Boolean|String|Function} val + * @return {Function} + * @api private + */ + +exports.compileETag = function(val) { + var fn; + + if (typeof val === 'function') { + return val; + } + + switch (val) { + case true: + case 'weak': + fn = exports.wetag; + break; + case false: + break; + case 'strong': + fn = exports.etag; + break; + default: + throw new TypeError('unknown value for etag function: ' + val); + } + + return fn; +} + +/** + * Compile "query parser" value to function. + * + * @param {String|Function} val + * @return {Function} + * @api private + */ + +exports.compileQueryParser = function compileQueryParser(val) { + var fn; + + if (typeof val === 'function') { + return val; + } + + switch (val) { + case true: + case 'simple': + fn = querystring.parse; + break; + case false: + fn = newObject; + break; + case 'extended': + fn = parseExtendedQueryString; + break; + default: + throw new TypeError('unknown value for query parser function: ' + val); + } + + return fn; +} + +/** + * Compile "proxy trust" value to function. + * + * @param {Boolean|String|Number|Array|Function} val + * @return {Function} + * @api private + */ + +exports.compileTrust = function(val) { + if (typeof val === 'function') return val; + + if (val === true) { + // Support plain true/false + return function(){ return true }; + } + + if (typeof val === 'number') { + // Support trusting hop count + return function(a, i){ return i < val }; + } + + if (typeof val === 'string') { + // Support comma-separated values + val = val.split(',') + .map(function (v) { return v.trim() }) + } + + return proxyaddr.compile(val || []); +} + +/** + * Set the charset in a given Content-Type string. + * + * @param {String} type + * @param {String} charset + * @return {String} + * @api private + */ + +exports.setCharset = function setCharset(type, charset) { + if (!type || !charset) { + return type; + } + + // parse type + var parsed = contentType.parse(type); + + // set charset + parsed.parameters.charset = charset; + + // format type + return contentType.format(parsed); +}; + +/** + * Create an ETag generator function, generating ETags with + * the given options. + * + * @param {object} options + * @return {function} + * @private + */ + +function createETagGenerator (options) { + return function generateETag (body, encoding) { + var buf = !Buffer.isBuffer(body) + ? Buffer.from(body, encoding) + : body + + return etag(buf, options) + } +} + +/** + * Parse an extended query string with qs. + * + * @param {String} str + * @return {Object} + * @private + */ + +function parseExtendedQueryString(str) { + return qs.parse(str, { + allowPrototypes: true + }); +} + +/** + * Return new empty object. + * + * @return {Object} + * @api private + */ + +function newObject() { + return {}; +} diff --git a/gun-server/node_modules/express/lib/view.js b/gun-server/node_modules/express/lib/view.js new file mode 100644 index 0000000..c08ab4d --- /dev/null +++ b/gun-server/node_modules/express/lib/view.js @@ -0,0 +1,182 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var debug = require('debug')('express:view'); +var path = require('path'); +var fs = require('fs'); + +/** + * Module variables. + * @private + */ + +var dirname = path.dirname; +var basename = path.basename; +var extname = path.extname; +var join = path.join; +var resolve = path.resolve; + +/** + * Module exports. + * @public + */ + +module.exports = View; + +/** + * Initialize a new `View` with the given `name`. + * + * Options: + * + * - `defaultEngine` the default template engine name + * - `engines` template engine require() cache + * - `root` root path for view lookup + * + * @param {string} name + * @param {object} options + * @public + */ + +function View(name, options) { + var opts = options || {}; + + this.defaultEngine = opts.defaultEngine; + this.ext = extname(name); + this.name = name; + this.root = opts.root; + + if (!this.ext && !this.defaultEngine) { + throw new Error('No default engine was specified and no extension was provided.'); + } + + var fileName = name; + + if (!this.ext) { + // get extension from default engine name + this.ext = this.defaultEngine[0] !== '.' + ? '.' + this.defaultEngine + : this.defaultEngine; + + fileName += this.ext; + } + + if (!opts.engines[this.ext]) { + // load engine + var mod = this.ext.slice(1) + debug('require "%s"', mod) + + // default engine export + var fn = require(mod).__express + + if (typeof fn !== 'function') { + throw new Error('Module "' + mod + '" does not provide a view engine.') + } + + opts.engines[this.ext] = fn + } + + // store loaded engine + this.engine = opts.engines[this.ext]; + + // lookup path + this.path = this.lookup(fileName); +} + +/** + * Lookup view by the given `name` + * + * @param {string} name + * @private + */ + +View.prototype.lookup = function lookup(name) { + var path; + var roots = [].concat(this.root); + + debug('lookup "%s"', name); + + for (var i = 0; i < roots.length && !path; i++) { + var root = roots[i]; + + // resolve the path + var loc = resolve(root, name); + var dir = dirname(loc); + var file = basename(loc); + + // resolve the file + path = this.resolve(dir, file); + } + + return path; +}; + +/** + * Render with the given options. + * + * @param {object} options + * @param {function} callback + * @private + */ + +View.prototype.render = function render(options, callback) { + debug('render "%s"', this.path); + this.engine(this.path, options, callback); +}; + +/** + * Resolve the file within the given directory. + * + * @param {string} dir + * @param {string} file + * @private + */ + +View.prototype.resolve = function resolve(dir, file) { + var ext = this.ext; + + // . + var path = join(dir, file); + var stat = tryStat(path); + + if (stat && stat.isFile()) { + return path; + } + + // /index. + path = join(dir, basename(file, ext), 'index' + ext); + stat = tryStat(path); + + if (stat && stat.isFile()) { + return path; + } +}; + +/** + * Return a stat, maybe. + * + * @param {string} path + * @return {fs.Stats} + * @private + */ + +function tryStat(path) { + debug('stat "%s"', path); + + try { + return fs.statSync(path); + } catch (e) { + return undefined; + } +} diff --git a/gun-server/node_modules/express/package.json b/gun-server/node_modules/express/package.json new file mode 100644 index 0000000..f299d88 --- /dev/null +++ b/gun-server/node_modules/express/package.json @@ -0,0 +1,98 @@ +{ + "name": "express", + "description": "Fast, unopinionated, minimalist web framework", + "version": "4.19.2", + "author": "TJ Holowaychuk ", + "contributors": [ + "Aaron Heckmann ", + "Ciaran Jessup ", + "Douglas Christopher Wilson ", + "Guillermo Rauch ", + "Jonathan Ong ", + "Roman Shtylman ", + "Young Jae Sim " + ], + "license": "MIT", + "repository": "expressjs/express", + "homepage": "http://expressjs.com/", + "keywords": [ + "express", + "framework", + "sinatra", + "web", + "http", + "rest", + "restful", + "router", + "app", + "api" + ], + "dependencies": { + "accepts": "~1.3.8", + "array-flatten": "1.1.1", + "body-parser": "1.20.2", + "content-disposition": "0.5.4", + "content-type": "~1.0.4", + "cookie": "0.6.0", + "cookie-signature": "1.0.6", + "debug": "2.6.9", + "depd": "2.0.0", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "1.2.0", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "merge-descriptors": "1.0.1", + "methods": "~1.1.2", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "path-to-regexp": "0.1.7", + "proxy-addr": "~2.0.7", + "qs": "6.11.0", + "range-parser": "~1.2.1", + "safe-buffer": "5.2.1", + "send": "0.18.0", + "serve-static": "1.15.0", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "type-is": "~1.6.18", + "utils-merge": "1.0.1", + "vary": "~1.1.2" + }, + "devDependencies": { + "after": "0.8.2", + "connect-redis": "3.4.2", + "cookie-parser": "1.4.6", + "cookie-session": "2.0.0", + "ejs": "3.1.9", + "eslint": "8.47.0", + "express-session": "1.17.2", + "hbs": "4.2.0", + "marked": "0.7.0", + "method-override": "3.0.0", + "mocha": "10.2.0", + "morgan": "1.10.0", + "nyc": "15.1.0", + "pbkdf2-password": "1.2.1", + "supertest": "6.3.0", + "vhost": "~3.0.2" + }, + "engines": { + "node": ">= 0.10.0" + }, + "files": [ + "LICENSE", + "History.md", + "Readme.md", + "index.js", + "lib/" + ], + "scripts": { + "lint": "eslint .", + "test": "mocha --require test/support/env --reporter spec --bail --check-leaks test/ test/acceptance/", + "test-ci": "nyc --reporter=lcovonly --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "test-tap": "mocha --require test/support/env --reporter tap --check-leaks test/ test/acceptance/" + } +} diff --git a/gun-server/node_modules/finalhandler/HISTORY.md b/gun-server/node_modules/finalhandler/HISTORY.md new file mode 100644 index 0000000..ec2d38b --- /dev/null +++ b/gun-server/node_modules/finalhandler/HISTORY.md @@ -0,0 +1,195 @@ +1.2.0 / 2022-03-22 +================== + + * Remove set content headers that break response + * deps: on-finished@2.4.1 + * deps: statuses@2.0.1 + - Rename `425 Unordered Collection` to standard `425 Too Early` + +1.1.2 / 2019-05-09 +================== + + * Set stricter `Content-Security-Policy` header + * deps: parseurl@~1.3.3 + * deps: statuses@~1.5.0 + +1.1.1 / 2018-03-06 +================== + + * Fix 404 output for bad / missing pathnames + * deps: encodeurl@~1.0.2 + - Fix encoding `%` as last character + * deps: statuses@~1.4.0 + +1.1.0 / 2017-09-24 +================== + + * Use `res.headersSent` when available + +1.0.6 / 2017-09-22 +================== + + * deps: debug@2.6.9 + +1.0.5 / 2017-09-15 +================== + + * deps: parseurl@~1.3.2 + - perf: reduce overhead for full URLs + - perf: unroll the "fast-path" `RegExp` + +1.0.4 / 2017-08-03 +================== + + * deps: debug@2.6.8 + +1.0.3 / 2017-05-16 +================== + + * deps: debug@2.6.7 + - deps: ms@2.0.0 + +1.0.2 / 2017-04-22 +================== + + * deps: debug@2.6.4 + - deps: ms@0.7.3 + +1.0.1 / 2017-03-21 +================== + + * Fix missing `` in HTML document + * deps: debug@2.6.3 + - Fix: `DEBUG_MAX_ARRAY_LENGTH` + +1.0.0 / 2017-02-15 +================== + + * Fix exception when `err` cannot be converted to a string + * Fully URL-encode the pathname in the 404 message + * Only include the pathname in the 404 message + * Send complete HTML document + * Set `Content-Security-Policy: default-src 'self'` header + * deps: debug@2.6.1 + - Allow colors in workers + - Deprecated `DEBUG_FD` environment variable set to `3` or higher + - Fix error when running under React Native + - Use same color for same namespace + - deps: ms@0.7.2 + +0.5.1 / 2016-11-12 +================== + + * Fix exception when `err.headers` is not an object + * deps: statuses@~1.3.1 + * perf: hoist regular expressions + * perf: remove duplicate validation path + +0.5.0 / 2016-06-15 +================== + + * Change invalid or non-numeric status code to 500 + * Overwrite status message to match set status code + * Prefer `err.statusCode` if `err.status` is invalid + * Set response headers from `err.headers` object + * Use `statuses` instead of `http` module for status messages + - Includes all defined status messages + +0.4.1 / 2015-12-02 +================== + + * deps: escape-html@~1.0.3 + - perf: enable strict mode + - perf: optimize string replacement + - perf: use faster string coercion + +0.4.0 / 2015-06-14 +================== + + * Fix a false-positive when unpiping in Node.js 0.8 + * Support `statusCode` property on `Error` objects + * Use `unpipe` module for unpiping requests + * deps: escape-html@1.0.2 + * deps: on-finished@~2.3.0 + - Add defined behavior for HTTP `CONNECT` requests + - Add defined behavior for HTTP `Upgrade` requests + - deps: ee-first@1.1.1 + * perf: enable strict mode + * perf: remove argument reassignment + +0.3.6 / 2015-05-11 +================== + + * deps: debug@~2.2.0 + - deps: ms@0.7.1 + +0.3.5 / 2015-04-22 +================== + + * deps: on-finished@~2.2.1 + - Fix `isFinished(req)` when data buffered + +0.3.4 / 2015-03-15 +================== + + * deps: debug@~2.1.3 + - Fix high intensity foreground color for bold + - deps: ms@0.7.0 + +0.3.3 / 2015-01-01 +================== + + * deps: debug@~2.1.1 + * deps: on-finished@~2.2.0 + +0.3.2 / 2014-10-22 +================== + + * deps: on-finished@~2.1.1 + - Fix handling of pipelined requests + +0.3.1 / 2014-10-16 +================== + + * deps: debug@~2.1.0 + - Implement `DEBUG_FD` env variable support + +0.3.0 / 2014-09-17 +================== + + * Terminate in progress response only on error + * Use `on-finished` to determine request status + +0.2.0 / 2014-09-03 +================== + + * Set `X-Content-Type-Options: nosniff` header + * deps: debug@~2.0.0 + +0.1.0 / 2014-07-16 +================== + + * Respond after request fully read + - prevents hung responses and socket hang ups + * deps: debug@1.0.4 + +0.0.3 / 2014-07-11 +================== + + * deps: debug@1.0.3 + - Add support for multiple wildcards in namespaces + +0.0.2 / 2014-06-19 +================== + + * Handle invalid status codes + +0.0.1 / 2014-06-05 +================== + + * deps: debug@1.0.2 + +0.0.0 / 2014-06-05 +================== + + * Extracted from connect/express diff --git a/gun-server/node_modules/finalhandler/LICENSE b/gun-server/node_modules/finalhandler/LICENSE new file mode 100644 index 0000000..6022106 --- /dev/null +++ b/gun-server/node_modules/finalhandler/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014-2022 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/gun-server/node_modules/finalhandler/README.md b/gun-server/node_modules/finalhandler/README.md new file mode 100644 index 0000000..81f10ef --- /dev/null +++ b/gun-server/node_modules/finalhandler/README.md @@ -0,0 +1,147 @@ +# finalhandler + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][github-actions-ci-image]][github-actions-ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Node.js function to invoke as the final step to respond to HTTP request. + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install finalhandler +``` + +## API + +```js +var finalhandler = require('finalhandler') +``` + +### finalhandler(req, res, [options]) + +Returns function to be invoked as the final step for the given `req` and `res`. +This function is to be invoked as `fn(err)`. If `err` is falsy, the handler will +write out a 404 response to the `res`. If it is truthy, an error response will +be written out to the `res` or `res` will be terminated if a response has already +started. + +When an error is written, the following information is added to the response: + + * The `res.statusCode` is set from `err.status` (or `err.statusCode`). If + this value is outside the 4xx or 5xx range, it will be set to 500. + * The `res.statusMessage` is set according to the status code. + * The body will be the HTML of the status code message if `env` is + `'production'`, otherwise will be `err.stack`. + * Any headers specified in an `err.headers` object. + +The final handler will also unpipe anything from `req` when it is invoked. + +#### options.env + +By default, the environment is determined by `NODE_ENV` variable, but it can be +overridden by this option. + +#### options.onerror + +Provide a function to be called with the `err` when it exists. Can be used for +writing errors to a central location without excessive function generation. Called +as `onerror(err, req, res)`. + +## Examples + +### always 404 + +```js +var finalhandler = require('finalhandler') +var http = require('http') + +var server = http.createServer(function (req, res) { + var done = finalhandler(req, res) + done() +}) + +server.listen(3000) +``` + +### perform simple action + +```js +var finalhandler = require('finalhandler') +var fs = require('fs') +var http = require('http') + +var server = http.createServer(function (req, res) { + var done = finalhandler(req, res) + + fs.readFile('index.html', function (err, buf) { + if (err) return done(err) + res.setHeader('Content-Type', 'text/html') + res.end(buf) + }) +}) + +server.listen(3000) +``` + +### use with middleware-style functions + +```js +var finalhandler = require('finalhandler') +var http = require('http') +var serveStatic = require('serve-static') + +var serve = serveStatic('public') + +var server = http.createServer(function (req, res) { + var done = finalhandler(req, res) + serve(req, res, done) +}) + +server.listen(3000) +``` + +### keep log of all errors + +```js +var finalhandler = require('finalhandler') +var fs = require('fs') +var http = require('http') + +var server = http.createServer(function (req, res) { + var done = finalhandler(req, res, { onerror: logerror }) + + fs.readFile('index.html', function (err, buf) { + if (err) return done(err) + res.setHeader('Content-Type', 'text/html') + res.end(buf) + }) +}) + +server.listen(3000) + +function logerror (err) { + console.error(err.stack || err.toString()) +} +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/finalhandler.svg +[npm-url]: https://npmjs.org/package/finalhandler +[node-image]: https://img.shields.io/node/v/finalhandler.svg +[node-url]: https://nodejs.org/en/download +[coveralls-image]: https://img.shields.io/coveralls/pillarjs/finalhandler.svg +[coveralls-url]: https://coveralls.io/r/pillarjs/finalhandler?branch=master +[downloads-image]: https://img.shields.io/npm/dm/finalhandler.svg +[downloads-url]: https://npmjs.org/package/finalhandler +[github-actions-ci-image]: https://img.shields.io/github/workflow/status/pillarjs/finalhandler/ci/master?label=ci +[github-actions-ci-url]: https://github.com/jshttp/pillarjs/finalhandler?query=workflow%3Aci diff --git a/gun-server/node_modules/finalhandler/SECURITY.md b/gun-server/node_modules/finalhandler/SECURITY.md new file mode 100644 index 0000000..6e23249 --- /dev/null +++ b/gun-server/node_modules/finalhandler/SECURITY.md @@ -0,0 +1,25 @@ +# Security Policies and Procedures + +## Reporting a Bug + +The `finalhandler` team and community take all security bugs seriously. Thank +you for improving the security of Express. We appreciate your efforts and +responsible disclosure and will make every effort to acknowledge your +contributions. + +Report security bugs by emailing the current owner(s) of `finalhandler`. This +information can be found in the npm registry using the command +`npm owner ls finalhandler`. +If unsure or unable to get the information from the above, open an issue +in the [project issue tracker](https://github.com/pillarjs/finalhandler/issues) +asking for the current contact information. + +To ensure the timely response to your report, please ensure that the entirety +of the report is contained within the email body and not solely behind a web +link or an attachment. + +At least one owner will acknowledge your email within 48 hours, and will send a +more detailed response within 48 hours indicating the next steps in handling +your report. After the initial reply to your report, the owners will +endeavor to keep you informed of the progress towards a fix and full +announcement, and may ask for additional information or guidance. diff --git a/gun-server/node_modules/finalhandler/index.js b/gun-server/node_modules/finalhandler/index.js new file mode 100644 index 0000000..f628e42 --- /dev/null +++ b/gun-server/node_modules/finalhandler/index.js @@ -0,0 +1,336 @@ +/*! + * finalhandler + * Copyright(c) 2014-2022 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var debug = require('debug')('finalhandler') +var encodeUrl = require('encodeurl') +var escapeHtml = require('escape-html') +var onFinished = require('on-finished') +var parseUrl = require('parseurl') +var statuses = require('statuses') +var unpipe = require('unpipe') + +/** + * Module variables. + * @private + */ + +var DOUBLE_SPACE_REGEXP = /\x20{2}/g +var NEWLINE_REGEXP = /\n/g + +/* istanbul ignore next */ +var defer = typeof setImmediate === 'function' + ? setImmediate + : function (fn) { process.nextTick(fn.bind.apply(fn, arguments)) } +var isFinished = onFinished.isFinished + +/** + * Create a minimal HTML document. + * + * @param {string} message + * @private + */ + +function createHtmlDocument (message) { + var body = escapeHtml(message) + .replace(NEWLINE_REGEXP, '
      ') + .replace(DOUBLE_SPACE_REGEXP, '  ') + + return '\n' + + '\n' + + '\n' + + '\n' + + 'Error\n' + + '\n' + + '\n' + + '
      ' + body + '
      \n' + + '\n' + + '\n' +} + +/** + * Module exports. + * @public + */ + +module.exports = finalhandler + +/** + * Create a function to handle the final response. + * + * @param {Request} req + * @param {Response} res + * @param {Object} [options] + * @return {Function} + * @public + */ + +function finalhandler (req, res, options) { + var opts = options || {} + + // get environment + var env = opts.env || process.env.NODE_ENV || 'development' + + // get error callback + var onerror = opts.onerror + + return function (err) { + var headers + var msg + var status + + // ignore 404 on in-flight response + if (!err && headersSent(res)) { + debug('cannot 404 after headers sent') + return + } + + // unhandled error + if (err) { + // respect status code from error + status = getErrorStatusCode(err) + + if (status === undefined) { + // fallback to status code on response + status = getResponseStatusCode(res) + } else { + // respect headers from error + headers = getErrorHeaders(err) + } + + // get error message + msg = getErrorMessage(err, status, env) + } else { + // not found + status = 404 + msg = 'Cannot ' + req.method + ' ' + encodeUrl(getResourceName(req)) + } + + debug('default %s', status) + + // schedule onerror callback + if (err && onerror) { + defer(onerror, err, req, res) + } + + // cannot actually respond + if (headersSent(res)) { + debug('cannot %d after headers sent', status) + req.socket.destroy() + return + } + + // send response + send(req, res, status, headers, msg) + } +} + +/** + * Get headers from Error object. + * + * @param {Error} err + * @return {object} + * @private + */ + +function getErrorHeaders (err) { + if (!err.headers || typeof err.headers !== 'object') { + return undefined + } + + var headers = Object.create(null) + var keys = Object.keys(err.headers) + + for (var i = 0; i < keys.length; i++) { + var key = keys[i] + headers[key] = err.headers[key] + } + + return headers +} + +/** + * Get message from Error object, fallback to status message. + * + * @param {Error} err + * @param {number} status + * @param {string} env + * @return {string} + * @private + */ + +function getErrorMessage (err, status, env) { + var msg + + if (env !== 'production') { + // use err.stack, which typically includes err.message + msg = err.stack + + // fallback to err.toString() when possible + if (!msg && typeof err.toString === 'function') { + msg = err.toString() + } + } + + return msg || statuses.message[status] +} + +/** + * Get status code from Error object. + * + * @param {Error} err + * @return {number} + * @private + */ + +function getErrorStatusCode (err) { + // check err.status + if (typeof err.status === 'number' && err.status >= 400 && err.status < 600) { + return err.status + } + + // check err.statusCode + if (typeof err.statusCode === 'number' && err.statusCode >= 400 && err.statusCode < 600) { + return err.statusCode + } + + return undefined +} + +/** + * Get resource name for the request. + * + * This is typically just the original pathname of the request + * but will fallback to "resource" is that cannot be determined. + * + * @param {IncomingMessage} req + * @return {string} + * @private + */ + +function getResourceName (req) { + try { + return parseUrl.original(req).pathname + } catch (e) { + return 'resource' + } +} + +/** + * Get status code from response. + * + * @param {OutgoingMessage} res + * @return {number} + * @private + */ + +function getResponseStatusCode (res) { + var status = res.statusCode + + // default status code to 500 if outside valid range + if (typeof status !== 'number' || status < 400 || status > 599) { + status = 500 + } + + return status +} + +/** + * Determine if the response headers have been sent. + * + * @param {object} res + * @returns {boolean} + * @private + */ + +function headersSent (res) { + return typeof res.headersSent !== 'boolean' + ? Boolean(res._header) + : res.headersSent +} + +/** + * Send response. + * + * @param {IncomingMessage} req + * @param {OutgoingMessage} res + * @param {number} status + * @param {object} headers + * @param {string} message + * @private + */ + +function send (req, res, status, headers, message) { + function write () { + // response body + var body = createHtmlDocument(message) + + // response status + res.statusCode = status + res.statusMessage = statuses.message[status] + + // remove any content headers + res.removeHeader('Content-Encoding') + res.removeHeader('Content-Language') + res.removeHeader('Content-Range') + + // response headers + setHeaders(res, headers) + + // security headers + res.setHeader('Content-Security-Policy', "default-src 'none'") + res.setHeader('X-Content-Type-Options', 'nosniff') + + // standard headers + res.setHeader('Content-Type', 'text/html; charset=utf-8') + res.setHeader('Content-Length', Buffer.byteLength(body, 'utf8')) + + if (req.method === 'HEAD') { + res.end() + return + } + + res.end(body, 'utf8') + } + + if (isFinished(req)) { + write() + return + } + + // unpipe everything from the request + unpipe(req) + + // flush the request + onFinished(req, write) + req.resume() +} + +/** + * Set response headers from an object. + * + * @param {OutgoingMessage} res + * @param {object} headers + * @private + */ + +function setHeaders (res, headers) { + if (!headers) { + return + } + + var keys = Object.keys(headers) + for (var i = 0; i < keys.length; i++) { + var key = keys[i] + res.setHeader(key, headers[key]) + } +} diff --git a/gun-server/node_modules/finalhandler/package.json b/gun-server/node_modules/finalhandler/package.json new file mode 100644 index 0000000..16bf11e --- /dev/null +++ b/gun-server/node_modules/finalhandler/package.json @@ -0,0 +1,46 @@ +{ + "name": "finalhandler", + "description": "Node.js final http responder", + "version": "1.2.0", + "author": "Douglas Christopher Wilson ", + "license": "MIT", + "repository": "pillarjs/finalhandler", + "dependencies": { + "debug": "2.6.9", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "statuses": "2.0.1", + "unpipe": "~1.0.0" + }, + "devDependencies": { + "eslint": "7.32.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.25.4", + "eslint-plugin-markdown": "2.2.1", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "5.2.0", + "eslint-plugin-standard": "4.1.0", + "mocha": "9.2.2", + "nyc": "15.1.0", + "readable-stream": "2.3.6", + "safe-buffer": "5.2.1", + "supertest": "6.2.2" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "SECURITY.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-ci": "nyc --reporter=lcovonly --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + } +} diff --git a/gun-server/node_modules/forwarded/HISTORY.md b/gun-server/node_modules/forwarded/HISTORY.md new file mode 100644 index 0000000..381e6aa --- /dev/null +++ b/gun-server/node_modules/forwarded/HISTORY.md @@ -0,0 +1,21 @@ +0.2.0 / 2021-05-31 +================== + + * Use `req.socket` over deprecated `req.connection` + +0.1.2 / 2017-09-14 +================== + + * perf: improve header parsing + * perf: reduce overhead when no `X-Forwarded-For` header + +0.1.1 / 2017-09-10 +================== + + * Fix trimming leading / trailing OWS + * perf: hoist regular expression + +0.1.0 / 2014-09-21 +================== + + * Initial release diff --git a/gun-server/node_modules/forwarded/LICENSE b/gun-server/node_modules/forwarded/LICENSE new file mode 100644 index 0000000..84441fb --- /dev/null +++ b/gun-server/node_modules/forwarded/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014-2017 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/gun-server/node_modules/forwarded/README.md b/gun-server/node_modules/forwarded/README.md new file mode 100644 index 0000000..fdd220b --- /dev/null +++ b/gun-server/node_modules/forwarded/README.md @@ -0,0 +1,57 @@ +# forwarded + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][ci-image]][ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Parse HTTP X-Forwarded-For header + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install forwarded +``` + +## API + +```js +var forwarded = require('forwarded') +``` + +### forwarded(req) + +```js +var addresses = forwarded(req) +``` + +Parse the `X-Forwarded-For` header from the request. Returns an array +of the addresses, including the socket address for the `req`, in reverse +order (i.e. index `0` is the socket address and the last index is the +furthest address, typically the end-user). + +## Testing + +```sh +$ npm test +``` + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/jshttp/forwarded/master?label=ci +[ci-url]: https://github.com/jshttp/forwarded/actions?query=workflow%3Aci +[npm-image]: https://img.shields.io/npm/v/forwarded.svg +[npm-url]: https://npmjs.org/package/forwarded +[node-version-image]: https://img.shields.io/node/v/forwarded.svg +[node-version-url]: https://nodejs.org/en/download/ +[coveralls-image]: https://img.shields.io/coveralls/jshttp/forwarded/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/forwarded?branch=master +[downloads-image]: https://img.shields.io/npm/dm/forwarded.svg +[downloads-url]: https://npmjs.org/package/forwarded diff --git a/gun-server/node_modules/forwarded/index.js b/gun-server/node_modules/forwarded/index.js new file mode 100644 index 0000000..b2b6bdd --- /dev/null +++ b/gun-server/node_modules/forwarded/index.js @@ -0,0 +1,90 @@ +/*! + * forwarded + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = forwarded + +/** + * Get all addresses in the request, using the `X-Forwarded-For` header. + * + * @param {object} req + * @return {array} + * @public + */ + +function forwarded (req) { + if (!req) { + throw new TypeError('argument req is required') + } + + // simple header parsing + var proxyAddrs = parse(req.headers['x-forwarded-for'] || '') + var socketAddr = getSocketAddr(req) + var addrs = [socketAddr].concat(proxyAddrs) + + // return all addresses + return addrs +} + +/** + * Get the socket address for a request. + * + * @param {object} req + * @return {string} + * @private + */ + +function getSocketAddr (req) { + return req.socket + ? req.socket.remoteAddress + : req.connection.remoteAddress +} + +/** + * Parse the X-Forwarded-For header. + * + * @param {string} header + * @private + */ + +function parse (header) { + var end = header.length + var list = [] + var start = header.length + + // gather addresses, backwards + for (var i = header.length - 1; i >= 0; i--) { + switch (header.charCodeAt(i)) { + case 0x20: /* */ + if (start === end) { + start = end = i + } + break + case 0x2c: /* , */ + if (start !== end) { + list.push(header.substring(start, end)) + } + start = end = i + break + default: + start = i + break + } + } + + // final address + if (start !== end) { + list.push(header.substring(start, end)) + } + + return list +} diff --git a/gun-server/node_modules/forwarded/package.json b/gun-server/node_modules/forwarded/package.json new file mode 100644 index 0000000..bf9c7d6 --- /dev/null +++ b/gun-server/node_modules/forwarded/package.json @@ -0,0 +1,45 @@ +{ + "name": "forwarded", + "description": "Parse HTTP X-Forwarded-For header", + "version": "0.2.0", + "contributors": [ + "Douglas Christopher Wilson " + ], + "license": "MIT", + "keywords": [ + "x-forwarded-for", + "http", + "req" + ], + "repository": "jshttp/forwarded", + "devDependencies": { + "beautify-benchmark": "0.2.4", + "benchmark": "2.1.4", + "deep-equal": "1.0.1", + "eslint": "7.27.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.23.4", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "4.3.1", + "eslint-plugin-standard": "4.1.0", + "mocha": "8.4.0", + "nyc": "15.1.0" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "bench": "node benchmark/index.js", + "lint": "eslint .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "version": "node scripts/version-history.js && git add HISTORY.md" + } +} diff --git a/gun-server/node_modules/fresh/HISTORY.md b/gun-server/node_modules/fresh/HISTORY.md new file mode 100644 index 0000000..4586996 --- /dev/null +++ b/gun-server/node_modules/fresh/HISTORY.md @@ -0,0 +1,70 @@ +0.5.2 / 2017-09-13 +================== + + * Fix regression matching multiple ETags in `If-None-Match` + * perf: improve `If-None-Match` token parsing + +0.5.1 / 2017-09-11 +================== + + * Fix handling of modified headers with invalid dates + * perf: improve ETag match loop + +0.5.0 / 2017-02-21 +================== + + * Fix incorrect result when `If-None-Match` has both `*` and ETags + * Fix weak `ETag` matching to match spec + * perf: delay reading header values until needed + * perf: skip checking modified time if ETag check failed + * perf: skip parsing `If-None-Match` when no `ETag` header + * perf: use `Date.parse` instead of `new Date` + +0.4.0 / 2017-02-05 +================== + + * Fix false detection of `no-cache` request directive + * perf: enable strict mode + * perf: hoist regular expressions + * perf: remove duplicate conditional + * perf: remove unnecessary boolean coercions + +0.3.0 / 2015-05-12 +================== + + * Add weak `ETag` matching support + +0.2.4 / 2014-09-07 +================== + + * Support Node.js 0.6 + +0.2.3 / 2014-09-07 +================== + + * Move repository to jshttp + +0.2.2 / 2014-02-19 +================== + + * Revert "Fix for blank page on Safari reload" + +0.2.1 / 2014-01-29 +================== + + * Fix for blank page on Safari reload + +0.2.0 / 2013-08-11 +================== + + * Return stale for `Cache-Control: no-cache` + +0.1.0 / 2012-06-15 +================== + + * Add `If-None-Match: *` support + +0.0.1 / 2012-06-10 +================== + + * Initial release diff --git a/gun-server/node_modules/fresh/LICENSE b/gun-server/node_modules/fresh/LICENSE new file mode 100644 index 0000000..1434ade --- /dev/null +++ b/gun-server/node_modules/fresh/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2012 TJ Holowaychuk +Copyright (c) 2016-2017 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/gun-server/node_modules/fresh/README.md b/gun-server/node_modules/fresh/README.md new file mode 100644 index 0000000..1c1c680 --- /dev/null +++ b/gun-server/node_modules/fresh/README.md @@ -0,0 +1,119 @@ +# fresh + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +HTTP response freshness testing + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +``` +$ npm install fresh +``` + +## API + + + +```js +var fresh = require('fresh') +``` + +### fresh(reqHeaders, resHeaders) + +Check freshness of the response using request and response headers. + +When the response is still "fresh" in the client's cache `true` is +returned, otherwise `false` is returned to indicate that the client +cache is now stale and the full response should be sent. + +When a client sends the `Cache-Control: no-cache` request header to +indicate an end-to-end reload request, this module will return `false` +to make handling these requests transparent. + +## Known Issues + +This module is designed to only follow the HTTP specifications, not +to work-around all kinda of client bugs (especially since this module +typically does not recieve enough information to understand what the +client actually is). + +There is a known issue that in certain versions of Safari, Safari +will incorrectly make a request that allows this module to validate +freshness of the resource even when Safari does not have a +representation of the resource in the cache. The module +[jumanji](https://www.npmjs.com/package/jumanji) can be used in +an Express application to work-around this issue and also provides +links to further reading on this Safari bug. + +## Example + +### API usage + + + +```js +var reqHeaders = { 'if-none-match': '"foo"' } +var resHeaders = { 'etag': '"bar"' } +fresh(reqHeaders, resHeaders) +// => false + +var reqHeaders = { 'if-none-match': '"foo"' } +var resHeaders = { 'etag': '"foo"' } +fresh(reqHeaders, resHeaders) +// => true +``` + +### Using with Node.js http server + +```js +var fresh = require('fresh') +var http = require('http') + +var server = http.createServer(function (req, res) { + // perform server logic + // ... including adding ETag / Last-Modified response headers + + if (isFresh(req, res)) { + // client has a fresh copy of resource + res.statusCode = 304 + res.end() + return + } + + // send the resource + res.statusCode = 200 + res.end('hello, world!') +}) + +function isFresh (req, res) { + return fresh(req.headers, { + 'etag': res.getHeader('ETag'), + 'last-modified': res.getHeader('Last-Modified') + }) +} + +server.listen(3000) +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/fresh.svg +[npm-url]: https://npmjs.org/package/fresh +[node-version-image]: https://img.shields.io/node/v/fresh.svg +[node-version-url]: https://nodejs.org/en/ +[travis-image]: https://img.shields.io/travis/jshttp/fresh/master.svg +[travis-url]: https://travis-ci.org/jshttp/fresh +[coveralls-image]: https://img.shields.io/coveralls/jshttp/fresh/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/fresh?branch=master +[downloads-image]: https://img.shields.io/npm/dm/fresh.svg +[downloads-url]: https://npmjs.org/package/fresh diff --git a/gun-server/node_modules/fresh/index.js b/gun-server/node_modules/fresh/index.js new file mode 100644 index 0000000..d154f5a --- /dev/null +++ b/gun-server/node_modules/fresh/index.js @@ -0,0 +1,137 @@ +/*! + * fresh + * Copyright(c) 2012 TJ Holowaychuk + * Copyright(c) 2016-2017 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * RegExp to check for no-cache token in Cache-Control. + * @private + */ + +var CACHE_CONTROL_NO_CACHE_REGEXP = /(?:^|,)\s*?no-cache\s*?(?:,|$)/ + +/** + * Module exports. + * @public + */ + +module.exports = fresh + +/** + * Check freshness of the response using request and response headers. + * + * @param {Object} reqHeaders + * @param {Object} resHeaders + * @return {Boolean} + * @public + */ + +function fresh (reqHeaders, resHeaders) { + // fields + var modifiedSince = reqHeaders['if-modified-since'] + var noneMatch = reqHeaders['if-none-match'] + + // unconditional request + if (!modifiedSince && !noneMatch) { + return false + } + + // Always return stale when Cache-Control: no-cache + // to support end-to-end reload requests + // https://tools.ietf.org/html/rfc2616#section-14.9.4 + var cacheControl = reqHeaders['cache-control'] + if (cacheControl && CACHE_CONTROL_NO_CACHE_REGEXP.test(cacheControl)) { + return false + } + + // if-none-match + if (noneMatch && noneMatch !== '*') { + var etag = resHeaders['etag'] + + if (!etag) { + return false + } + + var etagStale = true + var matches = parseTokenList(noneMatch) + for (var i = 0; i < matches.length; i++) { + var match = matches[i] + if (match === etag || match === 'W/' + etag || 'W/' + match === etag) { + etagStale = false + break + } + } + + if (etagStale) { + return false + } + } + + // if-modified-since + if (modifiedSince) { + var lastModified = resHeaders['last-modified'] + var modifiedStale = !lastModified || !(parseHttpDate(lastModified) <= parseHttpDate(modifiedSince)) + + if (modifiedStale) { + return false + } + } + + return true +} + +/** + * Parse an HTTP Date into a number. + * + * @param {string} date + * @private + */ + +function parseHttpDate (date) { + var timestamp = date && Date.parse(date) + + // istanbul ignore next: guard against date.js Date.parse patching + return typeof timestamp === 'number' + ? timestamp + : NaN +} + +/** + * Parse a HTTP token list. + * + * @param {string} str + * @private + */ + +function parseTokenList (str) { + var end = 0 + var list = [] + var start = 0 + + // gather tokens + for (var i = 0, len = str.length; i < len; i++) { + switch (str.charCodeAt(i)) { + case 0x20: /* */ + if (start === end) { + start = end = i + 1 + } + break + case 0x2c: /* , */ + list.push(str.substring(start, end)) + start = end = i + 1 + break + default: + end = i + 1 + break + } + } + + // final token + list.push(str.substring(start, end)) + + return list +} diff --git a/gun-server/node_modules/fresh/package.json b/gun-server/node_modules/fresh/package.json new file mode 100644 index 0000000..c2fa0f4 --- /dev/null +++ b/gun-server/node_modules/fresh/package.json @@ -0,0 +1,46 @@ +{ + "name": "fresh", + "description": "HTTP response freshness testing", + "version": "0.5.2", + "author": "TJ Holowaychuk (http://tjholowaychuk.com)", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)" + ], + "license": "MIT", + "keywords": [ + "fresh", + "http", + "conditional", + "cache" + ], + "repository": "jshttp/fresh", + "devDependencies": { + "beautify-benchmark": "0.2.4", + "benchmark": "2.1.4", + "eslint": "3.19.0", + "eslint-config-standard": "10.2.1", + "eslint-plugin-import": "2.7.0", + "eslint-plugin-markdown": "1.0.0-beta.6", + "eslint-plugin-node": "5.1.1", + "eslint-plugin-promise": "3.5.0", + "eslint-plugin-standard": "3.0.1", + "istanbul": "0.4.5", + "mocha": "1.21.5" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "bench": "node benchmark/index.js", + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + } +} diff --git a/gun-server/node_modules/function-bind/.eslintrc b/gun-server/node_modules/function-bind/.eslintrc new file mode 100644 index 0000000..71a054f --- /dev/null +++ b/gun-server/node_modules/function-bind/.eslintrc @@ -0,0 +1,21 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "func-name-matching": 0, + "indent": [2, 4], + "no-new-func": [1], + }, + + "overrides": [ + { + "files": "test/**", + "rules": { + "max-lines-per-function": 0, + "strict": [0] + }, + }, + ], +} diff --git a/gun-server/node_modules/function-bind/.github/FUNDING.yml b/gun-server/node_modules/function-bind/.github/FUNDING.yml new file mode 100644 index 0000000..7448219 --- /dev/null +++ b/gun-server/node_modules/function-bind/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/function-bind +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/gun-server/node_modules/function-bind/.github/SECURITY.md b/gun-server/node_modules/function-bind/.github/SECURITY.md new file mode 100644 index 0000000..82e4285 --- /dev/null +++ b/gun-server/node_modules/function-bind/.github/SECURITY.md @@ -0,0 +1,3 @@ +# Security + +Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report. diff --git a/gun-server/node_modules/function-bind/.nycrc b/gun-server/node_modules/function-bind/.nycrc new file mode 100644 index 0000000..1826526 --- /dev/null +++ b/gun-server/node_modules/function-bind/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/gun-server/node_modules/function-bind/CHANGELOG.md b/gun-server/node_modules/function-bind/CHANGELOG.md new file mode 100644 index 0000000..f9e6cc0 --- /dev/null +++ b/gun-server/node_modules/function-bind/CHANGELOG.md @@ -0,0 +1,136 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.1.2](https://github.com/ljharb/function-bind/compare/v1.1.1...v1.1.2) - 2023-10-12 + +### Merged + +- Point to the correct file [`#16`](https://github.com/ljharb/function-bind/pull/16) + +### Commits + +- [Tests] migrate tests to Github Actions [`4f8b57c`](https://github.com/ljharb/function-bind/commit/4f8b57c02f2011fe9ae353d5e74e8745f0988af8) +- [Tests] remove `jscs` [`90eb2ed`](https://github.com/ljharb/function-bind/commit/90eb2edbeefd5b76cd6c3a482ea3454db169b31f) +- [meta] update `.gitignore` [`53fcdc3`](https://github.com/ljharb/function-bind/commit/53fcdc371cd66634d6e9b71c836a50f437e89fed) +- [Tests] up to `node` `v11.10`, `v10.15`, `v9.11`, `v8.15`, `v6.16`, `v4.9`; use `nvm install-latest-npm`; run audit script in tests [`1fe8f6e`](https://github.com/ljharb/function-bind/commit/1fe8f6e9aed0dfa8d8b3cdbd00c7f5ea0cd2b36e) +- [meta] add `auto-changelog` [`1921fcb`](https://github.com/ljharb/function-bind/commit/1921fcb5b416b63ffc4acad051b6aad5722f777d) +- [Robustness] remove runtime dependency on all builtins except `.apply` [`f743e61`](https://github.com/ljharb/function-bind/commit/f743e61aa6bb2360358c04d4884c9db853d118b7) +- Docs: enable badges; update wording [`503cb12`](https://github.com/ljharb/function-bind/commit/503cb12d998b5f91822776c73332c7adcd6355dd) +- [readme] update badges [`290c5db`](https://github.com/ljharb/function-bind/commit/290c5dbbbda7264efaeb886552a374b869a4bb48) +- [Tests] switch to nyc for coverage [`ea360ba`](https://github.com/ljharb/function-bind/commit/ea360ba907fc2601ed18d01a3827fa2d3533cdf8) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`cae5e9e`](https://github.com/ljharb/function-bind/commit/cae5e9e07a5578dc6df26c03ee22851ce05b943c) +- [meta] add `funding` field; create FUNDING.yml [`c9f4274`](https://github.com/ljharb/function-bind/commit/c9f4274aa80ea3aae9657a3938fdba41a3b04ca6) +- [Tests] fix eslint errors from #15 [`f69aaa2`](https://github.com/ljharb/function-bind/commit/f69aaa2beb2fdab4415bfb885760a699d0b9c964) +- [actions] fix permissions [`99a0cd9`](https://github.com/ljharb/function-bind/commit/99a0cd9f3b5bac223a0d572f081834cd73314be7) +- [meta] use `npmignore` to autogenerate an npmignore file [`f03b524`](https://github.com/ljharb/function-bind/commit/f03b524ca91f75a109a5d062f029122c86ecd1ae) +- [Dev Deps] update `@ljharb/eslint‑config`, `eslint`, `tape` [`7af9300`](https://github.com/ljharb/function-bind/commit/7af930023ae2ce7645489532821e4fbbcd7a2280) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `covert`, `tape` [`64a9127`](https://github.com/ljharb/function-bind/commit/64a9127ab0bd331b93d6572eaf6e9971967fc08c) +- [Tests] use `aud` instead of `npm audit` [`e75069c`](https://github.com/ljharb/function-bind/commit/e75069c50010a8fcce2a9ce2324934c35fdb4386) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `tape` [`d03555c`](https://github.com/ljharb/function-bind/commit/d03555ca59dea3b71ce710045e4303b9e2619e28) +- [meta] add `safe-publish-latest` [`9c8f809`](https://github.com/ljharb/function-bind/commit/9c8f8092aed027d7e80c94f517aa892385b64f09) +- [Dev Deps] update `@ljharb/eslint-config`, `tape` [`baf6893`](https://github.com/ljharb/function-bind/commit/baf6893e27f5b59abe88bc1995e6f6ed1e527397) +- [meta] create SECURITY.md [`4db1779`](https://github.com/ljharb/function-bind/commit/4db17799f1f28ae294cb95e0081ca2b591c3911b) +- [Tests] add `npm run audit` [`c8b38ec`](https://github.com/ljharb/function-bind/commit/c8b38ec40ed3f85dabdee40ed4148f1748375bc2) +- Revert "Point to the correct file" [`05cdf0f`](https://github.com/ljharb/function-bind/commit/05cdf0fa205c6a3c5ba40bbedd1dfa9874f915c9) + +## [v1.1.1](https://github.com/ljharb/function-bind/compare/v1.1.0...v1.1.1) - 2017-08-28 + +### Commits + +- [Tests] up to `node` `v8`; newer npm breaks on older node; fix scripts [`817f7d2`](https://github.com/ljharb/function-bind/commit/817f7d28470fdbff8ef608d4d565dd4d1430bc5e) +- [Dev Deps] update `eslint`, `jscs`, `tape`, `@ljharb/eslint-config` [`854288b`](https://github.com/ljharb/function-bind/commit/854288b1b6f5c555f89aceb9eff1152510262084) +- [Dev Deps] update `tape`, `jscs`, `eslint`, `@ljharb/eslint-config` [`83e639f`](https://github.com/ljharb/function-bind/commit/83e639ff74e6cd6921285bccec22c1bcf72311bd) +- Only apps should have lockfiles [`5ed97f5`](https://github.com/ljharb/function-bind/commit/5ed97f51235c17774e0832e122abda0f3229c908) +- Use a SPDX-compliant “license†field. [`5feefea`](https://github.com/ljharb/function-bind/commit/5feefea0dc0193993e83e5df01ded424403a5381) + +## [v1.1.0](https://github.com/ljharb/function-bind/compare/v1.0.2...v1.1.0) - 2016-02-14 + +### Commits + +- Update `eslint`, `tape`; use my personal shared `eslint` config [`9c9062a`](https://github.com/ljharb/function-bind/commit/9c9062abbe9dd70b59ea2c3a3c3a81f29b457097) +- Add `npm run eslint` [`dd96c56`](https://github.com/ljharb/function-bind/commit/dd96c56720034a3c1ffee10b8a59a6f7c53e24ad) +- [New] return the native `bind` when available. [`82186e0`](https://github.com/ljharb/function-bind/commit/82186e03d73e580f95ff167e03f3582bed90ed72) +- [Dev Deps] update `tape`, `jscs`, `eslint`, `@ljharb/eslint-config` [`a3dd767`](https://github.com/ljharb/function-bind/commit/a3dd76720c795cb7f4586b0544efabf8aa107b8b) +- Update `eslint` [`3dae2f7`](https://github.com/ljharb/function-bind/commit/3dae2f7423de30a2d20313ddb1edc19660142fe9) +- Update `tape`, `covert`, `jscs` [`a181eee`](https://github.com/ljharb/function-bind/commit/a181eee0cfa24eb229c6e843a971f36e060a2f6a) +- [Tests] up to `node` `v5.6`, `v4.3` [`964929a`](https://github.com/ljharb/function-bind/commit/964929a6a4ddb36fb128de2bcc20af5e4f22e1ed) +- Test up to `io.js` `v2.1` [`2be7310`](https://github.com/ljharb/function-bind/commit/2be7310f2f74886a7124ca925be411117d41d5ea) +- Update `tape`, `jscs`, `eslint`, `@ljharb/eslint-config` [`45f3d68`](https://github.com/ljharb/function-bind/commit/45f3d6865c6ca93726abcef54febe009087af101) +- [Dev Deps] update `tape`, `jscs` [`6e1340d`](https://github.com/ljharb/function-bind/commit/6e1340d94642deaecad3e717825db641af4f8b1f) +- [Tests] up to `io.js` `v3.3`, `node` `v4.1` [`d9bad2b`](https://github.com/ljharb/function-bind/commit/d9bad2b778b1b3a6dd2876087b88b3acf319f8cc) +- Update `eslint` [`935590c`](https://github.com/ljharb/function-bind/commit/935590caa024ab356102e4858e8fc315b2ccc446) +- [Dev Deps] update `jscs`, `eslint`, `@ljharb/eslint-config` [`8c9a1ef`](https://github.com/ljharb/function-bind/commit/8c9a1efd848e5167887aa8501857a0940a480c57) +- Test on `io.js` `v2.2` [`9a3a38c`](https://github.com/ljharb/function-bind/commit/9a3a38c92013aed6e108666e7bd40969b84ac86e) +- Run `travis-ci` tests on `iojs` and `node` v0.12; speed up builds; allow 0.8 failures. [`69afc26`](https://github.com/ljharb/function-bind/commit/69afc2617405b147dd2a8d8ae73ca9e9283f18b4) +- [Dev Deps] Update `tape`, `eslint` [`36c1be0`](https://github.com/ljharb/function-bind/commit/36c1be0ab12b45fe5df6b0fdb01a5d5137fd0115) +- Update `tape`, `jscs` [`98d8303`](https://github.com/ljharb/function-bind/commit/98d8303cd5ca1c6b8f985469f86b0d44d7d45f6e) +- Update `jscs` [`9633a4e`](https://github.com/ljharb/function-bind/commit/9633a4e9fbf82051c240855166e468ba8ba0846f) +- Update `tape`, `jscs` [`c80ef0f`](https://github.com/ljharb/function-bind/commit/c80ef0f46efc9791e76fa50de4414092ac147831) +- Test up to `io.js` `v3.0` [`7e2c853`](https://github.com/ljharb/function-bind/commit/7e2c8537d52ab9cf5a655755561d8917684c0df4) +- Test on `io.js` `v2.4` [`5a199a2`](https://github.com/ljharb/function-bind/commit/5a199a27ba46795ba5eaf0845d07d4b8232895c9) +- Test on `io.js` `v2.3` [`a511b88`](https://github.com/ljharb/function-bind/commit/a511b8896de0bddf3b56862daa416c701f4d0453) +- Fixing a typo from 822b4e1938db02dc9584aa434fd3a45cb20caf43 [`732d6b6`](https://github.com/ljharb/function-bind/commit/732d6b63a9b33b45230e630dbcac7a10855d3266) +- Update `jscs` [`da52a48`](https://github.com/ljharb/function-bind/commit/da52a4886c06d6490f46ae30b15e4163ba08905d) +- Lock covert to v1.0.0. [`d6150fd`](https://github.com/ljharb/function-bind/commit/d6150fda1e6f486718ebdeff823333d9e48e7430) + +## [v1.0.2](https://github.com/ljharb/function-bind/compare/v1.0.1...v1.0.2) - 2014-10-04 + +## [v1.0.1](https://github.com/ljharb/function-bind/compare/v1.0.0...v1.0.1) - 2014-10-03 + +### Merged + +- make CI build faster [`#3`](https://github.com/ljharb/function-bind/pull/3) + +### Commits + +- Using my standard jscs.json [`d8ee94c`](https://github.com/ljharb/function-bind/commit/d8ee94c993eff0a84cf5744fe6a29627f5cffa1a) +- Adding `npm run lint` [`7571ab7`](https://github.com/ljharb/function-bind/commit/7571ab7dfdbd99b25a1dbb2d232622bd6f4f9c10) +- Using consistent indentation [`e91a1b1`](https://github.com/ljharb/function-bind/commit/e91a1b13a61e99ec1e530e299b55508f74218a95) +- Updating jscs [`7e17892`](https://github.com/ljharb/function-bind/commit/7e1789284bc629bc9c1547a61c9b227bbd8c7a65) +- Using consistent quotes [`c50b57f`](https://github.com/ljharb/function-bind/commit/c50b57fcd1c5ec38320979c837006069ebe02b77) +- Adding keywords [`cb94631`](https://github.com/ljharb/function-bind/commit/cb946314eed35f21186a25fb42fc118772f9ee00) +- Directly export a function expression instead of using a declaration, and relying on hoisting. [`5a33c5f`](https://github.com/ljharb/function-bind/commit/5a33c5f45642de180e0d207110bf7d1843ceb87c) +- Naming npm URL and badge in README; use SVG [`2aef8fc`](https://github.com/ljharb/function-bind/commit/2aef8fcb79d54e63a58ae557c4e60949e05d5e16) +- Naming deps URLs in README [`04228d7`](https://github.com/ljharb/function-bind/commit/04228d766670ee45ca24e98345c1f6a7621065b5) +- Naming travis-ci URLs in README; using SVG [`62c810c`](https://github.com/ljharb/function-bind/commit/62c810c2f54ced956cd4d4ab7b793055addfe36e) +- Make sure functions are invoked correctly (also passing coverage tests) [`2b289b4`](https://github.com/ljharb/function-bind/commit/2b289b4dfbf037ffcfa4dc95eb540f6165e9e43a) +- Removing the strict mode pragmas; they make tests fail. [`1aa701d`](https://github.com/ljharb/function-bind/commit/1aa701d199ddc3782476e8f7eef82679be97b845) +- Adding myself as a contributor [`85fd57b`](https://github.com/ljharb/function-bind/commit/85fd57b0860e5a7af42de9a287f3f265fc6d72fc) +- Adding strict mode pragmas [`915b08e`](https://github.com/ljharb/function-bind/commit/915b08e084c86a722eafe7245e21db74aa21ca4c) +- Adding devDeps URLs to README [`4ccc731`](https://github.com/ljharb/function-bind/commit/4ccc73112c1769859e4ca3076caf4086b3cba2cd) +- Fixing the description. [`a7a472c`](https://github.com/ljharb/function-bind/commit/a7a472cf649af515c635cf560fc478fbe48999c8) +- Using a function expression instead of a function declaration. [`b5d3e4e`](https://github.com/ljharb/function-bind/commit/b5d3e4ea6aaffc63888953eeb1fbc7ff45f1fa14) +- Updating tape [`f086be6`](https://github.com/ljharb/function-bind/commit/f086be6029fb56dde61a258c1340600fa174d1e0) +- Updating jscs [`5f9bdb3`](https://github.com/ljharb/function-bind/commit/5f9bdb375ab13ba48f30852aab94029520c54d71) +- Updating jscs [`9b409ba`](https://github.com/ljharb/function-bind/commit/9b409ba6118e23395a4e5d83ef39152aab9d3bfc) +- Run coverage as part of tests. [`8e1b6d4`](https://github.com/ljharb/function-bind/commit/8e1b6d459f047d1bd4fee814e01247c984c80bd0) +- Run linter as part of tests [`c1ca83f`](https://github.com/ljharb/function-bind/commit/c1ca83f832df94587d09e621beba682fabfaa987) +- Updating covert [`701e837`](https://github.com/ljharb/function-bind/commit/701e83774b57b4d3ef631e1948143f43a72f4bb9) + +## [v1.0.0](https://github.com/ljharb/function-bind/compare/v0.2.0...v1.0.0) - 2014-08-09 + +### Commits + +- Make sure old and unstable nodes don't fail Travis [`27adca3`](https://github.com/ljharb/function-bind/commit/27adca34a4ab6ad67b6dfde43942a1b103ce4d75) +- Fixing an issue when the bound function is called as a constructor in ES3. [`e20122d`](https://github.com/ljharb/function-bind/commit/e20122d267d92ce553859b280cbbea5d27c07731) +- Adding `npm run coverage` [`a2e29c4`](https://github.com/ljharb/function-bind/commit/a2e29c4ecaef9e2f6cd1603e868c139073375502) +- Updating tape [`b741168`](https://github.com/ljharb/function-bind/commit/b741168b12b235b1717ff696087645526b69213c) +- Upgrading tape [`63631a0`](https://github.com/ljharb/function-bind/commit/63631a04c7fbe97cc2fa61829cc27246d6986f74) +- Updating tape [`363cb46`](https://github.com/ljharb/function-bind/commit/363cb46dafb23cb3e347729a22f9448051d78464) + +## v0.2.0 - 2014-03-23 + +### Commits + +- Updating test coverage to match es5-shim. [`aa94d44`](https://github.com/ljharb/function-bind/commit/aa94d44b8f9d7f69f10e060db7709aa7a694e5d4) +- initial [`942ee07`](https://github.com/ljharb/function-bind/commit/942ee07e94e542d91798137bc4b80b926137e066) +- Setting the bound function's length properly. [`079f46a`](https://github.com/ljharb/function-bind/commit/079f46a2d3515b7c0b308c2c13fceb641f97ca25) +- Ensuring that some older browsers will throw when given a regex. [`36ac55b`](https://github.com/ljharb/function-bind/commit/36ac55b87f460d4330253c92870aa26fbfe8227f) +- Removing npm scripts that don't have dependencies [`9d2be60`](https://github.com/ljharb/function-bind/commit/9d2be600002cb8bc8606f8f3585ad3e05868c750) +- Updating tape [`297a4ac`](https://github.com/ljharb/function-bind/commit/297a4acc5464db381940aafb194d1c88f4e678f3) +- Skipping length tests for now. [`d9891ea`](https://github.com/ljharb/function-bind/commit/d9891ea4d2aaffa69f408339cdd61ff740f70565) +- don't take my tea [`dccd930`](https://github.com/ljharb/function-bind/commit/dccd930bfd60ea10cb178d28c97550c3bc8c1e07) diff --git a/gun-server/node_modules/function-bind/LICENSE b/gun-server/node_modules/function-bind/LICENSE new file mode 100644 index 0000000..62d6d23 --- /dev/null +++ b/gun-server/node_modules/function-bind/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2013 Raynos. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + diff --git a/gun-server/node_modules/function-bind/README.md b/gun-server/node_modules/function-bind/README.md new file mode 100644 index 0000000..814c20b --- /dev/null +++ b/gun-server/node_modules/function-bind/README.md @@ -0,0 +1,46 @@ +# function-bind [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] + +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Implementation of function.prototype.bind + +Old versions of phantomjs, Internet Explorer < 9, and node < 0.6 don't support `Function.prototype.bind`. + +## Example + +```js +Function.prototype.bind = require("function-bind") +``` + +## Installation + +`npm install function-bind` + +## Contributors + + - Raynos + +## MIT Licenced + +[package-url]: https://npmjs.org/package/function-bind +[npm-version-svg]: https://versionbadg.es/Raynos/function-bind.svg +[deps-svg]: https://david-dm.org/Raynos/function-bind.svg +[deps-url]: https://david-dm.org/Raynos/function-bind +[dev-deps-svg]: https://david-dm.org/Raynos/function-bind/dev-status.svg +[dev-deps-url]: https://david-dm.org/Raynos/function-bind#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/function-bind.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/function-bind.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/function-bind.svg +[downloads-url]: https://npm-stat.com/charts.html?package=function-bind +[codecov-image]: https://codecov.io/gh/Raynos/function-bind/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/Raynos/function-bind/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/Raynos/function-bind +[actions-url]: https://github.com/Raynos/function-bind/actions diff --git a/gun-server/node_modules/function-bind/implementation.js b/gun-server/node_modules/function-bind/implementation.js new file mode 100644 index 0000000..fd4384c --- /dev/null +++ b/gun-server/node_modules/function-bind/implementation.js @@ -0,0 +1,84 @@ +'use strict'; + +/* eslint no-invalid-this: 1 */ + +var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; +var toStr = Object.prototype.toString; +var max = Math.max; +var funcType = '[object Function]'; + +var concatty = function concatty(a, b) { + var arr = []; + + for (var i = 0; i < a.length; i += 1) { + arr[i] = a[i]; + } + for (var j = 0; j < b.length; j += 1) { + arr[j + a.length] = b[j]; + } + + return arr; +}; + +var slicy = function slicy(arrLike, offset) { + var arr = []; + for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) { + arr[j] = arrLike[i]; + } + return arr; +}; + +var joiny = function (arr, joiner) { + var str = ''; + for (var i = 0; i < arr.length; i += 1) { + str += arr[i]; + if (i + 1 < arr.length) { + str += joiner; + } + } + return str; +}; + +module.exports = function bind(that) { + var target = this; + if (typeof target !== 'function' || toStr.apply(target) !== funcType) { + throw new TypeError(ERROR_MESSAGE + target); + } + var args = slicy(arguments, 1); + + var bound; + var binder = function () { + if (this instanceof bound) { + var result = target.apply( + this, + concatty(args, arguments) + ); + if (Object(result) === result) { + return result; + } + return this; + } + return target.apply( + that, + concatty(args, arguments) + ); + + }; + + var boundLength = max(0, target.length - args.length); + var boundArgs = []; + for (var i = 0; i < boundLength; i++) { + boundArgs[i] = '$' + i; + } + + bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder); + + if (target.prototype) { + var Empty = function Empty() {}; + Empty.prototype = target.prototype; + bound.prototype = new Empty(); + Empty.prototype = null; + } + + return bound; +}; diff --git a/gun-server/node_modules/function-bind/index.js b/gun-server/node_modules/function-bind/index.js new file mode 100644 index 0000000..3bb6b96 --- /dev/null +++ b/gun-server/node_modules/function-bind/index.js @@ -0,0 +1,5 @@ +'use strict'; + +var implementation = require('./implementation'); + +module.exports = Function.prototype.bind || implementation; diff --git a/gun-server/node_modules/function-bind/package.json b/gun-server/node_modules/function-bind/package.json new file mode 100644 index 0000000..6185963 --- /dev/null +++ b/gun-server/node_modules/function-bind/package.json @@ -0,0 +1,87 @@ +{ + "name": "function-bind", + "version": "1.1.2", + "description": "Implementation of Function.prototype.bind", + "keywords": [ + "function", + "bind", + "shim", + "es5" + ], + "author": "Raynos ", + "repository": { + "type": "git", + "url": "https://github.com/Raynos/function-bind.git" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "main": "index", + "homepage": "https://github.com/Raynos/function-bind", + "contributors": [ + { + "name": "Raynos" + }, + { + "name": "Jordan Harband", + "url": "https://github.com/ljharb" + } + ], + "bugs": { + "url": "https://github.com/Raynos/function-bind/issues", + "email": "raynos2@gmail.com" + }, + "devDependencies": { + "@ljharb/eslint-config": "^21.1.0", + "aud": "^2.0.3", + "auto-changelog": "^2.4.0", + "eslint": "=8.8.0", + "in-publish": "^2.0.1", + "npmignore": "^0.3.0", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.7.1" + }, + "license": "MIT", + "scripts": { + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepack": "npmignore --auto --commentLines=autogenerated", + "pretest": "npm run lint", + "test": "npm run tests-only", + "posttest": "aud --production", + "tests-only": "nyc tape 'test/**/*.js'", + "lint": "eslint --ext=js,mjs .", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "ie/8..latest", + "firefox/16..latest", + "firefox/nightly", + "chrome/22..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + } +} diff --git a/gun-server/node_modules/function-bind/test/.eslintrc b/gun-server/node_modules/function-bind/test/.eslintrc new file mode 100644 index 0000000..8a56d5b --- /dev/null +++ b/gun-server/node_modules/function-bind/test/.eslintrc @@ -0,0 +1,9 @@ +{ + "rules": { + "array-bracket-newline": 0, + "array-element-newline": 0, + "max-statements-per-line": [2, { "max": 2 }], + "no-invalid-this": 0, + "no-magic-numbers": 0, + } +} diff --git a/gun-server/node_modules/function-bind/test/index.js b/gun-server/node_modules/function-bind/test/index.js new file mode 100644 index 0000000..2edecce --- /dev/null +++ b/gun-server/node_modules/function-bind/test/index.js @@ -0,0 +1,252 @@ +// jscs:disable requireUseStrict + +var test = require('tape'); + +var functionBind = require('../implementation'); +var getCurrentContext = function () { return this; }; + +test('functionBind is a function', function (t) { + t.equal(typeof functionBind, 'function'); + t.end(); +}); + +test('non-functions', function (t) { + var nonFunctions = [true, false, [], {}, 42, 'foo', NaN, /a/g]; + t.plan(nonFunctions.length); + for (var i = 0; i < nonFunctions.length; ++i) { + try { functionBind.call(nonFunctions[i]); } catch (ex) { + t.ok(ex instanceof TypeError, 'throws when given ' + String(nonFunctions[i])); + } + } + t.end(); +}); + +test('without a context', function (t) { + t.test('binds properly', function (st) { + var args, context; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + context = this; + }) + }; + namespace.func(1, 2, 3); + st.deepEqual(args, [1, 2, 3]); + st.equal(context, getCurrentContext.call()); + st.end(); + }); + + t.test('binds properly, and still supplies bound arguments', function (st) { + var args, context; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + context = this; + }, undefined, 1, 2, 3) + }; + namespace.func(4, 5, 6); + st.deepEqual(args, [1, 2, 3, 4, 5, 6]); + st.equal(context, getCurrentContext.call()); + st.end(); + }); + + t.test('returns properly', function (st) { + var args; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + return this; + }, null) + }; + var context = namespace.func(1, 2, 3); + st.equal(context, getCurrentContext.call(), 'returned context is namespaced context'); + st.deepEqual(args, [1, 2, 3], 'passed arguments are correct'); + st.end(); + }); + + t.test('returns properly with bound arguments', function (st) { + var args; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + return this; + }, null, 1, 2, 3) + }; + var context = namespace.func(4, 5, 6); + st.equal(context, getCurrentContext.call(), 'returned context is namespaced context'); + st.deepEqual(args, [1, 2, 3, 4, 5, 6], 'passed arguments are correct'); + st.end(); + }); + + t.test('called as a constructor', function (st) { + var thunkify = function (value) { + return function () { return value; }; + }; + st.test('returns object value', function (sst) { + var expectedReturnValue = [1, 2, 3]; + var Constructor = functionBind.call(thunkify(expectedReturnValue), null); + var result = new Constructor(); + sst.equal(result, expectedReturnValue); + sst.end(); + }); + + st.test('does not return primitive value', function (sst) { + var Constructor = functionBind.call(thunkify(42), null); + var result = new Constructor(); + sst.notEqual(result, 42); + sst.end(); + }); + + st.test('object from bound constructor is instance of original and bound constructor', function (sst) { + var A = function (x) { + this.name = x || 'A'; + }; + var B = functionBind.call(A, null, 'B'); + + var result = new B(); + sst.ok(result instanceof B, 'result is instance of bound constructor'); + sst.ok(result instanceof A, 'result is instance of original constructor'); + sst.end(); + }); + + st.end(); + }); + + t.end(); +}); + +test('with a context', function (t) { + t.test('with no bound arguments', function (st) { + var args, context; + var boundContext = {}; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + context = this; + }, boundContext) + }; + namespace.func(1, 2, 3); + st.equal(context, boundContext, 'binds a context properly'); + st.deepEqual(args, [1, 2, 3], 'supplies passed arguments'); + st.end(); + }); + + t.test('with bound arguments', function (st) { + var args, context; + var boundContext = {}; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + context = this; + }, boundContext, 1, 2, 3) + }; + namespace.func(4, 5, 6); + st.equal(context, boundContext, 'binds a context properly'); + st.deepEqual(args, [1, 2, 3, 4, 5, 6], 'supplies bound and passed arguments'); + st.end(); + }); + + t.test('returns properly', function (st) { + var boundContext = {}; + var args; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + return this; + }, boundContext) + }; + var context = namespace.func(1, 2, 3); + st.equal(context, boundContext, 'returned context is bound context'); + st.notEqual(context, getCurrentContext.call(), 'returned context is not lexical context'); + st.deepEqual(args, [1, 2, 3], 'passed arguments are correct'); + st.end(); + }); + + t.test('returns properly with bound arguments', function (st) { + var boundContext = {}; + var args; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + return this; + }, boundContext, 1, 2, 3) + }; + var context = namespace.func(4, 5, 6); + st.equal(context, boundContext, 'returned context is bound context'); + st.notEqual(context, getCurrentContext.call(), 'returned context is not lexical context'); + st.deepEqual(args, [1, 2, 3, 4, 5, 6], 'passed arguments are correct'); + st.end(); + }); + + t.test('passes the correct arguments when called as a constructor', function (st) { + var expected = { name: 'Correct' }; + var namespace = { + Func: functionBind.call(function (arg) { + return arg; + }, { name: 'Incorrect' }) + }; + var returned = new namespace.Func(expected); + st.equal(returned, expected, 'returns the right arg when called as a constructor'); + st.end(); + }); + + t.test('has the new instance\'s context when called as a constructor', function (st) { + var actualContext; + var expectedContext = { foo: 'bar' }; + var namespace = { + Func: functionBind.call(function () { + actualContext = this; + }, expectedContext) + }; + var result = new namespace.Func(); + st.equal(result instanceof namespace.Func, true); + st.notEqual(actualContext, expectedContext); + st.end(); + }); + + t.end(); +}); + +test('bound function length', function (t) { + t.test('sets a correct length without thisArg', function (st) { + var subject = functionBind.call(function (a, b, c) { return a + b + c; }); + st.equal(subject.length, 3); + st.equal(subject(1, 2, 3), 6); + st.end(); + }); + + t.test('sets a correct length with thisArg', function (st) { + var subject = functionBind.call(function (a, b, c) { return a + b + c; }, {}); + st.equal(subject.length, 3); + st.equal(subject(1, 2, 3), 6); + st.end(); + }); + + t.test('sets a correct length without thisArg and first argument', function (st) { + var subject = functionBind.call(function (a, b, c) { return a + b + c; }, undefined, 1); + st.equal(subject.length, 2); + st.equal(subject(2, 3), 6); + st.end(); + }); + + t.test('sets a correct length with thisArg and first argument', function (st) { + var subject = functionBind.call(function (a, b, c) { return a + b + c; }, {}, 1); + st.equal(subject.length, 2); + st.equal(subject(2, 3), 6); + st.end(); + }); + + t.test('sets a correct length without thisArg and too many arguments', function (st) { + var subject = functionBind.call(function (a, b, c) { return a + b + c; }, undefined, 1, 2, 3, 4); + st.equal(subject.length, 0); + st.equal(subject(), 6); + st.end(); + }); + + t.test('sets a correct length with thisArg and too many arguments', function (st) { + var subject = functionBind.call(function (a, b, c) { return a + b + c; }, {}, 1, 2, 3, 4); + st.equal(subject.length, 0); + st.equal(subject(), 6); + st.end(); + }); +}); diff --git a/gun-server/node_modules/get-intrinsic/.eslintrc b/gun-server/node_modules/get-intrinsic/.eslintrc new file mode 100644 index 0000000..8376636 --- /dev/null +++ b/gun-server/node_modules/get-intrinsic/.eslintrc @@ -0,0 +1,38 @@ +{ + "root": true, + + "extends": "@ljharb", + + "env": { + "es6": true, + "es2017": true, + "es2020": true, + "es2021": true, + "es2022": true, + }, + + "rules": { + "array-bracket-newline": 0, + "complexity": 0, + "eqeqeq": [2, "allow-null"], + "func-name-matching": 0, + "id-length": 0, + "max-lines": 0, + "max-lines-per-function": [2, 90], + "max-params": [2, 4], + "max-statements": 0, + "max-statements-per-line": [2, { "max": 2 }], + "multiline-comment-style": 0, + "no-magic-numbers": 0, + "sort-keys": 0, + }, + + "overrides": [ + { + "files": "test/**", + "rules": { + "new-cap": 0, + }, + }, + ], +} diff --git a/gun-server/node_modules/get-intrinsic/.github/FUNDING.yml b/gun-server/node_modules/get-intrinsic/.github/FUNDING.yml new file mode 100644 index 0000000..8e8da0d --- /dev/null +++ b/gun-server/node_modules/get-intrinsic/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/get-intrinsic +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/gun-server/node_modules/get-intrinsic/.nycrc b/gun-server/node_modules/get-intrinsic/.nycrc new file mode 100644 index 0000000..bdd626c --- /dev/null +++ b/gun-server/node_modules/get-intrinsic/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/gun-server/node_modules/get-intrinsic/CHANGELOG.md b/gun-server/node_modules/get-intrinsic/CHANGELOG.md new file mode 100644 index 0000000..96d5397 --- /dev/null +++ b/gun-server/node_modules/get-intrinsic/CHANGELOG.md @@ -0,0 +1,143 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.2.4](https://github.com/ljharb/get-intrinsic/compare/v1.2.3...v1.2.4) - 2024-02-05 + +### Commits + +- [Refactor] use all 7 <+ ES6 Errors from `es-errors` [`bcac811`](https://github.com/ljharb/get-intrinsic/commit/bcac811abdc1c982e12abf848a410d6aae148d14) + +## [v1.2.3](https://github.com/ljharb/get-intrinsic/compare/v1.2.2...v1.2.3) - 2024-02-03 + +### Commits + +- [Refactor] use `es-errors`, so things that only need those do not need `get-intrinsic` [`f11db9c`](https://github.com/ljharb/get-intrinsic/commit/f11db9c4fb97d87bbd53d3c73ac6b3db3613ad3b) +- [Dev Deps] update `aud`, `es-abstract`, `mock-property`, `npmignore` [`b7ac7d1`](https://github.com/ljharb/get-intrinsic/commit/b7ac7d1616fefb03877b1aed0c8f8d61aad32b6c) +- [meta] simplify `exports` [`faa0cc6`](https://github.com/ljharb/get-intrinsic/commit/faa0cc618e2830ffb51a8202490b0c215d965cbc) +- [meta] add missing `engines.node` [`774dd0b`](https://github.com/ljharb/get-intrinsic/commit/774dd0b3e8f741c3f05a6322d124d6087f146af1) +- [Dev Deps] update `tape` [`5828e8e`](https://github.com/ljharb/get-intrinsic/commit/5828e8e4a04e69312e87a36c0ea39428a7a4c3d8) +- [Robustness] use null objects for lookups [`eb9a11f`](https://github.com/ljharb/get-intrinsic/commit/eb9a11fa9eb3e13b193fcc05a7fb814341b1a7b7) +- [meta] add `sideEffects` flag [`89bcc7a`](https://github.com/ljharb/get-intrinsic/commit/89bcc7a42e19bf07b7c21e3094d5ab177109e6d2) + +## [v1.2.2](https://github.com/ljharb/get-intrinsic/compare/v1.2.1...v1.2.2) - 2023-10-20 + +### Commits + +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `call-bind`, `es-abstract`, `mock-property`, `object-inspect`, `tape` [`f51bcf2`](https://github.com/ljharb/get-intrinsic/commit/f51bcf26412d58d17ce17c91c9afd0ad271f0762) +- [Refactor] use `hasown` instead of `has` [`18d14b7`](https://github.com/ljharb/get-intrinsic/commit/18d14b799bea6b5765e1cec91890830cbcdb0587) +- [Deps] update `function-bind` [`6e109c8`](https://github.com/ljharb/get-intrinsic/commit/6e109c81e03804cc5e7824fb64353cdc3d8ee2c7) + +## [v1.2.1](https://github.com/ljharb/get-intrinsic/compare/v1.2.0...v1.2.1) - 2023-05-13 + +### Commits + +- [Fix] avoid a crash in envs without `__proto__` [`7bad8d0`](https://github.com/ljharb/get-intrinsic/commit/7bad8d061bf8721733b58b73a2565af2b6756b64) +- [Dev Deps] update `es-abstract` [`c60e6b7`](https://github.com/ljharb/get-intrinsic/commit/c60e6b7b4cf9660c7f27ed970970fd55fac48dc5) + +## [v1.2.0](https://github.com/ljharb/get-intrinsic/compare/v1.1.3...v1.2.0) - 2023-01-19 + +### Commits + +- [actions] update checkout action [`ca6b12f`](https://github.com/ljharb/get-intrinsic/commit/ca6b12f31eaacea4ea3b055e744cd61623385ffb) +- [Dev Deps] update `@ljharb/eslint-config`, `es-abstract`, `object-inspect`, `tape` [`41a3727`](https://github.com/ljharb/get-intrinsic/commit/41a3727d0026fa04273ae216a5f8e12eefd72da8) +- [Fix] ensure `Error.prototype` is undeniable [`c511e97`](https://github.com/ljharb/get-intrinsic/commit/c511e97ae99c764c4524b540dee7a70757af8da3) +- [Dev Deps] update `aud`, `es-abstract`, `tape` [`1bef8a8`](https://github.com/ljharb/get-intrinsic/commit/1bef8a8fd439ebb80863199b6189199e0851ac67) +- [Dev Deps] update `aud`, `es-abstract` [`0d41f16`](https://github.com/ljharb/get-intrinsic/commit/0d41f16bcd500bc28b7bfc98043ebf61ea081c26) +- [New] add `BigInt64Array` and `BigUint64Array` [`a6cca25`](https://github.com/ljharb/get-intrinsic/commit/a6cca25f29635889b7e9bd669baf9e04be90e48c) +- [Tests] use `gopd` [`ecf7722`](https://github.com/ljharb/get-intrinsic/commit/ecf7722240d15cfd16edda06acf63359c10fb9bd) + +## [v1.1.3](https://github.com/ljharb/get-intrinsic/compare/v1.1.2...v1.1.3) - 2022-09-12 + +### Commits + +- [Dev Deps] update `es-abstract`, `es-value-fixtures`, `tape` [`07ff291`](https://github.com/ljharb/get-intrinsic/commit/07ff291816406ebe5a12d7f16965bde0942dd688) +- [Fix] properly check for % signs [`50ac176`](https://github.com/ljharb/get-intrinsic/commit/50ac1760fe99c227e64eabde76e9c0e44cd881b5) + +## [v1.1.2](https://github.com/ljharb/get-intrinsic/compare/v1.1.1...v1.1.2) - 2022-06-08 + +### Fixed + +- [Fix] properly validate against extra % signs [`#16`](https://github.com/ljharb/get-intrinsic/issues/16) + +### Commits + +- [actions] reuse common workflows [`0972547`](https://github.com/ljharb/get-intrinsic/commit/0972547efd0abc863fe4c445a6ca7eb4f8c6901d) +- [meta] use `npmignore` to autogenerate an npmignore file [`5ba0b51`](https://github.com/ljharb/get-intrinsic/commit/5ba0b51d8d8d4f1c31d426d74abc0770fd106bad) +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`c364492`](https://github.com/ljharb/get-intrinsic/commit/c364492af4af51333e6f81c0bf21fd3d602c3661) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `es-abstract`, `object-inspect`, `tape` [`dc04dad`](https://github.com/ljharb/get-intrinsic/commit/dc04dad86f6e5608775a2640cb0db5927ae29ed9) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `es-abstract`, `object-inspect`, `safe-publish-latest`, `tape` [`1c14059`](https://github.com/ljharb/get-intrinsic/commit/1c1405984e86dd2dc9366c15d8a0294a96a146a5) +- [Tests] use `mock-property` [`b396ef0`](https://github.com/ljharb/get-intrinsic/commit/b396ef05bb73b1d699811abd64b0d9b97997fdda) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `object-inspect`, `tape` [`c2c758d`](https://github.com/ljharb/get-intrinsic/commit/c2c758d3b90af4fef0a76910d8d3c292ec8d1d3e) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `es-abstract`, `es-value-fixtures`, `object-inspect`, `tape` [`29e3c09`](https://github.com/ljharb/get-intrinsic/commit/29e3c091c2bf3e17099969847e8729d0e46896de) +- [actions] update codecov uploader [`8cbc141`](https://github.com/ljharb/get-intrinsic/commit/8cbc1418940d7a8941f3a7985cbc4ac095c5e13d) +- [Dev Deps] update `@ljharb/eslint-config`, `es-abstract`, `es-value-fixtures`, `object-inspect`, `tape` [`10b6f5c`](https://github.com/ljharb/get-intrinsic/commit/10b6f5c02593fb3680c581d696ac124e30652932) +- [readme] add github actions/codecov badges [`4e25400`](https://github.com/ljharb/get-intrinsic/commit/4e25400d9f51ae9eb059cbe22d9144e70ea214e8) +- [Tests] use `for-each` instead of `foreach` [`c05b957`](https://github.com/ljharb/get-intrinsic/commit/c05b957ad9a7bc7721af7cc9e9be1edbfe057496) +- [Dev Deps] update `es-abstract` [`29b05ae`](https://github.com/ljharb/get-intrinsic/commit/29b05aec3e7330e9ad0b8e0f685a9112c20cdd97) +- [meta] use `prepublishOnly` script for npm 7+ [`95c285d`](https://github.com/ljharb/get-intrinsic/commit/95c285da810516057d3bbfa871176031af38f05d) +- [Deps] update `has-symbols` [`593cb4f`](https://github.com/ljharb/get-intrinsic/commit/593cb4fb38e7922e40e42c183f45274b636424cd) +- [readme] fix repo URLs [`1c8305b`](https://github.com/ljharb/get-intrinsic/commit/1c8305b5365827c9b6fc785434aac0e1328ff2f5) +- [Deps] update `has-symbols` [`c7138b6`](https://github.com/ljharb/get-intrinsic/commit/c7138b6c6d73132d859471fb8c13304e1e7c8b20) +- [Dev Deps] remove unused `has-bigints` [`bd63aff`](https://github.com/ljharb/get-intrinsic/commit/bd63aff6ad8f3a986c557fcda2914187bdaab359) + +## [v1.1.1](https://github.com/ljharb/get-intrinsic/compare/v1.1.0...v1.1.1) - 2021-02-03 + +### Fixed + +- [meta] export `./package.json` [`#9`](https://github.com/ljharb/get-intrinsic/issues/9) + +### Commits + +- [readme] flesh out the readme; use `evalmd` [`d12f12c`](https://github.com/ljharb/get-intrinsic/commit/d12f12c15345a0a0772cc65a7c64369529abd614) +- [eslint] set up proper globals config [`5a8c098`](https://github.com/ljharb/get-intrinsic/commit/5a8c0984e3319d1ac0e64b102f8ec18b64e79f36) +- [Dev Deps] update `eslint` [`7b9a5c0`](https://github.com/ljharb/get-intrinsic/commit/7b9a5c0d31a90ca1a1234181c74988fb046701cd) + +## [v1.1.0](https://github.com/ljharb/get-intrinsic/compare/v1.0.2...v1.1.0) - 2021-01-25 + +### Fixed + +- [Refactor] delay `Function` eval until syntax-derived values are requested [`#3`](https://github.com/ljharb/get-intrinsic/issues/3) + +### Commits + +- [Tests] migrate tests to Github Actions [`2ab762b`](https://github.com/ljharb/get-intrinsic/commit/2ab762b48164aea8af37a40ba105bbc8246ab8c4) +- [meta] do not publish github action workflow files [`5e7108e`](https://github.com/ljharb/get-intrinsic/commit/5e7108e4768b244d48d9567ba4f8a6cab9c65b8e) +- [Tests] add some coverage [`01ac7a8`](https://github.com/ljharb/get-intrinsic/commit/01ac7a87ac29738567e8524cd8c9e026b1fa8cb3) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `call-bind`, `es-abstract`, `tape`; add `call-bind` [`911b672`](https://github.com/ljharb/get-intrinsic/commit/911b672fbffae433a96924c6ce013585e425f4b7) +- [Refactor] rearrange evalled constructors a bit [`7e7e4bf`](https://github.com/ljharb/get-intrinsic/commit/7e7e4bf583f3799c8ac1c6c5e10d2cb553957347) +- [meta] add Automatic Rebase and Require Allow Edits workflows [`0199968`](https://github.com/ljharb/get-intrinsic/commit/01999687a263ffce0a3cb011dfbcb761754aedbc) + +## [v1.0.2](https://github.com/ljharb/get-intrinsic/compare/v1.0.1...v1.0.2) - 2020-12-17 + +### Commits + +- [Fix] Throw for non‑existent intrinsics [`68f873b`](https://github.com/ljharb/get-intrinsic/commit/68f873b013c732a05ad6f5fc54f697e55515461b) +- [Fix] Throw for non‑existent segments in the intrinsic path [`8325dee`](https://github.com/ljharb/get-intrinsic/commit/8325deee43128f3654d3399aa9591741ebe17b21) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `has-bigints`, `object-inspect` [`0c227a7`](https://github.com/ljharb/get-intrinsic/commit/0c227a7d8b629166f25715fd242553892e458525) +- [meta] do not lint coverage output [`70d2419`](https://github.com/ljharb/get-intrinsic/commit/70d24199b620043cd9110fc5f426d214ebe21dc9) + +## [v1.0.1](https://github.com/ljharb/get-intrinsic/compare/v1.0.0...v1.0.1) - 2020-10-30 + +### Commits + +- [Tests] gather coverage data on every job [`d1d280d`](https://github.com/ljharb/get-intrinsic/commit/d1d280dec714e3f0519cc877dbcb193057d9cac6) +- [Fix] add missing dependencies [`5031771`](https://github.com/ljharb/get-intrinsic/commit/5031771bb1095b38be88ce7c41d5de88718e432e) +- [Tests] use `es-value-fixtures` [`af48765`](https://github.com/ljharb/get-intrinsic/commit/af48765a23c5323fb0b6b38dbf00eb5099c7bebc) + +## v1.0.0 - 2020-10-29 + +### Commits + +- Implementation [`bbce57c`](https://github.com/ljharb/get-intrinsic/commit/bbce57c6f33d05b2d8d3efa273ceeb3ee01127bb) +- Tests [`17b4f0d`](https://github.com/ljharb/get-intrinsic/commit/17b4f0d56dea6b4059b56fc30ef3ee4d9500ebc2) +- Initial commit [`3153294`](https://github.com/ljharb/get-intrinsic/commit/31532948de363b0a27dd9fd4649e7b7028ec4b44) +- npm init [`fb326c4`](https://github.com/ljharb/get-intrinsic/commit/fb326c4d2817c8419ec31de1295f06bb268a7902) +- [meta] add Automatic Rebase and Require Allow Edits workflows [`48862fb`](https://github.com/ljharb/get-intrinsic/commit/48862fb2508c8f6a57968e6d08b7c883afc9d550) +- [meta] add `auto-changelog` [`5f28ad0`](https://github.com/ljharb/get-intrinsic/commit/5f28ad019e060a353d8028f9f2591a9cc93074a1) +- [meta] add "funding"; create `FUNDING.yml` [`c2bbdde`](https://github.com/ljharb/get-intrinsic/commit/c2bbddeba73a875be61484ee4680b129a6d4e0a1) +- [Tests] add `npm run lint` [`0a84b98`](https://github.com/ljharb/get-intrinsic/commit/0a84b98b22b7cf7a748666f705b0003a493c35fd) +- Only apps should have lockfiles [`9586c75`](https://github.com/ljharb/get-intrinsic/commit/9586c75866c1ee678e4d5d4dbbdef6997e511b05) diff --git a/gun-server/node_modules/get-intrinsic/LICENSE b/gun-server/node_modules/get-intrinsic/LICENSE new file mode 100644 index 0000000..48f05d0 --- /dev/null +++ b/gun-server/node_modules/get-intrinsic/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/gun-server/node_modules/get-intrinsic/README.md b/gun-server/node_modules/get-intrinsic/README.md new file mode 100644 index 0000000..3aa0bba --- /dev/null +++ b/gun-server/node_modules/get-intrinsic/README.md @@ -0,0 +1,71 @@ +# get-intrinsic [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Get and robustly cache all JS language-level intrinsics at first require time. + +See the syntax described [in the JS spec](https://tc39.es/ecma262/#sec-well-known-intrinsic-objects) for reference. + +## Example + +```js +var GetIntrinsic = require('get-intrinsic'); +var assert = require('assert'); + +// static methods +assert.equal(GetIntrinsic('%Math.pow%'), Math.pow); +assert.equal(Math.pow(2, 3), 8); +assert.equal(GetIntrinsic('%Math.pow%')(2, 3), 8); +delete Math.pow; +assert.equal(GetIntrinsic('%Math.pow%')(2, 3), 8); + +// instance methods +var arr = [1]; +assert.equal(GetIntrinsic('%Array.prototype.push%'), Array.prototype.push); +assert.deepEqual(arr, [1]); + +arr.push(2); +assert.deepEqual(arr, [1, 2]); + +GetIntrinsic('%Array.prototype.push%').call(arr, 3); +assert.deepEqual(arr, [1, 2, 3]); + +delete Array.prototype.push; +GetIntrinsic('%Array.prototype.push%').call(arr, 4); +assert.deepEqual(arr, [1, 2, 3, 4]); + +// missing features +delete JSON.parse; // to simulate a real intrinsic that is missing in the environment +assert.throws(() => GetIntrinsic('%JSON.parse%')); +assert.equal(undefined, GetIntrinsic('%JSON.parse%', true)); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +## Security + +Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report. + +[package-url]: https://npmjs.org/package/get-intrinsic +[npm-version-svg]: https://versionbadg.es/ljharb/get-intrinsic.svg +[deps-svg]: https://david-dm.org/ljharb/get-intrinsic.svg +[deps-url]: https://david-dm.org/ljharb/get-intrinsic +[dev-deps-svg]: https://david-dm.org/ljharb/get-intrinsic/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/get-intrinsic#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/get-intrinsic.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/get-intrinsic.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/get-intrinsic.svg +[downloads-url]: https://npm-stat.com/charts.html?package=get-intrinsic +[codecov-image]: https://codecov.io/gh/ljharb/get-intrinsic/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/get-intrinsic/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/get-intrinsic +[actions-url]: https://github.com/ljharb/get-intrinsic/actions diff --git a/gun-server/node_modules/get-intrinsic/index.js b/gun-server/node_modules/get-intrinsic/index.js new file mode 100644 index 0000000..c25e2c4 --- /dev/null +++ b/gun-server/node_modules/get-intrinsic/index.js @@ -0,0 +1,359 @@ +'use strict'; + +var undefined; + +var $Error = require('es-errors'); +var $EvalError = require('es-errors/eval'); +var $RangeError = require('es-errors/range'); +var $ReferenceError = require('es-errors/ref'); +var $SyntaxError = require('es-errors/syntax'); +var $TypeError = require('es-errors/type'); +var $URIError = require('es-errors/uri'); + +var $Function = Function; + +// eslint-disable-next-line consistent-return +var getEvalledConstructor = function (expressionSyntax) { + try { + return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')(); + } catch (e) {} +}; + +var $gOPD = Object.getOwnPropertyDescriptor; +if ($gOPD) { + try { + $gOPD({}, ''); + } catch (e) { + $gOPD = null; // this is IE 8, which has a broken gOPD + } +} + +var throwTypeError = function () { + throw new $TypeError(); +}; +var ThrowTypeError = $gOPD + ? (function () { + try { + // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties + arguments.callee; // IE 8 does not throw here + return throwTypeError; + } catch (calleeThrows) { + try { + // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '') + return $gOPD(arguments, 'callee').get; + } catch (gOPDthrows) { + return throwTypeError; + } + } + }()) + : throwTypeError; + +var hasSymbols = require('has-symbols')(); +var hasProto = require('has-proto')(); + +var getProto = Object.getPrototypeOf || ( + hasProto + ? function (x) { return x.__proto__; } // eslint-disable-line no-proto + : null +); + +var needsEval = {}; + +var TypedArray = typeof Uint8Array === 'undefined' || !getProto ? undefined : getProto(Uint8Array); + +var INTRINSICS = { + __proto__: null, + '%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError, + '%Array%': Array, + '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer, + '%ArrayIteratorPrototype%': hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined, + '%AsyncFromSyncIteratorPrototype%': undefined, + '%AsyncFunction%': needsEval, + '%AsyncGenerator%': needsEval, + '%AsyncGeneratorFunction%': needsEval, + '%AsyncIteratorPrototype%': needsEval, + '%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics, + '%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt, + '%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined : BigInt64Array, + '%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined : BigUint64Array, + '%Boolean%': Boolean, + '%DataView%': typeof DataView === 'undefined' ? undefined : DataView, + '%Date%': Date, + '%decodeURI%': decodeURI, + '%decodeURIComponent%': decodeURIComponent, + '%encodeURI%': encodeURI, + '%encodeURIComponent%': encodeURIComponent, + '%Error%': $Error, + '%eval%': eval, // eslint-disable-line no-eval + '%EvalError%': $EvalError, + '%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array, + '%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array, + '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry, + '%Function%': $Function, + '%GeneratorFunction%': needsEval, + '%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array, + '%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array, + '%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array, + '%isFinite%': isFinite, + '%isNaN%': isNaN, + '%IteratorPrototype%': hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined, + '%JSON%': typeof JSON === 'object' ? JSON : undefined, + '%Map%': typeof Map === 'undefined' ? undefined : Map, + '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Map()[Symbol.iterator]()), + '%Math%': Math, + '%Number%': Number, + '%Object%': Object, + '%parseFloat%': parseFloat, + '%parseInt%': parseInt, + '%Promise%': typeof Promise === 'undefined' ? undefined : Promise, + '%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy, + '%RangeError%': $RangeError, + '%ReferenceError%': $ReferenceError, + '%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect, + '%RegExp%': RegExp, + '%Set%': typeof Set === 'undefined' ? undefined : Set, + '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Set()[Symbol.iterator]()), + '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer, + '%String%': String, + '%StringIteratorPrototype%': hasSymbols && getProto ? getProto(''[Symbol.iterator]()) : undefined, + '%Symbol%': hasSymbols ? Symbol : undefined, + '%SyntaxError%': $SyntaxError, + '%ThrowTypeError%': ThrowTypeError, + '%TypedArray%': TypedArray, + '%TypeError%': $TypeError, + '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array, + '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray, + '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array, + '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array, + '%URIError%': $URIError, + '%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap, + '%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef, + '%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet +}; + +if (getProto) { + try { + null.error; // eslint-disable-line no-unused-expressions + } catch (e) { + // https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229 + var errorProto = getProto(getProto(e)); + INTRINSICS['%Error.prototype%'] = errorProto; + } +} + +var doEval = function doEval(name) { + var value; + if (name === '%AsyncFunction%') { + value = getEvalledConstructor('async function () {}'); + } else if (name === '%GeneratorFunction%') { + value = getEvalledConstructor('function* () {}'); + } else if (name === '%AsyncGeneratorFunction%') { + value = getEvalledConstructor('async function* () {}'); + } else if (name === '%AsyncGenerator%') { + var fn = doEval('%AsyncGeneratorFunction%'); + if (fn) { + value = fn.prototype; + } + } else if (name === '%AsyncIteratorPrototype%') { + var gen = doEval('%AsyncGenerator%'); + if (gen && getProto) { + value = getProto(gen.prototype); + } + } + + INTRINSICS[name] = value; + + return value; +}; + +var LEGACY_ALIASES = { + __proto__: null, + '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'], + '%ArrayPrototype%': ['Array', 'prototype'], + '%ArrayProto_entries%': ['Array', 'prototype', 'entries'], + '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'], + '%ArrayProto_keys%': ['Array', 'prototype', 'keys'], + '%ArrayProto_values%': ['Array', 'prototype', 'values'], + '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'], + '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'], + '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'], + '%BooleanPrototype%': ['Boolean', 'prototype'], + '%DataViewPrototype%': ['DataView', 'prototype'], + '%DatePrototype%': ['Date', 'prototype'], + '%ErrorPrototype%': ['Error', 'prototype'], + '%EvalErrorPrototype%': ['EvalError', 'prototype'], + '%Float32ArrayPrototype%': ['Float32Array', 'prototype'], + '%Float64ArrayPrototype%': ['Float64Array', 'prototype'], + '%FunctionPrototype%': ['Function', 'prototype'], + '%Generator%': ['GeneratorFunction', 'prototype'], + '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'], + '%Int8ArrayPrototype%': ['Int8Array', 'prototype'], + '%Int16ArrayPrototype%': ['Int16Array', 'prototype'], + '%Int32ArrayPrototype%': ['Int32Array', 'prototype'], + '%JSONParse%': ['JSON', 'parse'], + '%JSONStringify%': ['JSON', 'stringify'], + '%MapPrototype%': ['Map', 'prototype'], + '%NumberPrototype%': ['Number', 'prototype'], + '%ObjectPrototype%': ['Object', 'prototype'], + '%ObjProto_toString%': ['Object', 'prototype', 'toString'], + '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'], + '%PromisePrototype%': ['Promise', 'prototype'], + '%PromiseProto_then%': ['Promise', 'prototype', 'then'], + '%Promise_all%': ['Promise', 'all'], + '%Promise_reject%': ['Promise', 'reject'], + '%Promise_resolve%': ['Promise', 'resolve'], + '%RangeErrorPrototype%': ['RangeError', 'prototype'], + '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'], + '%RegExpPrototype%': ['RegExp', 'prototype'], + '%SetPrototype%': ['Set', 'prototype'], + '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'], + '%StringPrototype%': ['String', 'prototype'], + '%SymbolPrototype%': ['Symbol', 'prototype'], + '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'], + '%TypedArrayPrototype%': ['TypedArray', 'prototype'], + '%TypeErrorPrototype%': ['TypeError', 'prototype'], + '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'], + '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'], + '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'], + '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'], + '%URIErrorPrototype%': ['URIError', 'prototype'], + '%WeakMapPrototype%': ['WeakMap', 'prototype'], + '%WeakSetPrototype%': ['WeakSet', 'prototype'] +}; + +var bind = require('function-bind'); +var hasOwn = require('hasown'); +var $concat = bind.call(Function.call, Array.prototype.concat); +var $spliceApply = bind.call(Function.apply, Array.prototype.splice); +var $replace = bind.call(Function.call, String.prototype.replace); +var $strSlice = bind.call(Function.call, String.prototype.slice); +var $exec = bind.call(Function.call, RegExp.prototype.exec); + +/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */ +var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; +var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */ +var stringToPath = function stringToPath(string) { + var first = $strSlice(string, 0, 1); + var last = $strSlice(string, -1); + if (first === '%' && last !== '%') { + throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`'); + } else if (last === '%' && first !== '%') { + throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`'); + } + var result = []; + $replace(string, rePropName, function (match, number, quote, subString) { + result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match; + }); + return result; +}; +/* end adaptation */ + +var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { + var intrinsicName = name; + var alias; + if (hasOwn(LEGACY_ALIASES, intrinsicName)) { + alias = LEGACY_ALIASES[intrinsicName]; + intrinsicName = '%' + alias[0] + '%'; + } + + if (hasOwn(INTRINSICS, intrinsicName)) { + var value = INTRINSICS[intrinsicName]; + if (value === needsEval) { + value = doEval(intrinsicName); + } + if (typeof value === 'undefined' && !allowMissing) { + throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); + } + + return { + alias: alias, + name: intrinsicName, + value: value + }; + } + + throw new $SyntaxError('intrinsic ' + name + ' does not exist!'); +}; + +module.exports = function GetIntrinsic(name, allowMissing) { + if (typeof name !== 'string' || name.length === 0) { + throw new $TypeError('intrinsic name must be a non-empty string'); + } + if (arguments.length > 1 && typeof allowMissing !== 'boolean') { + throw new $TypeError('"allowMissing" argument must be a boolean'); + } + + if ($exec(/^%?[^%]*%?$/, name) === null) { + throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name'); + } + var parts = stringToPath(name); + var intrinsicBaseName = parts.length > 0 ? parts[0] : ''; + + var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing); + var intrinsicRealName = intrinsic.name; + var value = intrinsic.value; + var skipFurtherCaching = false; + + var alias = intrinsic.alias; + if (alias) { + intrinsicBaseName = alias[0]; + $spliceApply(parts, $concat([0, 1], alias)); + } + + for (var i = 1, isOwn = true; i < parts.length; i += 1) { + var part = parts[i]; + var first = $strSlice(part, 0, 1); + var last = $strSlice(part, -1); + if ( + ( + (first === '"' || first === "'" || first === '`') + || (last === '"' || last === "'" || last === '`') + ) + && first !== last + ) { + throw new $SyntaxError('property names with quotes must have matching quotes'); + } + if (part === 'constructor' || !isOwn) { + skipFurtherCaching = true; + } + + intrinsicBaseName += '.' + part; + intrinsicRealName = '%' + intrinsicBaseName + '%'; + + if (hasOwn(INTRINSICS, intrinsicRealName)) { + value = INTRINSICS[intrinsicRealName]; + } else if (value != null) { + if (!(part in value)) { + if (!allowMissing) { + throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.'); + } + return void undefined; + } + if ($gOPD && (i + 1) >= parts.length) { + var desc = $gOPD(value, part); + isOwn = !!desc; + + // By convention, when a data property is converted to an accessor + // property to emulate a data property that does not suffer from + // the override mistake, that accessor's getter is marked with + // an `originalValue` property. Here, when we detect this, we + // uphold the illusion by pretending to see that original data + // property, i.e., returning the value rather than the getter + // itself. + if (isOwn && 'get' in desc && !('originalValue' in desc.get)) { + value = desc.get; + } else { + value = value[part]; + } + } else { + isOwn = hasOwn(value, part); + value = value[part]; + } + + if (isOwn && !skipFurtherCaching) { + INTRINSICS[intrinsicRealName] = value; + } + } + } + return value; +}; diff --git a/gun-server/node_modules/get-intrinsic/package.json b/gun-server/node_modules/get-intrinsic/package.json new file mode 100644 index 0000000..568dff9 --- /dev/null +++ b/gun-server/node_modules/get-intrinsic/package.json @@ -0,0 +1,93 @@ +{ + "name": "get-intrinsic", + "version": "1.2.4", + "description": "Get and robustly cache all JS language-level intrinsics at first require time", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "prelint": "evalmd README.md", + "lint": "eslint --ext=.js,.mjs .", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/get-intrinsic.git" + }, + "keywords": [ + "javascript", + "ecmascript", + "es", + "js", + "intrinsic", + "getintrinsic", + "es-abstract" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/get-intrinsic/issues" + }, + "homepage": "https://github.com/ljharb/get-intrinsic#readme", + "devDependencies": { + "@ljharb/eslint-config": "^21.1.0", + "aud": "^2.0.4", + "auto-changelog": "^2.4.0", + "call-bind": "^1.0.5", + "es-abstract": "^1.22.3", + "es-value-fixtures": "^1.4.2", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "for-each": "^0.3.3", + "gopd": "^1.0.1", + "make-async-function": "^1.0.0", + "make-async-generator-function": "^1.0.0", + "make-generator-function": "^2.0.0", + "mock-property": "^1.0.3", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "object-inspect": "^1.13.1", + "safe-publish-latest": "^2.0.0", + "tape": "^5.7.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "has-proto": "^1.0.1", + "has-symbols": "^1.0.3", + "hasown": "^2.0.0" + }, + "testling": { + "files": "test/GetIntrinsic.js" + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/gun-server/node_modules/get-intrinsic/test/GetIntrinsic.js b/gun-server/node_modules/get-intrinsic/test/GetIntrinsic.js new file mode 100644 index 0000000..1cc08e0 --- /dev/null +++ b/gun-server/node_modules/get-intrinsic/test/GetIntrinsic.js @@ -0,0 +1,274 @@ +'use strict'; + +var GetIntrinsic = require('../'); + +var test = require('tape'); +var forEach = require('for-each'); +var debug = require('object-inspect'); +var generatorFns = require('make-generator-function')(); +var asyncFns = require('make-async-function').list(); +var asyncGenFns = require('make-async-generator-function')(); +var mockProperty = require('mock-property'); + +var callBound = require('call-bind/callBound'); +var v = require('es-value-fixtures'); +var $gOPD = require('gopd'); +var DefinePropertyOrThrow = require('es-abstract/2021/DefinePropertyOrThrow'); + +var $isProto = callBound('%Object.prototype.isPrototypeOf%'); + +test('export', function (t) { + t.equal(typeof GetIntrinsic, 'function', 'it is a function'); + t.equal(GetIntrinsic.length, 2, 'function has length of 2'); + + t.end(); +}); + +test('throws', function (t) { + t['throws']( + function () { GetIntrinsic('not an intrinsic'); }, + SyntaxError, + 'nonexistent intrinsic throws a syntax error' + ); + + t['throws']( + function () { GetIntrinsic(''); }, + TypeError, + 'empty string intrinsic throws a type error' + ); + + t['throws']( + function () { GetIntrinsic('.'); }, + SyntaxError, + '"just a dot" intrinsic throws a syntax error' + ); + + t['throws']( + function () { GetIntrinsic('%String'); }, + SyntaxError, + 'Leading % without trailing % throws a syntax error' + ); + + t['throws']( + function () { GetIntrinsic('String%'); }, + SyntaxError, + 'Trailing % without leading % throws a syntax error' + ); + + t['throws']( + function () { GetIntrinsic("String['prototype]"); }, + SyntaxError, + 'Dynamic property access is disallowed for intrinsics (unterminated string)' + ); + + t['throws']( + function () { GetIntrinsic('%Proxy.prototype.undefined%'); }, + TypeError, + "Throws when middle part doesn't exist (%Proxy.prototype.undefined%)" + ); + + t['throws']( + function () { GetIntrinsic('%Array.prototype%garbage%'); }, + SyntaxError, + 'Throws with extra percent signs' + ); + + t['throws']( + function () { GetIntrinsic('%Array.prototype%push%'); }, + SyntaxError, + 'Throws with extra percent signs, even on an existing intrinsic' + ); + + forEach(v.nonStrings, function (nonString) { + t['throws']( + function () { GetIntrinsic(nonString); }, + TypeError, + debug(nonString) + ' is not a String' + ); + }); + + forEach(v.nonBooleans, function (nonBoolean) { + t['throws']( + function () { GetIntrinsic('%', nonBoolean); }, + TypeError, + debug(nonBoolean) + ' is not a Boolean' + ); + }); + + forEach([ + 'toString', + 'propertyIsEnumerable', + 'hasOwnProperty' + ], function (objectProtoMember) { + t['throws']( + function () { GetIntrinsic(objectProtoMember); }, + SyntaxError, + debug(objectProtoMember) + ' is not an intrinsic' + ); + }); + + t.end(); +}); + +test('base intrinsics', function (t) { + t.equal(GetIntrinsic('%Object%'), Object, '%Object% yields Object'); + t.equal(GetIntrinsic('Object'), Object, 'Object yields Object'); + t.equal(GetIntrinsic('%Array%'), Array, '%Array% yields Array'); + t.equal(GetIntrinsic('Array'), Array, 'Array yields Array'); + + t.end(); +}); + +test('dotted paths', function (t) { + t.equal(GetIntrinsic('%Object.prototype.toString%'), Object.prototype.toString, '%Object.prototype.toString% yields Object.prototype.toString'); + t.equal(GetIntrinsic('Object.prototype.toString'), Object.prototype.toString, 'Object.prototype.toString yields Object.prototype.toString'); + t.equal(GetIntrinsic('%Array.prototype.push%'), Array.prototype.push, '%Array.prototype.push% yields Array.prototype.push'); + t.equal(GetIntrinsic('Array.prototype.push'), Array.prototype.push, 'Array.prototype.push yields Array.prototype.push'); + + test('underscore paths are aliases for dotted paths', { skip: !Object.isFrozen || Object.isFrozen(Object.prototype) }, function (st) { + var original = GetIntrinsic('%ObjProto_toString%'); + + forEach([ + '%Object.prototype.toString%', + 'Object.prototype.toString', + '%ObjectPrototype.toString%', + 'ObjectPrototype.toString', + '%ObjProto_toString%', + 'ObjProto_toString' + ], function (name) { + DefinePropertyOrThrow(Object.prototype, 'toString', { + '[[Value]]': function toString() { + return original.apply(this, arguments); + } + }); + st.equal(GetIntrinsic(name), original, name + ' yields original Object.prototype.toString'); + }); + + DefinePropertyOrThrow(Object.prototype, 'toString', { '[[Value]]': original }); + st.end(); + }); + + test('dotted paths cache', { skip: !Object.isFrozen || Object.isFrozen(Object.prototype) }, function (st) { + var original = GetIntrinsic('%Object.prototype.propertyIsEnumerable%'); + + forEach([ + '%Object.prototype.propertyIsEnumerable%', + 'Object.prototype.propertyIsEnumerable', + '%ObjectPrototype.propertyIsEnumerable%', + 'ObjectPrototype.propertyIsEnumerable' + ], function (name) { + var restore = mockProperty(Object.prototype, 'propertyIsEnumerable', { + value: function propertyIsEnumerable() { + return original.apply(this, arguments); + } + }); + st.equal(GetIntrinsic(name), original, name + ' yields cached Object.prototype.propertyIsEnumerable'); + + restore(); + }); + + st.end(); + }); + + test('dotted path reports correct error', function (st) { + st['throws'](function () { + GetIntrinsic('%NonExistentIntrinsic.prototype.property%'); + }, /%NonExistentIntrinsic%/, 'The base intrinsic of %NonExistentIntrinsic.prototype.property% is %NonExistentIntrinsic%'); + + st['throws'](function () { + GetIntrinsic('%NonExistentIntrinsicPrototype.property%'); + }, /%NonExistentIntrinsicPrototype%/, 'The base intrinsic of %NonExistentIntrinsicPrototype.property% is %NonExistentIntrinsicPrototype%'); + + st.end(); + }); + + t.end(); +}); + +test('accessors', { skip: !$gOPD || typeof Map !== 'function' }, function (t) { + var actual = $gOPD(Map.prototype, 'size'); + t.ok(actual, 'Map.prototype.size has a descriptor'); + t.equal(typeof actual.get, 'function', 'Map.prototype.size has a getter function'); + t.equal(GetIntrinsic('%Map.prototype.size%'), actual.get, '%Map.prototype.size% yields the getter for it'); + t.equal(GetIntrinsic('Map.prototype.size'), actual.get, 'Map.prototype.size yields the getter for it'); + + t.end(); +}); + +test('generator functions', { skip: !generatorFns.length }, function (t) { + var $GeneratorFunction = GetIntrinsic('%GeneratorFunction%'); + var $GeneratorFunctionPrototype = GetIntrinsic('%Generator%'); + var $GeneratorPrototype = GetIntrinsic('%GeneratorPrototype%'); + + forEach(generatorFns, function (genFn) { + var fnName = genFn.name; + fnName = fnName ? "'" + fnName + "'" : 'genFn'; + + t.ok(genFn instanceof $GeneratorFunction, fnName + ' instanceof %GeneratorFunction%'); + t.ok($isProto($GeneratorFunctionPrototype, genFn), '%Generator% is prototype of ' + fnName); + t.ok($isProto($GeneratorPrototype, genFn.prototype), '%GeneratorPrototype% is prototype of ' + fnName + '.prototype'); + }); + + t.end(); +}); + +test('async functions', { skip: !asyncFns.length }, function (t) { + var $AsyncFunction = GetIntrinsic('%AsyncFunction%'); + var $AsyncFunctionPrototype = GetIntrinsic('%AsyncFunctionPrototype%'); + + forEach(asyncFns, function (asyncFn) { + var fnName = asyncFn.name; + fnName = fnName ? "'" + fnName + "'" : 'asyncFn'; + + t.ok(asyncFn instanceof $AsyncFunction, fnName + ' instanceof %AsyncFunction%'); + t.ok($isProto($AsyncFunctionPrototype, asyncFn), '%AsyncFunctionPrototype% is prototype of ' + fnName); + }); + + t.end(); +}); + +test('async generator functions', { skip: asyncGenFns.length === 0 }, function (t) { + var $AsyncGeneratorFunction = GetIntrinsic('%AsyncGeneratorFunction%'); + var $AsyncGeneratorFunctionPrototype = GetIntrinsic('%AsyncGenerator%'); + var $AsyncGeneratorPrototype = GetIntrinsic('%AsyncGeneratorPrototype%'); + + forEach(asyncGenFns, function (asyncGenFn) { + var fnName = asyncGenFn.name; + fnName = fnName ? "'" + fnName + "'" : 'asyncGenFn'; + + t.ok(asyncGenFn instanceof $AsyncGeneratorFunction, fnName + ' instanceof %AsyncGeneratorFunction%'); + t.ok($isProto($AsyncGeneratorFunctionPrototype, asyncGenFn), '%AsyncGenerator% is prototype of ' + fnName); + t.ok($isProto($AsyncGeneratorPrototype, asyncGenFn.prototype), '%AsyncGeneratorPrototype% is prototype of ' + fnName + '.prototype'); + }); + + t.end(); +}); + +test('%ThrowTypeError%', function (t) { + var $ThrowTypeError = GetIntrinsic('%ThrowTypeError%'); + + t.equal(typeof $ThrowTypeError, 'function', 'is a function'); + t['throws']( + $ThrowTypeError, + TypeError, + '%ThrowTypeError% throws a TypeError' + ); + + t.end(); +}); + +test('allowMissing', { skip: asyncGenFns.length > 0 }, function (t) { + t['throws']( + function () { GetIntrinsic('%AsyncGeneratorPrototype%'); }, + TypeError, + 'throws when missing' + ); + + t.equal( + GetIntrinsic('%AsyncGeneratorPrototype%', true), + undefined, + 'does not throw when allowMissing' + ); + + t.end(); +}); diff --git a/gun-server/node_modules/gopd/.eslintrc b/gun-server/node_modules/gopd/.eslintrc new file mode 100644 index 0000000..e2550c0 --- /dev/null +++ b/gun-server/node_modules/gopd/.eslintrc @@ -0,0 +1,16 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "func-style": [2, "declaration"], + "id-length": 0, + "multiline-comment-style": 0, + "new-cap": [2, { + "capIsNewExceptions": [ + "GetIntrinsic", + ], + }], + }, +} diff --git a/gun-server/node_modules/gopd/.github/FUNDING.yml b/gun-server/node_modules/gopd/.github/FUNDING.yml new file mode 100644 index 0000000..94a44a8 --- /dev/null +++ b/gun-server/node_modules/gopd/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/gopd +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/gun-server/node_modules/gopd/CHANGELOG.md b/gun-server/node_modules/gopd/CHANGELOG.md new file mode 100644 index 0000000..f111eb1 --- /dev/null +++ b/gun-server/node_modules/gopd/CHANGELOG.md @@ -0,0 +1,25 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.1](https://github.com/ljharb/gopd/compare/v1.0.0...v1.0.1) - 2022-11-01 + +### Commits + +- [Fix] actually export gOPD instead of dP [`4b624bf`](https://github.com/ljharb/gopd/commit/4b624bfbeff788c5e3ff16d9443a83627847234f) + +## v1.0.0 - 2022-11-01 + +### Commits + +- Initial implementation, tests, readme [`0911e01`](https://github.com/ljharb/gopd/commit/0911e012cd642092bd88b732c161c58bf4f20bea) +- Initial commit [`b84e33f`](https://github.com/ljharb/gopd/commit/b84e33f5808a805ac57ff88d4247ad935569acbe) +- [actions] add reusable workflows [`12ae28a`](https://github.com/ljharb/gopd/commit/12ae28ae5f50f86e750215b6e2188901646d0119) +- npm init [`280118b`](https://github.com/ljharb/gopd/commit/280118badb45c80b4483836b5cb5315bddf6e582) +- [meta] add `auto-changelog` [`bb78de5`](https://github.com/ljharb/gopd/commit/bb78de5639a180747fb290c28912beaaf1615709) +- [meta] create FUNDING.yml; add `funding` in package.json [`11c22e6`](https://github.com/ljharb/gopd/commit/11c22e6355bb01f24e7fac4c9bb3055eb5b25002) +- [meta] use `npmignore` to autogenerate an npmignore file [`4f4537a`](https://github.com/ljharb/gopd/commit/4f4537a843b39f698c52f072845092e6fca345bb) +- Only apps should have lockfiles [`c567022`](https://github.com/ljharb/gopd/commit/c567022a18573aa7951cf5399445d9840e23e98b) diff --git a/gun-server/node_modules/gopd/LICENSE b/gun-server/node_modules/gopd/LICENSE new file mode 100644 index 0000000..6abfe14 --- /dev/null +++ b/gun-server/node_modules/gopd/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/gun-server/node_modules/gopd/README.md b/gun-server/node_modules/gopd/README.md new file mode 100644 index 0000000..784e56a --- /dev/null +++ b/gun-server/node_modules/gopd/README.md @@ -0,0 +1,40 @@ +# gopd [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +`Object.getOwnPropertyDescriptor`, but accounts for IE's broken implementation. + +## Usage + +```javascript +var gOPD = require('gopd'); +var assert = require('assert'); + +if (gOPD) { + assert.equal(typeof gOPD, 'function', 'descriptors supported'); + // use gOPD like Object.getOwnPropertyDescriptor here +} else { + assert.ok(!gOPD, 'descriptors not supported'); +} +``` + +[package-url]: https://npmjs.org/package/gopd +[npm-version-svg]: https://versionbadg.es/ljharb/gopd.svg +[deps-svg]: https://david-dm.org/ljharb/gopd.svg +[deps-url]: https://david-dm.org/ljharb/gopd +[dev-deps-svg]: https://david-dm.org/ljharb/gopd/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/gopd#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/gopd.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/gopd.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/gopd.svg +[downloads-url]: https://npm-stat.com/charts.html?package=gopd +[codecov-image]: https://codecov.io/gh/ljharb/gopd/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/gopd/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/gopd +[actions-url]: https://github.com/ljharb/gopd/actions diff --git a/gun-server/node_modules/gopd/index.js b/gun-server/node_modules/gopd/index.js new file mode 100644 index 0000000..fb6d3bb --- /dev/null +++ b/gun-server/node_modules/gopd/index.js @@ -0,0 +1,16 @@ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); + +var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true); + +if ($gOPD) { + try { + $gOPD([], 'length'); + } catch (e) { + // IE 8 has a broken gOPD + $gOPD = null; + } +} + +module.exports = $gOPD; diff --git a/gun-server/node_modules/gopd/package.json b/gun-server/node_modules/gopd/package.json new file mode 100644 index 0000000..d5e1fa4 --- /dev/null +++ b/gun-server/node_modules/gopd/package.json @@ -0,0 +1,71 @@ +{ + "name": "gopd", + "version": "1.0.1", + "description": "`Object.getOwnPropertyDescriptor`, but accounts for IE's broken implementation.", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "lint": "eslint --ext=js,mjs .", + "postlint": "evalmd README.md", + "pretest": "npm run lint", + "tests-only": "tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/gopd.git" + }, + "keywords": [ + "ecmascript", + "javascript", + "getownpropertydescriptor", + "property", + "descriptor" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/gopd/issues" + }, + "homepage": "https://github.com/ljharb/gopd#readme", + "dependencies": { + "get-intrinsic": "^1.1.3" + }, + "devDependencies": { + "@ljharb/eslint-config": "^21.0.0", + "aud": "^2.0.1", + "auto-changelog": "^2.4.0", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "in-publish": "^2.0.1", + "npmignore": "^0.3.0", + "safe-publish-latest": "^2.0.0", + "tape": "^5.6.1" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + } +} diff --git a/gun-server/node_modules/gopd/test/index.js b/gun-server/node_modules/gopd/test/index.js new file mode 100644 index 0000000..0376bfb --- /dev/null +++ b/gun-server/node_modules/gopd/test/index.js @@ -0,0 +1,35 @@ +'use strict'; + +var test = require('tape'); +var gOPD = require('../'); + +test('gOPD', function (t) { + t.test('supported', { skip: !gOPD }, function (st) { + st.equal(typeof gOPD, 'function', 'is a function'); + + var obj = { x: 1 }; + st.ok('x' in obj, 'property exists'); + + var desc = gOPD(obj, 'x'); + st.deepEqual( + desc, + { + configurable: true, + enumerable: true, + value: 1, + writable: true + }, + 'descriptor is as expected' + ); + + st.end(); + }); + + t.test('not supported', { skip: gOPD }, function (st) { + st.notOk(gOPD, 'is falsy'); + + st.end(); + }); + + t.end(); +}); diff --git a/gun-server/node_modules/gun/.dockerignore b/gun-server/node_modules/gun/.dockerignore new file mode 100755 index 0000000..d66a45b --- /dev/null +++ b/gun-server/node_modules/gun/.dockerignore @@ -0,0 +1,6 @@ +node_modules +radata +stats.radata +.git +.gitignore +*.md diff --git a/gun-server/node_modules/gun/.github/FUNDING.yml b/gun-server/node_modules/gun/.github/FUNDING.yml new file mode 100755 index 0000000..7648662 --- /dev/null +++ b/gun-server/node_modules/gun/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: amark +patreon: gunDB +open_collective: gun +ko_fi: # Replace with a single Ko-fi username +tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/gun-server/node_modules/gun/.github/workflows/ci.yml b/gun-server/node_modules/gun/.github/workflows/ci.yml new file mode 100755 index 0000000..2feccfe --- /dev/null +++ b/gun-server/node_modules/gun/.github/workflows/ci.yml @@ -0,0 +1,114 @@ +name: ci + +on: + - push + - pull_request + +jobs: + + test: + strategy: + matrix: + node-version: [ 14.x ] + os: [ ubuntu-latest ] + runs-on: ${{ matrix.os }} + steps: + + # checkout the code + - name: Checkout + uses: actions/checkout@v2 + + # verify the version in package.json matches the release tag + - name: Version + uses: tcurdt/action-verify-version-npm@master + + # setup the node version + - name: Setup Node ${{ matrix.node-version }} + uses: actions/setup-node@v1 + with: + node-version: ${{ matrix.node-version }} + + # cache node_modules if we can + - name: Cache + id: cache-modules + uses: actions/cache@v2 + with: + path: node_modules + key: ${{ matrix.node-version }}-${{ runner.OS }}-build-${{ hashFiles('package.json') }} + + # ottherweise run install + - name: Install + if: steps.cache-modules.outputs.cache-hit != 'true' + run: npm install + + # run tests + - name: Test + run: npm test + + # create github release + release: + if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v') + needs: [ test ] + runs-on: ubuntu-latest + steps: + + # create github release (which triggers the release workflows) + - name: Release + uses: softprops/action-gh-release@v1 + # env: + # GITHUB_TOKEN: ${{ secrets.PAT }} + +# # publish latest master or release to dockerhub +# dockerhub: +# if: github.event_name == 'push' +# needs: [ test ] +# runs-on: ubuntu-latest +# env: +# image: ${{ secrets.DOCKERHUB_USERNAME }}/gun +# steps: + +# - name: Checkout +# uses: actions/checkout@v2 + +# - name: Login +# env: +# DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }} +# DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }} +# run: echo -n ${{ secrets.DOCKERHUB_TOKEN }} | docker login -u ${{ secrets.DOCKERHUB_USERNAME }} --password-stdin + +# - name: Build +# run: | +# echo "SHA=$GITHUB_SHA" +# docker build --build-arg SHA=$GITHUB_SHA \ +# BUILD_DATE=$(date +'%Y-%m-%dT%H:%M:%S') \ +# VCS_REF=${GITHUB_REF} \ +# VCS_URL=${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY} \ +# VERSION=${GITHUB_REF##*/} \ +# SHA=$GITHUB_SHA \ +# --label "SHA=$GITHUB_SHA" \ +# --tag ${{ env.image }}:${GITHUB_REF##*/} \ +# --tag ${{ env.image }}:latest \ +# . + +# - name: Push +# run: docker push ${{ env.image }} + + + # publish release to npm + npm: + if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v') + needs: [ test ] + # needs: [ release ] + runs-on: ubuntu-latest + steps: + + - name: Checkout + uses: actions/checkout@v2 + + - name: Publish + env: + NPM_AUTH_TOKEN: ${{ secrets.NPM_AUTH_TOKEN }} + run: | + npm config set //registry.npmjs.org/:_authToken=$NPM_AUTH_TOKEN + npm install + npm publish --access=public diff --git a/gun-server/node_modules/gun/.prettierignore b/gun-server/node_modules/gun/.prettierignore new file mode 100755 index 0000000..f59ec20 --- /dev/null +++ b/gun-server/node_modules/gun/.prettierignore @@ -0,0 +1 @@ +* \ No newline at end of file diff --git a/gun-server/node_modules/gun/.travis.yml b/gun-server/node_modules/gun/.travis.yml new file mode 100755 index 0000000..46f76dd --- /dev/null +++ b/gun-server/node_modules/gun/.travis.yml @@ -0,0 +1,10 @@ +language: node_js +branches: + except: + - debug + - manhattan +node_js: + - 10 +cache: + directories: + - node_modules diff --git a/gun-server/node_modules/gun/CHANGELOG.md b/gun-server/node_modules/gun/CHANGELOG.md new file mode 100755 index 0000000..37a3623 --- /dev/null +++ b/gun-server/node_modules/gun/CHANGELOG.md @@ -0,0 +1,113 @@ +# CHANGELOG + +## 0.2020.x + +`>0.2020.520` may break in-process `gun1` `gun2` message passing. Check `test/common.js` "Check multi instance message passing" for a hint and/or complain on community chat. + + - No breaking changes to core API. + - Storage adapter `put` event breaking change (temporary?), RAD is official now and storage adapters should be RAD plugins instead of GUN adapters. + - GUN soul format changed from being a random UUID to being a more predictable graph path (of where initially created) to support even better offline behavior. This means `null`ing & replacing an object will not create a new but re-merge. + - Pretty much all internal GUN utility will be deleted, these are mostly undocumented but will affect some people - they will still be available as a separate file but deprecated. + - As the DHT gets implemented, your relay peers may automatically connect to it, so do not assume your peer is standalone. `Gun({axe: false` should help prevent this but loses you most scaling properties. + - The 2019 -> 2020 "changes" are happening gradually, based on experimental in-production tests. + - As always, **most important** is to ask in the [community chat](http://chat.gun.eco) if you have any issues, and to keep up to date with changes. + +## 0.2019.x + +Some RAD & SEA data format changes, but with as much backward compatibility as possible, tho ideally should be dropped. + +## 0.9.x + +No breaking changes, but the new Radix Storage Engine (RSE) has been finally integrated and works with S3 as a backup. + +// Edit: commentary removed. + +## 0.8.x + +Adapter interfaces have changed from `Gun.on('event', cb)` to `gun.on('event', cb)`, this will force adapters to be instance specific. + +`.path()` and `.not()` have been officially removed from the core bundle, you can bundle them yourself at `lib/path.js` and `lib/not.js` if you still need them. + +## 0.7.x + +Small breaking change to `.val(cb)`: + +Previously `.val(cb)` would ONLY be called when data exists, like `.on(cb)`. + +However, due to popular demand, people wanted `.val(cb)` to also get called for `.not(cb)` rather than (before) it would "wait" until data arrived. + +NOTE: For dynamic paths, `.val(cb)` will still wait, like: + +`gun.get('users').map().val(cb)` because the behavior of the `map()` is simply to not fire anything down the chain unless items are found. + +## 0.6.x + +Introduced experimental features, chaining `.val()` (no callback) and `.map(cb)` behaving as a map/reduce function. + +It also upgraded the socket adapters and did end-to-end load testing and correctness testing. + +## 0.5.9 + +GUN 0.3 -> 0.4 -> 0.5 Migration Guide: +`gun.back` -> `gun.back()`; +`gun.get(key, cb)` -> cb(err, data) -> cb(at) at.err, at.put; +`gun.map(cb)` -> `gun.map().on(cb)`; +`gun.init` -> deprecated; +`gun.put(data, cb)` -> cb(err, ok) -> cb(ack) ack.err, ack.ok; +`gun.get(key)` global/absolute -> `gun.back(-1).get(key)`; +`gun.key(key)` -> temporarily broken; + +## 0.3.7 + + - Catch localStorage errors. + +## 0.3.6 + + - Fixed S3 typo. + +## 0.3.5 + + - Fixed server push. + +## 0.3.4 + + - Breaking Change! `list.set(item)` returns the item's chain now, not the list chain. + - Client and Server GUN servers are now more up to spec, trimmed excess HTTP/REST header data. + - Gun.is.lex added. + +## 0.3.3 + +- You can now link nodes natively, `gun.get('mark').path('owner').put(gun.get('cat'))`! +- Sets (or tables, collections, lists) are now easily done with `gun.get('users').set(gun.get('person/mark'))`. + +## 0.3.2 + +Bug fixes. + +## 0.3.1 + +Bug fixes. + +## 0.3 + +Migration Guide! Migrate by changing `.attach(` to `.wsp(` on your server if you have one with gun. Remove `.set()` (delete it), and change `.set($DATA)` (where you call set with something) to `.path('I' + Date.now() + 'R' + Gun.text.random(5)).put($DATA)`. If you have NodeJS style callbacks in your `.get` (which documentation previously recommended that you shouldn't) they previous took `err, graph` and now they take `err, node` (which means now using callback style is fine to use). Inside of `.not()` no longer use `return` or `this`, instead (probably) use `gun` and no `return`. If you are a module developer, use `opt.wire` now instead of `opt.hooks` and message Mark since he needs to talk to you since the wire protocol has changed. + +- Server side default `.wsp()` renamed from `.attach()`. +- `.set()` deprecated because it did a bunch of random inconsistent things. Its useful behavior has now become implicit (see below) or can be done explicitly. +- `.not()` it was previously common to `return` the chain inside of .not, beware that if you have code like `gun.get(key).not(function(){ return this.put({}).key(key) }).val()` cause `.val()` to be triggered twice (this is intentional, because it funnels two separate chains together) which previously didn't happen. To fix this, just don't return the chain. +- `.put()` and `.path()` do implicit `.init()` by default, turn on explicit behavior with `Gun({init: true})`. +- `.get(soul, cb)` cb is called back with `err, node` rather than `err, graph`. +- Options `opt.wire` renamed from `opt.hooks`. +- `.val()` when called empty automatically cleanly logs for convenience purposes. +- `.init()` added. +- `Gun.is.val` renamed from `Gun.is.value`. +- `Gun.is.rel` renamed from `Gun.is.soul`. +- `Gun.is.node.soul` renamed from `Gun.is.soul.on`. +- `Gun.union.ify` renamed from `Gun.union.pseudo`. +- `Gun.union.HAM` renamed from `Gun.HAM`. +- `Gun.HAM` is now the actual HAM function for conflict resolution. +- `Gun._.state` renamed from `Gun._.HAM`. +- Maximum Callstack Exceeded is less problematic now, unless you intentionally choke the thread. #95 +- Putting a regex or Date or NaN is actually detected and causes an error now while before it was silent. #122 #123 +- `.on()` gets called when a key is later newly made while before it did not. #116 +- `.val()` should not ever get called with a relation alone (internals should resolve it), this is fixed. #132 diff --git a/gun-server/node_modules/gun/Dockerfile b/gun-server/node_modules/gun/Dockerfile new file mode 100755 index 0000000..b5ba619 --- /dev/null +++ b/gun-server/node_modules/gun/Dockerfile @@ -0,0 +1,35 @@ +# install packages +FROM node:14-alpine as builder +RUN mkdir /work +WORKDIR /work +RUN apk add --no-cache alpine-sdk python3 +COPY package*.json ./ +RUN mkdir -p node_modules +RUN npm ci --only=production + +# fresh image without dev packages +FROM node:14-alpine +# build-time metadata as defined at http://label-schema.org +ARG BUILD_DATE +ARG VCS_REF +ARG VCS_URL +ARG VERSION +LABEL org.label-schema.build-date=$BUILD_DATE \ + org.label-schema.name="Gun - Offline First, Javascript Graph Database" \ + org.label-schema.url="http://gun.js.org" \ + org.label-schema.vcs-ref=$VCS_REF \ + org.label-schema.vcs-url=$VCS_URL \ + org.label-schema.vendor="The Gun Database Team" \ + org.label-schema.version=$VERSION \ + org.label-schema.schema-version="1.0" +ARG SHA +RUN mkdir /work +WORKDIR /work +COPY --from=builder /work/node_modules ./node_modules +RUN npm rebuild -q +ADD . . +RUN echo "{ \"sha\": \"$SHA\" }" > version.json +RUN cat version.json +EXPOSE 8080 +EXPOSE 8765 +CMD ["npm","start"] diff --git a/gun-server/node_modules/gun/LICENSE.md b/gun-server/node_modules/gun/LICENSE.md new file mode 100755 index 0000000..5389a33 --- /dev/null +++ b/gun-server/node_modules/gun/LICENSE.md @@ -0,0 +1,55 @@ +Copyright (c) 2015 Mark Nadal + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +--- + +Copyright (c) 2015 Mark Nadal + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgement in the product documentation would be + appreciated but is not required. +2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. +3. This notice may not be removed or altered from any source distribution. + +--- + +Copyright 2015 Mark Nadal + +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. diff --git a/gun-server/node_modules/gun/Procfile b/gun-server/node_modules/gun/Procfile new file mode 100755 index 0000000..d3c78cb --- /dev/null +++ b/gun-server/node_modules/gun/Procfile @@ -0,0 +1 @@ +web: node --inspect examples/http.js \ No newline at end of file diff --git a/gun-server/node_modules/gun/README.md b/gun-server/node_modules/gun/README.md new file mode 100755 index 0000000..ca8796b --- /dev/null +++ b/gun-server/node_modules/gun/README.md @@ -0,0 +1,323 @@ +

      + +[![](https://data.jsdelivr.com/v1/package/gh/amark/gun/badge?style=rounded)](https://data.jsdelivr.com/v1/package/gh/amark/gun/stats) +![Build](https://github.com/amark/gun/actions/workflows/ci.yml/badge.svg) +[![Gitter](https://img.shields.io/gitter/room/amark/gun.js.svg)](http://chat.gun.eco) + +**GUN** is an [ecosystem](https://gun.eco/docs/Ecosystem) of **tools** that let you build [community run](https://www.nbcnews.com/tech/tech-news/these-technologists-think-internet-broken-so-they-re-building-another-n1030136) and [encrypted applications](https://gun.eco/docs/Cartoon-Cryptography) - like an Open Source Firebase or a Decentralized Dropbox. + +The [Internet Archive](https://news.ycombinator.com/item?id=17685682) and [100s of other apps](https://github.com/amark/gun/wiki/awesome-gun) run GUN in-production. GUN is also part of [Twitter's Bluesky](https://blueskycommunity.net/) initiative! + + + Multiplayer by default with realtime p2p state synchronization! + + Graph data lets you use key/value, tables, documents, videos, & more! + + Local-first, offline, and decentralized with end-to-end encryption. + +Decentralized alternatives to [Zoom](https://www.zdnet.com/article/era-hatches-meething-an-open-source-browser-based-video-conferencing-system/), [Reddit](https://notabug.io/t/whatever/comments/36588a16b9008da4e3f15663c2225e949eca4a15/gpu-bot-test), [Instagram](https://iris.to/), [Slack](https://iris.to/), [YouTube](https://d.tube/), [Stripe](https://twitter.com/marknadal/status/1422717427427647489), [Wikipedia](https://news.ycombinator.com/item?id=17685682), Facebook [Horizon](https://twitter.com/marknadal/status/1424476179189305347) and more have already pushed terabytes of daily P2P traffic on GUN. We are a [friendly community](http://chat.gun.eco/) creating a [free fun future for freedom](https://youtu.be/1HJdrBk3BlE): + + + + + + + + + + + + + + + + + +
      + +## Quickstart + +GUN is *super easy* to get started with: + + - Try the [interactive tutorial](https://gun.eco/docs/Todo-Dapp) in the browser (**5min** ~ average developer). + - Or `npm install gun` and run the examples with `cd node_modules/gun && npm start` (**5min** ~ average developer). + +> **Note:** If you don't have [node](http://nodejs.org/) or [npm](https://www.npmjs.com/), read [this](https://github.com/amark/gun/blob/master/examples/install.sh) first. +> If the `npm` command line didn't work, you may need to `mkdir node_modules` first or use `sudo`. + +- An online demo of the examples are available here: http://gunjs.herokuapp.com/ +- Or write a quick app: ([try now in a playground](https://jsbin.com/kadobamevo/edit?js,console)) +```html + + +``` +- Or try something **mind blowing**, like saving circular references to a table of documents! ([play](http://jsbin.com/wefozepume/edit?js,console)) +```javascript +cat = {name: "Fluffy", species: "kitty"}; +mark = {boss: cat}; +cat.slave = mark; + +// partial updates merge with existing data! +gun.get('mark').put(mark); + +// access the data as if it is a document. +gun.get('mark').get('boss').get('name').once(function(data, key){ + // `once` grabs the data once, no subscriptions. + console.log("Mark's boss is", data); +}); + +// traverse a graph of circular references! +gun.get('mark').get('boss').get('slave').once(function(data, key){ + console.log("Mark is the cat's slave!", data); +}); + +// add both of them to a table! +gun.get('list').set(gun.get('mark').get('boss')); +gun.get('list').set(gun.get('mark')); + +// grab each item once from the table, continuously: +gun.get('list').map().once(function(data, key){ + console.log("Item:", data); +}); + +// live update the table! +gun.get('list').set({type: "cucumber", goal: "jumping cat"}); +``` + +Want to keep building more? **Jump to [THE DOCUMENTATION](#documentation)!** + +# About +First & foremost, GUN is **a community of the nicest and most helpful people** out there. So [I want to invite you](http://chat.gun.eco) to come tell us about what **you** are working on & wanting to build (new or old school alike! Just be nice as well.) and ask us your questions directly. :) + +


      Watch the 100 second intro!

      + +The GUN ecosystem stack is a collection of independent and modular tools covering everything from [CRDT](https://crdt.tech/) [conflict resolution](https://gun.eco/distributed/matters.html), [cryptographic security](https://gun.eco/docs/Cartoon-Cryptography) & [encryption](https://gun.eco/docs/SEA), [radix storage serialization](https://gun.eco/docs/RAD), [mesh networking](https://gun.eco/docs/DAM) & [routing algorithms](https://gun.eco/docs/Routing), to distributed systems [correctness & load testing](https://github.com/gundb/panic-server), CPU scheduled [JSON parser](https://github.com/amark/gun/blob/master/lib/yson.js) to prevent UI lag, and more! + +
      +
      + +On that note, let's get some official shout outs covered first: + +### Support + +

      +Thanks to: + + + + + + + + + + + + +
                   
      + +Robert Heessels, +Lorenzo Mangani, +NLnet Foundation, +Sam Liu, +Daniel Dombrowsky, +Vincent Woo, +AJ ONeal, +Bill Ottman, +Mike Lange, +Sean Matheson, +Alan Mimms, +Dário Freire, +John Williamson, +Robin Bron, +Elie Makhoul, +Mike Staub, +Bradley Matusiak, +Jeff Cook, +Nico, +Aaron Artille, +Tim Robinson, +Fabian Stamm, +Mike Staub, +Hunter Owens, +Jacob Millner, +Gerrit Balindt, +Gabriel Lemon +

      + + - Join others in sponsoring code: https://www.patreon.com/gunDB ! + - Ask questions: http://stackoverflow.com/questions/tagged/gun ? + - Found a bug? Report at: https://github.com/amark/gun/issues ; + - **Need help**? Chat with us: http://chat.gun.eco . + +### History + +[GUN](https://gun.eco) was created by [Mark Nadal](https://twitter.com/marknadal) in 2014 after he had spent 4 years trying to get his collaborative web app to scale up with traditional databases. + + After he realized [Master-Slave database architecture causes one big bottleneck](https://gun.eco/distributed/matters.html), he (as a complete newbie outsider) naively decided **to question the status quo** and shake things up with controversial, heretical, and contrarian experiments: + +**The NoDB** - no master, no servers, no "single source of truth", not built with a real programming language or real hardware, no DevOps, no locking, not *just* SQL or NoSQL but both (**all** - graphs, documents, tables, key/value). + +The goal was to build a P2P database that could survive living inside **any** browser, and could correctly sync data between **any** device after assuming **any** offline-first activity. + + + +Technically, **GUN is a graph synchronization protocol** with a *lightweight embedded engine*, capable of doing *[20M+ API ops/sec](https://gun.eco/docs/Performance)* in **just ~9KB gzipped size**. + +## Documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + +

      API reference

      Tutorials

      Examples

      GraphQL

      Electron

      React & Native

      Vue

      Svelte

      Webcomponents

      CAP Theorem Tradeoffs

      How Data Sync Works

      How GUN is Built

      Crypto Auth

      Modules

      Roadmap

      + +This would not be possible without **community contributors**, big shout out to: + +**[ajmeyghani](https://github.com/ajmeyghani) ([Learn GUN Basics with Diagrams](https://medium.com/@ajmeyghani/gundb-a-graph-database-in-javascript-3860a08d873c))**; **[anywhichway](https://github.com/anywhichway) ([Block Storage](https://github.com/anywhichway/gun-block))**; **[beebase](https://github.com/beebase) ([Quasar](https://github.com/beebase/gun-vuex-quasar))**; **[BrockAtkinson](https://github.com/BrockAtkinson) ([brunch config](https://github.com/BrockAtkinson/brunch-gun))**; **[Brysgo](https://github.com/brysgo) ([GraphQL](https://github.com/brysgo/graphql-gun))**; **[d3x0r](https://github.com/d3x0r) ([SQLite](https://github.com/d3x0r/gun-db))**; **[forrestjt](https://github.com/forrestjt) ([file.js](https://github.com/amark/gun/blob/master/lib/file.js))**; **[hillct](https://github.com/hillct) (Docker)**; **[JosePedroDias](https://github.com/josepedrodias) ([graph visualizer](http://acor.sl.pt:9966))**; **[JuniperChicago](https://github.com/JuniperChicago) ([cycle.js bindings](https://github.com/JuniperChicago/cycle-gun))**; **[jveres](https://github.com/jveres) ([todoMVC](https://github.com/jveres/todomvc))**; **[kristianmandrup](https://github.com/kristianmandrup) ([edge](https://github.com/kristianmandrup/gun-edge))**; **[Lightnet](https://github.com/Lightnet)** ([Awesome Vue User Examples](https://glitch.com/edit/#!/jsvuegunui?path=README.md:1:0) & [User Kitchen Sink Playground](https://gdb-auth-vue-node.glitch.me/)); **[lmangani](https://github.com/lmangani) ([Cytoscape Visualizer](https://github.com/lmangani/gun-scape), [Cassandra](https://github.com/lmangani/gun-cassandra), [Fastify](https://github.com/lmangani/fastify-gundb), [LetsEncrypt](https://github.com/lmangani/polyGun-letsencrypt))**; **[mhelander](https://github.com/mhelander) ([SEA](https://github.com/amark/gun/blob/master/sea.js))**; [omarzion](https://github.com/omarzion) ([Sticky Note App](https://github.com/omarzion/stickies)); [PsychoLlama](https://github.com/PsychoLlama) ([LevelDB](https://github.com/PsychoLlama/gun-level)); **[RangerMauve](https://github.com/RangerMauve) ([schema](https://github.com/gundb/gun-schema))**; **[robertheessels](https://github.com/swifty) ([gun-p2p-auth](https://github.com/swifty/gun-p2p-auth))**; **[rogowski](https://github.com/rogowski) (AXE)**; [sbeleidy](https://github.com/sbeleidy); **[sbiaudet](https://github.com/sbiaudet) ([C# Port](https://github.com/sbiaudet/cs-gun))**; **[Sean Matheson](https://github.com/ctrlplusb) ([Observable/RxJS/Most.js bindings](https://github.com/ctrlplusb/gun-most))**; **[Shadyzpop](https://github.com/Shadyzpop) ([React Native example](https://github.com/amark/gun/tree/master/examples/react-native))**; **[sjones6](https://github.com/sjones6) ([Flint](https://github.com/sjones6/gun-flint))**; RIP **[Stefdv](https://github.com/stefdv) (Polymer/web components)**; **[zrrrzzt](https://github.com/zrrrzzt) ([JWT Auth](https://gist.github.com/zrrrzzt/6f88dc3cedee4ee18588236756d2cfce))**; **[xmonader](https://github.com/xmonader) ([Python Port](https://github.com/xmonader/pygundb))**; + +I am missing many others, apologies, will be adding them soon! This list is infintiely old & way out of date, if you want to be listed in it please make a PR! :) + +## Testing + +You will need to `npm install -g mocha` first. Then in the gun root folder run `npm test`. Tests will trigger persistent writes to the DB, so subsequent runs of the test will fail. You must clear the DB before running the tests again. This can be done by running `rm -rf *data*` command in the project directory. + +## Shims + + > These are only needed for NodeJS & React Native, they shim the native Browser WebCrypto API. + +If you want to use [SEA](https://gun.eco/docs/SEA) for `User` auth and security, you will need to install: + +`npm install @peculiar/webcrypto --save` + +Please see [our React Native docs](https://gun.eco/docs/React-Native) for installation instructions! + +Then you can require [SEA](https://gun.eco/docs/SEA) without an error: + +```javascript +GUN = require('gun/gun'); +SEA = require('gun/sea'); +``` + +## Deploy + + > Note: The default examples that get auto-deployed on `npm start` CDN-ify all GUN files, modules, & storage. + + > Note: Moving forward, AXE will start to automatically cluster your peer into a shared DHT. You may want to disable this to run an isolated network. + + > Note: When deploying a web application using GUN on a cloud provider, you may have to set `CI=false` in your `.env`. This prevents GUN-specific warnings from being treated as errors when deploying your app. You may also resolve this by modifying your webpack config to not try to build the GUN dependencies. + +To quickly spin up a GUN relay peer for your development team, utilize [Heroku](http://heroku.com), [Docker](http://docker.com), or any others listed below. Or some variant thereof [Dokku](http://dokku.viewdocs.io/dokku/), K8s, etc. ! Or use all of them so your relays are decentralized too! + +### Linux + +`SSH` into the home directory of a clean OS install with `sudo` ability. Set any environment variables you need (see below), then do: + +```bash +curl -o- https://raw.githubusercontent.com/amark/gun/master/examples/install.sh | bash +``` + + > Read [install.sh](https://github.com/amark/gun/blob/master/examples/install.sh) first! + > If `curl` is not found, *copy&paste* the contents of install.sh into your ssh. + +You can now safely `CTRL+A+D` to escape without stopping the peer. To stop everything `killall screen` or `killall node`. + +Environment variables may need to be set like `export HTTPS_CERT=~/cert.pem HTTPS_KEY=~/key.pem PORT=443`. You can also look at a sample [nginx](https://gun.eco/docs/nginx) config. For production deployments, you probably will want to use something like `pm2` or better to keep the peer alive after machine reboots. + +### [Heroku](https://www.heroku.com/) + +[![Deploy](https://www.herokucdn.com/deploy/button.svg)](https://heroku.com/deploy?template=https://github.com/amark/gun) + + > Heroku deletes your data every 15 minutes, one way to fix this is by adding [cheap storage](https://gun.eco/docs/Using-Amazon-S3-for-Storage). + +Or: + +```bash +git clone https://github.com/amark/gun.git +cd gun +heroku create +git push -f heroku HEAD:master +``` + +Then visit the URL in the output of the 'heroku create' step, in a browser. Make sure to set any environment config vars in the settings tab. + +### [Zeet.co](https://www.zeet.co/) + +[![Deploy](https://deploy.zeet.co/gun.svg)](https://deploy.zeet.co/?url=https://github.com/amark/gun) + +Then visit the URL in the output of the 'now --npm' step, in your browser. + +### [Docker](https://www.docker.com/) + + > Warning: Docker image is community contributed and may be old with missing security updates, please check version numbers to compare. + +[![Docker Automated build](https://img.shields.io/docker/automated/gundb/gun.svg)](https://hub.docker.com/r/gundb/gun/) [![](https://images.microbadger.com/badges/image/gundb/gun.svg)](https://microbadger.com/images/gundb/gun "Get your own image badge on microbadger.com") [![Docker Pulls](https://img.shields.io/docker/pulls/gundb/gun.svg)](https://hub.docker.com/r/gundb/gun/) [![Docker Stars](https://img.shields.io/docker/stars/gundb/gun.svg)](https://hub.docker.com/r/gundb/gun/) + +Pull from the [Docker Hub](https://hub.docker.com/r/gundb/gun/) [![](https://images.microbadger.com/badges/commit/gundb/gun.svg)](https://microbadger.com/images/gundb/gun). Or: + +```bash +docker run -p 8765:8765 gundb/gun +``` + +Or build the [Docker](https://docs.docker.com/engine/installation/) image locally: + +```bash +git clone https://github.com/amark/gun.git +cd gun +docker build -t myrepo/gundb:v1 . +docker run -p 8765:8765 myrepo/gundb:v1 +``` + +Or, if you prefer your Docker image with metadata labels (Linux/Mac only): + +```bash +npm run docker +docker run -p 8765:8765 username/gun:git +``` + +Then visit [http://localhost:8765](http://localhost:8765) in your browser. + +## License + +Designed with ♥ by Mark Nadal, the GUN team, and many amazing contributors. + +Openly licensed under [Zlib / MIT / Apache 2.0](https://github.com/amark/gun/blob/master/LICENSE.md). + +[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Famark%2Fgun.svg?size=large)](https://app.fossa.io/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Famark%2Fgun?ref=badge_large) + +[YouTube](https://www.youtube.com/channel/UCQAtpf-zi9Pp4__2nToOM8g) . [Twitter](https://twitter.com/marknadal) diff --git a/gun-server/node_modules/gun/RELEASE.md b/gun-server/node_modules/gun/RELEASE.md new file mode 100755 index 0000000..8fb6bc1 --- /dev/null +++ b/gun-server/node_modules/gun/RELEASE.md @@ -0,0 +1,25 @@ +Every push or pull request will + + - run the tests + +Every push to master will + + - run the tests + - publish the latest docker image to dockerhub + +Creating a tag that starts with `v` will + + - create a new github release + - publish the release to npm + - publish the release to dockerhub + +Creating a release from the github web interface will + + - publish the release to npm + - publish the release to dockerhub + +Creating the release for version `0.2021.001` from the command line works as follows + + git tag v0.2021.001 + git push --tags + diff --git a/gun-server/node_modules/gun/app.json b/gun-server/node_modules/gun/app.json new file mode 100755 index 0000000..b1dc3db --- /dev/null +++ b/gun-server/node_modules/gun/app.json @@ -0,0 +1,18 @@ +{ + "name": "gun-server", + "website": "http://gun.eco/", + "repository": "https://github.com/amark/gun", + "logo": "https://avatars3.githubusercontent.com/u/8811914", + "keywords": ["node", "gun", "gunDB", "database","graph","offline-first"], + "description": "Javascript, Offline-First Javascript Graph Database Server Peer", + "env": { + "NPM_CONFIG_PRODUCTION": { + "description": "If you do not want default features, set to \"true\".", + "value": "false" + }, + "PEERS": { + "description": "Comma-separated list of peer urls to connect to", + "required": false + } + } +} diff --git a/gun-server/node_modules/gun/as.js b/gun-server/node_modules/gun/as.js new file mode 100755 index 0000000..9be7c33 --- /dev/null +++ b/gun-server/node_modules/gun/as.js @@ -0,0 +1,239 @@ +;(function(){ + function as(el, gun, cb, opt){ + el = $(el); + if(gun === as.gui && as.el && as.el.is(el)){ return } + + opt = opt || {}; + opt.match = opt.match || '{{ '; + opt.end = opt.end || ' }}'; + ;(function(){ // experimental + function nest(t, s,e, r, i,tmp,u){ + if(r && !r.length){ return t||'' } + if(!t){ return [] } + e = e || s; + i = t.indexOf(s, i||0); + if(0 > i){ return [] } + tmp = t.indexOf(e, i+1); + if(!r){ return [t.slice(i+s.length, tmp)].concat(nest(t, s,e, r, tmp,tmp,u)) } + return t.slice(0,i)+r[0]+nest(t.slice(tmp+e.length), s,e, r.slice(1), 0,tmp,u); + } + + /* experimental */ + function template(tag, attr){ + var html = (tag = $(tag))[0].outerHTML, sub, tmp; + if(html && (0 > html.indexOf(opt.match))){ return } + if(!attr){ + $.each(tag[0].attributes, function(i,v){ + if(!v){ return } + if(!nest(v.value, opt.match, opt.end).length){ return } + template(tag, v.name) + }); + if((sub = tag.children()).length){ + return sub.each(function(){ template(this) }); + } + } + var data = [], plate = attr? tag.attr(attr) : tag.html(); + tmp = nest(plate, opt.match, opt.end); + if(!tmp.length){ return } + $.each(tmp, function(pos, match){ + var expr = match.split(' '); + var path = (expr[0]).split('.'); + if(expr = expr.slice(1).join(' ')){ + expr = new Function("_", "b", "return (_)" + expr); + } + var val = (expr && expr('')) || ''; + data.push(val); + if(!attr){ tag.text(val) } + + var ref = gun, sup = [], tmp; + if(tmp = tag.attr('name')){ sup.push(tmp) } + tag.parents("[name]").each(function(){ + sup.push($(this).attr('name')); + }); + $.each(path = sup.reverse().concat(path), function(i,v){ + ref = ref.get(v); + }); + ref.on(function(v){ + v = data[pos] = expr? expr(v) : v; + var tmp = nest(plate, opt.match, opt.end, data); + if(attr){ + tag.attr(attr, tmp); + } else { + tag.text(tmp); + } + }); + }); + } + template(el); + + }()); + + as.gui = gun; + as.el = el; + if(el.data('as')){ + el.html(el.data('as').fresh); + } else { + el.data('as', { + fresh: el.html() + }) + } + el.find("[name]").each(function(){ + if($(this).find("[name]").length){ return } + var name = $(this), + parents = name.parents("[name]"), + path = [], + ref = gun; + + path.push(name.attr('name')); + parents.each(function(){ + path.push($(this).attr('name')); + }); + path = path.reverse(); + + path.forEach(function(key){ + if('#' === key){ + ref = ref.map() + } else { + ref = ref.get(key); + } + }); + + var many = path.slice().reverse().indexOf('#'), model; + many = (0 < ++many)? many : false; + if(many){ + model = name.closest("[name='#']"); + model = model.data('model') || model.data('model', {$: model.clone(), on: model.parent(), has: {}}).hide().data('model'); + } + + ref.get(function(at){ + var data = at.put, key = at.get, gui = at.gun || at.$, ui = name, back; + if(model){ + ui = model.has[(gui._).id]; + if(!ui){ + back = gui.back(many - 1); + ui = model.has[(back._).id]; + if(!ui){ + if(!(back._).get){ return } + ui = (model.has[(back._).id] = model.$.clone(true).prependTo(model.on)); + } + ui = ui.find("[name='"+key+"']").first(); + model.has[(gui._).id] = ui; + } + } + ui.data('gun', gui); + if(ui.data('was') === data){ return } + if(many && ui.is('.sort')){ + var up = ui.closest("[name='#']"); + var tmp = as.sort(data, up.parent().children().last()); + tmp? up.insertAfter(tmp) : up.prependTo(up.parent()); + } + if(as.lock === gui){ return } + if(!(data && data instanceof Object)){ + (ui[0] && u === ui[0].value)? ui.text(data) : ui.val(data); + } + ui.data('was', data); + if(cb){ + cb(data, key, ui); + } + }); + }); + } + as.wait = function(cb, wait, to){ + return function(a,b,c){ + var me = as.typing = this; + clearTimeout(to); + to = setTimeout(function(){ + cb.call(me, a,b,c); + as.typing = me = false; + }, wait || 200); + } + } + as.sort = function sort(num, li){ return parseFloat(num) >= parseFloat($(li).find('.sort').text() || -Infinity)? li : sort(num, li.prev()) } + $(document).on('keyup', 'input, textarea, [contenteditable]', as.wait(function(){ + var el = $(this); + var data = (el[0] && u === el[0].value)? el.text() : el.val(); + var g = el.data('gun'); + if(!g){ return } + as.lock = g; + g.put(data); + }, 99)); + //$(document).on('submit', 'form', function(e){ e.preventDefault() }); + var u; + window.as = as; + $.as = as; +}()); + +;(function(){ + $(document).on('click', 'a, button', function(e){ + var tmp = $(this).attr('href') || ''; + if(0 === tmp.indexOf('http')){ return } + e.preventDefault(); + r(tmp); + }); + function r(href){ + if(!href){ return } + if(href[0] == '#'){ href = href.slice(1) } + var h = href.split('/')[0]; + $('.page').hide(); + $('#' + h).show(); + if(r.on === h){ return } + location.hash = href; + (r.page[h] || {on:function(){}}).on(); + r.on = h; + return r; + }; + r.page = function(h, cb){ + r.page[h] = r.page[h] || {on: cb}; + return r; + } + r.render = function(id, model, onto, data){ + var $data = $( + $('#' + id).get(0) || + $('.model').find(model).clone(true).attr('id', id).appendTo(onto) + ); + $.each(data, function(field, val){ + if($.isPlainObject(val)){ return } + $data.find("[name='" + field + "']").val(val).text(val); + }); + return $data; + } + window.onhashchange = function(){ r(location.hash.slice(1)) }; + $.as && ($.as.route = r); + if(window.as){ + as.route = r; + } else { + $.route = r; + } +}()); + +;$(function(){ + $('.page').not(':first').hide(); + $.as.route(location.hash.slice(1)); + $(JOY.start = JOY.start || function(){ $.as(document, gun, null, JOY.opt) }); + + if($('body').attr('peers')){ (console.warn || console.log)('Warning: Please upgrade to https://github.com/eraeco/joydb#peers !') } + +}); +;(function(){ // need to isolate into separate module! + var joy = window.JOY = function(){}; + joy.auth = function(a,b,cb,o){ + if(!o){ o = cb ; cb = 0 } + if(o === true){ + gun.user().create(a, b); + return; + } + gun.user().auth(a,b, cb,o); + } + + var opt = joy.opt = window.CONFIG || {}, peers; + $('link[type=peer]').each(function(){ (peers || (peers = [])).push($(this).attr('href')) }); + !window.gun && (opt.peers = opt.peers || peers || (function(){ + (console.warn || console.log)('Warning: No peer provided, defaulting to DEMO peer. Do not run in production, or your data will be regularly wiped, reset, or deleted. For more info, check https://github.com/eraeco/joydb#peers !'); + return ['https://gunjs.herokuapp.com/gun']; + }())); + window.gun = window.gun || Gun(opt); + + gun.on('auth', function(ack){ + console.log("Your namespace is publicly available at", ack.soul); + }); +}()); \ No newline at end of file diff --git a/gun-server/node_modules/gun/axe.js b/gun-server/node_modules/gun/axe.js new file mode 100755 index 0000000..98b4557 --- /dev/null +++ b/gun-server/node_modules/gun/axe.js @@ -0,0 +1,109 @@ +;(function(){ + + var sT = setTimeout || {}, u; + if(typeof window !== ''+u){ sT.window = window } + var AXE = (sT.window||'').AXE || function(){}; + if(AXE.window = sT.window){ AXE.window.AXE = AXE } + + var Gun = (AXE.window||'').GUN || require('./gun'); + (Gun.AXE = AXE).GUN = AXE.Gun = Gun; + + //if(!Gun.window){ try{ require('./lib/axe') }catch(e){} } + if(!Gun.window){ require('./lib/axe') } + + Gun.on('opt', function(at){ start(at) ; this.to.next(at) }); // make sure to call the "next" middleware adapter. + + function start(root){ + if(root.axe){ return } + var opt = root.opt, peers = opt.peers; + if(false === opt.axe){ return } + if(!Gun.window){ return } // handled by ^ lib/axe.js + var w = Gun.window, lS = w.localStorage || opt.localStorage || {}, loc = w.location || opt.location || {}, nav = w.navigator || opt.navigator || {}; + var axe = root.axe = {}, tmp, id; + var mesh = opt.mesh = opt.mesh || Gun.Mesh(root); // DAM! + + tmp = peers[id = loc.origin + '/gun'] = peers[id] || {}; + tmp.id = tmp.url = id; tmp.retry = tmp.retry || 0; + tmp = peers[id = 'http://localhost:8765/gun'] = peers[id] || {}; + tmp.id = tmp.url = id; tmp.retry = tmp.retry || 0; + Gun.log.once("AXE", "AXE enabled: Trying to find network via (1) local peer (2) last used peers (3) a URL parameter, and last (4) hard coded peers."); + Gun.log.once("AXEWarn", "Warning: AXE is in alpha, use only for testing!"); + var last = lS.peers || ''; if(last){ last += ' ' } + last += ((loc.search||'').split('peers=')[1]||'').split('&')[0]; + + root.on('bye', function(peer){ + this.to.next(peer); + if(!peer.url){ return } // ignore WebRTC disconnects for now. + if(!nav.onLine){ peer.retry = 1 } + if(peer.retry){ return } + if(axe.fall){ delete axe.fall[peer.url || peer.id] } + (function next(){ + if(!axe.fall){ setTimeout(next, 9); return } // not found yet + var fall = Object.keys(axe.fall||''), one = fall[(Math.random()*fall.length) >> 0]; + if(!fall.length){ lS.peers = ''; one = 'https://gunjs.herokuapp.com/gun' } // out of peers + if(peers[one]){ next(); return } // already choose + mesh.hi(one); + }()); + }); + + root.on('hi', function(peer){ // TEMPORARY! Try to connect all peers. + this.to.next(peer); + if(!peer.url){ return } // ignore WebRTC disconnects for now. + return; // DO NOT COMMIT THIS FEATURE YET! KEEP TESTING NETWORK PERFORMANCE FIRST! + (function next(){ + if(!peer.wire){ return } + if(!axe.fall){ setTimeout(next, 9); return } // not found yet + var one = (next.fall = next.fall || Object.keys(axe.fall||'')).pop(); + if(!one){ return } + setTimeout(next, 99); + mesh.say({dam: 'opt', opt: {peers: one}}, peer); + }()); + }); + + function found(text){ + + axe.fall = {}; + ((text||'').match(/https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/ig)||[]).forEach(function(url){ + axe.fall[url] = {url: url, id: url, retry: 0}; // RETRY + }); + + return; + + // TODO: Finish porting below? Maybe not. + + Object.keys(last.peers||'').forEach(function(key){ + tmp = peers[id = key] = peers[id] || {}; + tmp.id = tmp.url = id; + }); + tmp = peers[id = 'https://guntest.herokuapp.com/gun'] = peers[id] || {}; + tmp.id = tmp.url = id; + + var mesh = opt.mesh = opt.mesh || Gun.Mesh(root); // DAM! + mesh.way = function(msg){ + if(root.$ === msg.$ || (msg._||'').via){ + mesh.say(msg, opt.peers); + return; + } + var at = (msg.$||'')._; + if(!at){ mesh.say(msg, opt.peers); return } + if(msg.get){ + if(at.axe){ return } // don't ask for it again! + at.axe = {}; + } + mesh.say(msg, opt.peers); + } + } + + if(last){ found(last); return } + try{ fetch(((loc.search||'').split('axe=')[1]||'').split('&')[0] || loc.axe || 'https://raw.githubusercontent.com/wiki/amark/gun/volunteer.dht.md').then(function(res){ + return res.text() + }).then(function(text){ + found(lS.peers = text); + }).catch(function(){ + found(); // nothing + })}catch(e){found()} + } + + var empty = {}, yes = true; + try{ if(typeof module != ''+u){ module.exports = AXE } }catch(e){} +}()); \ No newline at end of file diff --git a/gun-server/node_modules/gun/bower.json b/gun-server/node_modules/gun/bower.json new file mode 100755 index 0000000..71b2498 --- /dev/null +++ b/gun-server/node_modules/gun/bower.json @@ -0,0 +1,33 @@ +{ + "name": "gun", + "main": "gun.js", + "version": "0.1.5", + "homepage": "http://gunDB.io", + "authors": [ + { "name": "Mark Nadal", "email": "mark@accelsor.com" }, + { "name": "Alex LaFroscia", "email": "alex@lafroscia.com" } + ], + "repository": { + "type": "git", + "url": "https://github.com/amark/gun" + }, + "description": "A distributed, embedded, graph database engine.", + "moduleType": [ + "globals" + ], + "keywords": [ + "graph", + "database", + "gun", + "gundb", + "nodb" + ], + "license": "MIT", + "ignore": [ + "**/.*", + "node_modules", + "bower_components", + "test", + "tests" + ] +} diff --git a/gun-server/node_modules/gun/browser.js b/gun-server/node_modules/gun/browser.js new file mode 100755 index 0000000..2459a30 --- /dev/null +++ b/gun-server/node_modules/gun/browser.js @@ -0,0 +1 @@ +module.exports = require('./gun.js') \ No newline at end of file diff --git a/gun-server/node_modules/gun/examples/Main.js b/gun-server/node_modules/gun/examples/Main.js new file mode 100755 index 0000000..7ea37fe --- /dev/null +++ b/gun-server/node_modules/gun/examples/Main.js @@ -0,0 +1,217 @@ +import { render } from './iris/js/lib/preact.js'; +import { Router, route } from './iris/js/lib/preact-router.es.js'; +import { createHashHistory } from './iris/js/lib/history.production.min.js'; +import { Component } from './iris/js/lib/preact.js'; +import { Link } from './iris/js/lib/preact.match.js'; + +import Helpers from './iris/js/Helpers.js'; +import { html } from './iris/js/Helpers.js'; +import QRScanner from './iris/js/QRScanner.js'; +import PeerManager from './iris/js/PeerManager.js'; +import Session from './iris/js/Session.js'; +import { translate as t } from './iris/js/Translation.js'; + +import Settings from './iris/js/views/Settings.js'; +import LogoutConfirmation from './iris/js/views/LogoutConfirmation.js'; +import Chat from './iris/js/views/Chat.js'; +import Store from './iris/js/views/Store.js'; +import Checkout from './iris/js/views/Checkout.js'; +import Product from './iris/js/views/Product.js'; +import Login from './iris/js/views/Login.js'; +import Profile from './iris/js/views/Profile.js'; +import Group from './iris/js/views/Group.js'; +import Message from './iris/js/views/Message.js'; +import Follows from './iris/js/views/Follows.js'; +import Feed from './iris/js/views/Feed.js'; +import About from './iris/js/views/About.js'; +import Explorer from './iris/js/views/Explorer.js'; +import Contacts from './iris/js/views/Contacts.js'; +import Torrent from './iris/js/views/Torrent.js'; + +import VideoCall from './iris/js/components/VideoCall.js'; +import Identicon from './iris/js/components/Identicon.js'; +import MediaPlayer from './iris/js/components/MediaPlayer.js'; +import Footer from './iris/js/components/Footer.js'; +import State from './iris/js/State.js'; +import Icons from './iris/js/Icons.js'; + +const userAgent = navigator.userAgent.toLowerCase(); +const isElectron = (userAgent.indexOf(' electron/') > -1); +if (!isElectron && ('serviceWorker' in navigator)) { + window.addEventListener('load', function() { + navigator.serviceWorker.register('iris/serviceworker.js') + .catch(function(err) { + // registration failed :( + console.log('ServiceWorker registration failed: ', err); + }); + }); +} + +State.init(); +Session.init({autologin: true}); +PeerManager.init(); + +Helpers.checkColorScheme(); + +const APPLICATIONS = [ // TODO: move editable shortcuts to State.local gun + {url: '/', text: t('home'), icon: Icons.home}, + {url: '/feed', text: t('feed'), icon: Icons.feed}, + {url: '/media', text: t('media'), icon: Icons.play}, + {url: '/settings', text: t('settings'), icon: Icons.settings}, + {url: '/store', text: t('store'), icon: Icons.store}, + {url: '/explorer', text: t('explorer'), icon: Icons.folder}, + {url: '/chat', text: t('messages'), icon: Icons.chat}, + // {url: '/store', text: t('store'), icon: Icons.store}, // restore when it works! + {}, + {url: '../stats.html', text: 'Gun node stats'}, + {url: '../iris/index.html', text: 'Iris', icon: html``}, + {url: '../infinite-scroll/index.html', text: 'Infinite scroll'}, + {url: '../chat/index.html', text: 'Chat'}, + {url: '../game/space.html', text: 'Space'}, + {}, + {url: 'https://gun.eco/docs/', text: 'Gun documentation'}, + {url: 'https://examples.iris.to/components/', text: 'Iris web components'} +]; + +const HomeView = () => { + return html` + + `; +}; + +class MenuView extends Component { + componentDidMount() { + State.local.get('showMenu').on(showMenu => this.setState({showMenu})); + } + + render() { + const pub = Session.getPubKey(); + return html` +
      + + <${Identicon} str=${pub} width=40/> + + +

      + ${APPLICATIONS.map(a => { + if (a.url) { + return html` + + ${a.icon || Icons.circle} + ${a.text} + `; + } else { + return html`

      `; + } + })} +
      + `; + } +}; + +class Main extends Component { + constructor() { + super(); + this.showMenu = false; + } + + componentDidMount() { + State.local.get('loggedIn').on(loggedIn => this.setState({loggedIn})); + } + + handleRoute(e) { + let activeRoute = e.url; + if (!activeRoute && window.location.hash) { + return route(window.location.hash.replace('#', '')); // bubblegum fix back navigation + } + document.title = 'Iris'; + if (activeRoute && activeRoute.length > 1) { document.title += ' - ' + Helpers.capitalize(activeRoute.replace('/', '')); } + State.local.get('activeRoute').put(activeRoute); + QRScanner.cleanupScanner(); + } + + onClickOverlay() { + if (this.state.showMenu) { + this.setState({showMenu: false}); + } + } + + toggleMenu(show) { + this.setState({showMenu: typeof show === 'undefined' ? !this.state.showMenu : show}); + } + + render() { + const content = this.state.loggedIn ? html` +
      + State.local.get('showMenu').put(this.showMenu = !this.showMenu)} style="padding: 5px;cursor:pointer;" viewBox="0 -53 384 384" width="40px"> +
      +
      + <${MenuView}/> +
      + <${Router} history=${createHashHistory()} onChange=${e => this.handleRoute(e)}> + <${HomeView} path="/"/> + <${Feed} path="/feed"/> + <${Feed} path="/search/:term?/:type?"/> + <${Feed} path="/media" index="media"/> + <${Login} path="/login"/> + <${Chat} path="/chat/:id?"/> + <${Message} path="/post/:hash"/> + <${Torrent} path="/torrent/:id"/> + <${About} path="/about"/> + <${Settings} path="/settings"/> + <${LogoutConfirmation} path="/logout"/> + <${Profile} path="/profile/:id?" tab="profile"/> + <${Profile} path="/replies/:id?" tab="replies"/> + <${Profile} path="/likes/:id?" tab="likes"/> + <${Profile} path="/media/:id" tab="media"/> + <${Group} path="/group/:id?"/> + <${Store} path="/store/:store?"/> + <${Checkout} path="/checkout/:store?"/> + <${Product} path="/product/:product/:store"/> + <${Product} path="/product/new" store=Session.getPubKey()/> + <${Explorer} path="/explorer/:node"/> + <${Explorer} path="/explorer"/> + <${Follows} path="/follows/:id"/> + <${Follows} followers=${true} path="/followers/:id"/> + <${Contacts} path="/contacts"/> + +
      +
      + <${VideoCall}/> + ` : ''; + return html` +
      + ${content} +
      + `; + } +} + +render(html`<${Main}/>`, document.body); + +$('body').css('opacity', 1); // use opacity because setting focus on display: none elements fails diff --git a/gun-server/node_modules/gun/examples/angular/.angular-cli.json b/gun-server/node_modules/gun/examples/angular/.angular-cli.json new file mode 100755 index 0000000..bc5f7ad --- /dev/null +++ b/gun-server/node_modules/gun/examples/angular/.angular-cli.json @@ -0,0 +1,58 @@ +{ + "$schema": "./node_modules/@angular/cli/lib/config/schema.json", + "project": { + "name": "angular" + }, + "apps": [ + { + "root": "src", + "outDir": "dist", + "assets": [ + "assets", + "favicon.ico" + ], + "index": "index.html", + "main": "main.ts", + "polyfills": "polyfills.ts", + "test": "test.ts", + "tsconfig": "tsconfig.app.json", + "testTsconfig": "tsconfig.spec.json", + "prefix": "app", + "styles": [ + "styles.css" + ], + "scripts": [], + "environmentSource": "environments/environment.ts", + "environments": { + "dev": "environments/environment.ts", + "prod": "environments/environment.prod.ts" + } + } + ], + "e2e": { + "protractor": { + "config": "./protractor.conf.js" + } + }, + "lint": [ + { + "project": "src/tsconfig.app.json", + "exclude": "**/node_modules/**" + }, + { + "project": "src/tsconfig.spec.json" + }, + { + "project": "e2e/tsconfig.e2e.json" + } + ], + "test": { + "karma": { + "config": "./karma.conf.js" + } + }, + "defaults": { + "styleExt": "css", + "component": {} + } +} diff --git a/gun-server/node_modules/gun/examples/angular/.editorconfig b/gun-server/node_modules/gun/examples/angular/.editorconfig new file mode 100755 index 0000000..6e87a00 --- /dev/null +++ b/gun-server/node_modules/gun/examples/angular/.editorconfig @@ -0,0 +1,13 @@ +# Editor configuration, see http://editorconfig.org +root = true + +[*] +charset = utf-8 +indent_style = space +indent_size = 2 +insert_final_newline = true +trim_trailing_whitespace = true + +[*.md] +max_line_length = off +trim_trailing_whitespace = false diff --git a/gun-server/node_modules/gun/examples/angular/README.md b/gun-server/node_modules/gun/examples/angular/README.md new file mode 100755 index 0000000..62c2b5e --- /dev/null +++ b/gun-server/node_modules/gun/examples/angular/README.md @@ -0,0 +1,28 @@ +# Angular + +This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 1.0.0. + +## Development server + +Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files. + +## Code scaffolding + +Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive/pipe/service/class/module`. + +## Build + +Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `-prod` flag for a production build. + +## Running unit tests + +Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io). + +## Running end-to-end tests + +Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/). +Before running the tests make sure you are serving the app via `ng serve`. + +## Further help + +To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md). diff --git a/gun-server/node_modules/gun/examples/angular/e2e/tsconfig.e2e.json b/gun-server/node_modules/gun/examples/angular/e2e/tsconfig.e2e.json new file mode 100755 index 0000000..ac7a373 --- /dev/null +++ b/gun-server/node_modules/gun/examples/angular/e2e/tsconfig.e2e.json @@ -0,0 +1,12 @@ +{ + "extends": "../tsconfig.json", + "compilerOptions": { + "outDir": "../out-tsc/e2e", + "module": "commonjs", + "target": "es5", + "types":[ + "jasmine", + "node" + ] + } +} diff --git a/gun-server/node_modules/gun/examples/angular/example_package.json b/gun-server/node_modules/gun/examples/angular/example_package.json new file mode 100755 index 0000000..ec6a9fa --- /dev/null +++ b/gun-server/node_modules/gun/examples/angular/example_package.json @@ -0,0 +1,51 @@ +{ + "name": "angular", + "version": "0.0.0", + "license": "MIT", + "scripts": { + "ng": "ng", + "start": "ng serve", + "build": "ng build", + "test": "ng test", + "lint": "ng lint", + "e2e": "ng e2e" + }, + "private": true, + "dependencies": { + "@angular/common": "^4.1.0", + "@angular/compiler": "^4.1.0", + "@angular/core": "^4.1.0", + "@angular/forms": "^4.1.0", + "@angular/http": "^4.1.0", + "@angular/platform-browser": "^4.1.0", + "@angular/platform-browser-dynamic": "^4.1.0", + "@angular/router": "^4.1.0", + "core-js": "^2.4.1", + "express-http-proxy": "^1.0.1", + "gun": "https://github.com/amark/gun.git#master", + "ngx-pipes": "^2.0.5", + "rxjs": "^5.3.0", + "underscore": "^1.8.3", + "zone.js": "^0.8.9" + }, + "devDependencies": { + "@angular/cli": "1.0.0", + "@angular/compiler-cli": "^4.1.0", + "@types/jasmine": "2.5.38", + "@types/node": "~6.0.60", + "@types/underscore": "^1.8.0", + "codelyzer": "^2.1.1", + "jasmine-core": "^2.6.1", + "jasmine-spec-reporter": "^4.0.0", + "karma": "^1.6.0", + "karma-chrome-launcher": "~2.0.0", + "karma-cli": "~1.0.1", + "karma-coverage-istanbul-reporter": "^1.2.0", + "karma-jasmine": "~1.1.0", + "karma-jasmine-html-reporter": "^0.2.2", + "protractor": "~5.1.0", + "ts-node": "^3.0.2", + "tslint": "~4.5.0", + "typescript": "^2.3.2" + } +} diff --git a/gun-server/node_modules/gun/examples/angular/karma.conf.js b/gun-server/node_modules/gun/examples/angular/karma.conf.js new file mode 100755 index 0000000..84b4cd5 --- /dev/null +++ b/gun-server/node_modules/gun/examples/angular/karma.conf.js @@ -0,0 +1,44 @@ +// Karma configuration file, see link for more information +// https://karma-runner.github.io/0.13/config/configuration-file.html + +module.exports = function (config) { + config.set({ + basePath: '', + frameworks: ['jasmine', '@angular/cli'], + plugins: [ + require('karma-jasmine'), + require('karma-chrome-launcher'), + require('karma-jasmine-html-reporter'), + require('karma-coverage-istanbul-reporter'), + require('@angular/cli/plugins/karma') + ], + client:{ + clearContext: false // leave Jasmine Spec Runner output visible in browser + }, + files: [ + { pattern: './src/test.ts', watched: false } + ], + preprocessors: { + './src/test.ts': ['@angular/cli'] + }, + mime: { + 'text/x-typescript': ['ts','tsx'] + }, + coverageIstanbulReporter: { + reports: [ 'html', 'lcovonly' ], + fixWebpackSourcePaths: true + }, + angularCli: { + environment: 'dev' + }, + reporters: config.angularCli && config.angularCli.codeCoverage + ? ['progress', 'coverage-istanbul'] + : ['progress', 'kjhtml'], + port: 9876, + colors: true, + logLevel: config.LOG_INFO, + autoWatch: true, + browsers: ['Chrome'], + singleRun: false + }); +}; diff --git a/gun-server/node_modules/gun/examples/angular/protractor.conf.js b/gun-server/node_modules/gun/examples/angular/protractor.conf.js new file mode 100755 index 0000000..1c5e1e5 --- /dev/null +++ b/gun-server/node_modules/gun/examples/angular/protractor.conf.js @@ -0,0 +1,30 @@ +// Protractor configuration file, see link for more information +// https://github.com/angular/protractor/blob/master/lib/config.ts + +const { SpecReporter } = require('jasmine-spec-reporter'); + +exports.config = { + allScriptsTimeout: 11000, + specs: [ + './e2e/**/*.e2e-spec.ts' + ], + capabilities: { + 'browserName': 'chrome' + }, + directConnect: true, + baseUrl: 'http://localhost:4200/', + framework: 'jasmine', + jasmineNodeOpts: { + showColors: true, + defaultTimeoutInterval: 30000, + print: function() {} + }, + beforeLaunch: function() { + require('ts-node').register({ + project: 'e2e/tsconfig.e2e.json' + }); + }, + onPrepare() { + jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } })); + } +}; diff --git a/gun-server/node_modules/gun/examples/angular/server.js b/gun-server/node_modules/gun/examples/angular/server.js new file mode 100755 index 0000000..f8a1978 --- /dev/null +++ b/gun-server/node_modules/gun/examples/angular/server.js @@ -0,0 +1,20 @@ +var port = process.env.OPENSHIFT_NODEJS_PORT || process.env.VCAP_APP_PORT || process.env.PORT || process.argv[2] || 8765; +var host = process.env.OPENSHIFT_NODEJS_HOST || process.env.VCAP_APP_HOST || process.env.HOST || 'localhost'; + +var express = require('express'); +var proxy = require('express-http-proxy'); +var http = require('http'); +var app = express(); +var server = http.createServer(app); + +var Gun = require('gun'); +var gun = Gun({ + file: 'data.json', + web: server +}); + +app.use(Gun.serve); +app.use(proxy(host + ':4200')); +server.listen(port); + +console.log('Server started on port ' + port + ' with /gun'); diff --git a/gun-server/node_modules/gun/examples/angular/src/app/app.component.css b/gun-server/node_modules/gun/examples/angular/src/app/app.component.css new file mode 100755 index 0000000..4625ea1 --- /dev/null +++ b/gun-server/node_modules/gun/examples/angular/src/app/app.component.css @@ -0,0 +1,7 @@ +html, body { font-size: 14pt; padding: 10px 2.5%;} +.hide { display: none; } +form .who { width: 10%; } +form .what { width: 80%; } +ul { list-style: none; padding: 0; } +ul .when {color: #555; font-size: 12pt; float: right; display: none; } +li:hover .when {display: inline;} diff --git a/gun-server/node_modules/gun/examples/angular/src/app/app.component.html b/gun-server/node_modules/gun/examples/angular/src/app/app.component.html new file mode 100755 index 0000000..cb2bf2a --- /dev/null +++ b/gun-server/node_modules/gun/examples/angular/src/app/app.component.html @@ -0,0 +1,13 @@ +
      + +
      + + +
      +
      +
        +
      • {{todo[1]}}
      • +
      + + +
      diff --git a/gun-server/node_modules/gun/examples/angular/src/assets/.gitkeep b/gun-server/node_modules/gun/examples/angular/src/assets/.gitkeep new file mode 100755 index 0000000..e69de29 diff --git a/gun-server/node_modules/gun/examples/angular/src/favicon.ico b/gun-server/node_modules/gun/examples/angular/src/favicon.ico new file mode 100755 index 0000000..8081c7c Binary files /dev/null and b/gun-server/node_modules/gun/examples/angular/src/favicon.ico differ diff --git a/gun-server/node_modules/gun/examples/angular/src/index.html b/gun-server/node_modules/gun/examples/angular/src/index.html new file mode 100755 index 0000000..416f297 --- /dev/null +++ b/gun-server/node_modules/gun/examples/angular/src/index.html @@ -0,0 +1,14 @@ + + + + + Angular + + + + + + + Loading... + + diff --git a/gun-server/node_modules/gun/examples/angular/src/styles.css b/gun-server/node_modules/gun/examples/angular/src/styles.css new file mode 100755 index 0000000..90d4ee0 --- /dev/null +++ b/gun-server/node_modules/gun/examples/angular/src/styles.css @@ -0,0 +1 @@ +/* You can add global styles to this file, and also import other style files */ diff --git a/gun-server/node_modules/gun/examples/angular/src/tsconfig.app.json b/gun-server/node_modules/gun/examples/angular/src/tsconfig.app.json new file mode 100755 index 0000000..5e2507d --- /dev/null +++ b/gun-server/node_modules/gun/examples/angular/src/tsconfig.app.json @@ -0,0 +1,13 @@ +{ + "extends": "../tsconfig.json", + "compilerOptions": { + "outDir": "../out-tsc/app", + "module": "es2015", + "baseUrl": "", + "types": [] + }, + "exclude": [ + "test.ts", + "**/*.spec.ts" + ] +} diff --git a/gun-server/node_modules/gun/examples/angular/src/tsconfig.spec.json b/gun-server/node_modules/gun/examples/angular/src/tsconfig.spec.json new file mode 100755 index 0000000..510e3f1 --- /dev/null +++ b/gun-server/node_modules/gun/examples/angular/src/tsconfig.spec.json @@ -0,0 +1,20 @@ +{ + "extends": "../tsconfig.json", + "compilerOptions": { + "outDir": "../out-tsc/spec", + "module": "commonjs", + "target": "es5", + "baseUrl": "", + "types": [ + "jasmine", + "node" + ] + }, + "files": [ + "test.ts" + ], + "include": [ + "**/*.spec.ts", + "**/*.d.ts" + ] +} diff --git a/gun-server/node_modules/gun/examples/angular/src/typings.d.ts b/gun-server/node_modules/gun/examples/angular/src/typings.d.ts new file mode 100755 index 0000000..ef5c7bd --- /dev/null +++ b/gun-server/node_modules/gun/examples/angular/src/typings.d.ts @@ -0,0 +1,5 @@ +/* SystemJS module definition */ +declare var module: NodeModule; +interface NodeModule { + id: string; +} diff --git a/gun-server/node_modules/gun/examples/angular/tsconfig.json b/gun-server/node_modules/gun/examples/angular/tsconfig.json new file mode 100755 index 0000000..a35a8ee --- /dev/null +++ b/gun-server/node_modules/gun/examples/angular/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compileOnSave": false, + "compilerOptions": { + "outDir": "./dist/out-tsc", + "baseUrl": "src", + "sourceMap": true, + "declaration": false, + "moduleResolution": "node", + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "target": "es5", + "typeRoots": [ + "node_modules/@types" + ], + "lib": [ + "es2016", + "dom" + ] + } +} diff --git a/gun-server/node_modules/gun/examples/angular/tslint.json b/gun-server/node_modules/gun/examples/angular/tslint.json new file mode 100755 index 0000000..9113f13 --- /dev/null +++ b/gun-server/node_modules/gun/examples/angular/tslint.json @@ -0,0 +1,116 @@ +{ + "rulesDirectory": [ + "node_modules/codelyzer" + ], + "rules": { + "callable-types": true, + "class-name": true, + "comment-format": [ + true, + "check-space" + ], + "curly": true, + "eofline": true, + "forin": true, + "import-blacklist": [true, "rxjs"], + "import-spacing": true, + "indent": [ + true, + "spaces" + ], + "interface-over-type-literal": true, + "label-position": true, + "max-line-length": [ + true, + 140 + ], + "member-access": false, + "member-ordering": [ + true, + "static-before-instance", + "variables-before-functions" + ], + "no-arg": true, + "no-bitwise": true, + "no-console": [ + true, + "debug", + "info", + "time", + "timeEnd", + "trace" + ], + "no-construct": true, + "no-debugger": true, + "no-duplicate-variable": true, + "no-empty": false, + "no-empty-interface": true, + "no-eval": true, + "no-inferrable-types": [true, "ignore-params"], + "no-shadowed-variable": true, + "no-string-literal": false, + "no-string-throw": true, + "no-switch-case-fall-through": true, + "no-trailing-whitespace": true, + "no-unused-expression": true, + "no-use-before-declare": true, + "no-var-keyword": true, + "object-literal-sort-keys": false, + "one-line": [ + true, + "check-open-brace", + "check-catch", + "check-else", + "check-whitespace" + ], + "prefer-const": true, + "quotemark": [ + true, + "single" + ], + "radix": true, + "semicolon": [ + "always" + ], + "triple-equals": [ + true, + "allow-null-check" + ], + "typedef-whitespace": [ + true, + { + "call-signature": "nospace", + "index-signature": "nospace", + "parameter": "nospace", + "property-declaration": "nospace", + "variable-declaration": "nospace" + } + ], + "typeof-compare": true, + "unified-signatures": true, + "variable-name": false, + "whitespace": [ + true, + "check-branch", + "check-decl", + "check-operator", + "check-separator", + "check-type" + ], + + "directive-selector": [true, "attribute", "app", "camelCase"], + "component-selector": [true, "element", "app", "kebab-case"], + "use-input-property-decorator": true, + "use-output-property-decorator": true, + "use-host-property-decorator": true, + "no-input-rename": true, + "no-output-rename": true, + "use-life-cycle-interface": true, + "use-pipe-transform-interface": true, + "component-class-suffix": true, + "directive-class-suffix": true, + "no-access-missing-member": true, + "templates-use-public": true, + "invoke-injectable": true + } +} diff --git a/gun-server/node_modules/gun/examples/axe.html b/gun-server/node_modules/gun/examples/axe.html new file mode 100755 index 0000000..4f91aaa --- /dev/null +++ b/gun-server/node_modules/gun/examples/axe.html @@ -0,0 +1,46 @@ + + + + + + + Testing AXE + + + +

      + + + + + + + + diff --git a/gun-server/node_modules/gun/examples/basic/chat.html b/gun-server/node_modules/gun/examples/basic/chat.html new file mode 100755 index 0000000..64638fe --- /dev/null +++ b/gun-server/node_modules/gun/examples/basic/chat.html @@ -0,0 +1,21 @@ + +
        +
        + + + +
        + + + + \ No newline at end of file diff --git a/gun-server/node_modules/gun/examples/basic/emoji.html b/gun-server/node_modules/gun/examples/basic/emoji.html new file mode 100755 index 0000000..71d1dbc --- /dev/null +++ b/gun-server/node_modules/gun/examples/basic/emoji.html @@ -0,0 +1,2 @@ + +

        Moved to ./chat.html!

        \ No newline at end of file diff --git a/gun-server/node_modules/gun/examples/basic/note.html b/gun-server/node_modules/gun/examples/basic/note.html new file mode 100755 index 0000000..5dca5fe --- /dev/null +++ b/gun-server/node_modules/gun/examples/basic/note.html @@ -0,0 +1,9 @@ + + + + \ No newline at end of file diff --git a/gun-server/node_modules/gun/examples/basic/paste.html b/gun-server/node_modules/gun/examples/basic/paste.html new file mode 100755 index 0000000..0a84f3f --- /dev/null +++ b/gun-server/node_modules/gun/examples/basic/paste.html @@ -0,0 +1,2 @@ + +

        Moved to ./note.html!

        \ No newline at end of file diff --git a/gun-server/node_modules/gun/examples/basic/poll.html b/gun-server/node_modules/gun/examples/basic/poll.html new file mode 100755 index 0000000..03d4dec --- /dev/null +++ b/gun-server/node_modules/gun/examples/basic/poll.html @@ -0,0 +1,148 @@ + + + + + + + + + + + + + + + +
        + +
        + + + + +
        + +
        + +
        + + +
        +
        + +
        +
        +
        + +
        + + + add new title, text, question... + +
        + + + + + + + + + + + \ No newline at end of file diff --git a/gun-server/node_modules/gun/examples/basic/post.html b/gun-server/node_modules/gun/examples/basic/post.html new file mode 100755 index 0000000..bd39b08 --- /dev/null +++ b/gun-server/node_modules/gun/examples/basic/post.html @@ -0,0 +1,45 @@ + + +

        Posts

        + +
        + + + + +
        + +
        + + +
        + +
          + + + + + + + \ No newline at end of file diff --git a/gun-server/node_modules/gun/examples/basic/private.html b/gun-server/node_modules/gun/examples/basic/private.html new file mode 100755 index 0000000..e6536f7 --- /dev/null +++ b/gun-server/node_modules/gun/examples/basic/private.html @@ -0,0 +1,235 @@ + + +
          +
          + +
          +
          + +
          +
          +
          +
          +

          Login

          + + + + +
          + + +
          +

          Profile

          +

          Data is privately encrypted by default. "+" to grant access, "x" to revoke access.

          +
          +
          +
          +
          +
          +
          +
          + +
          + Public Key: +
          + + + + + + \ No newline at end of file diff --git a/gun-server/node_modules/gun/examples/basic/schedule.html b/gun-server/node_modules/gun/examples/basic/schedule.html new file mode 100755 index 0000000..a7733aa --- /dev/null +++ b/gun-server/node_modules/gun/examples/basic/schedule.html @@ -0,0 +1,121 @@ + + + + + + + + +

          Schedule

          + +
          + + + + : + + + + +
          +
          + + + +
            + +
            +
          • + + + + 0 + +
          • +
            + + + + + + + + + \ No newline at end of file diff --git a/gun-server/node_modules/gun/examples/basic/screen.html b/gun-server/node_modules/gun/examples/basic/screen.html new file mode 100755 index 0000000..3587027 --- /dev/null +++ b/gun-server/node_modules/gun/examples/basic/screen.html @@ -0,0 +1,59 @@ + + + +
            + + +
            + + + + + \ No newline at end of file diff --git a/gun-server/node_modules/gun/examples/basic/stream.html b/gun-server/node_modules/gun/examples/basic/stream.html new file mode 100755 index 0000000..ded42a2 --- /dev/null +++ b/gun-server/node_modules/gun/examples/basic/stream.html @@ -0,0 +1,55 @@ + + +
            +
            + Stream + add + resolution + or +
            + + + + + + + + + \ No newline at end of file diff --git a/gun-server/node_modules/gun/examples/basic/tables.html b/gun-server/node_modules/gun/examples/basic/tables.html new file mode 100755 index 0000000..31f17a7 --- /dev/null +++ b/gun-server/node_modules/gun/examples/basic/tables.html @@ -0,0 +1,132 @@ + + +

            Tables

            + +
            + + + + +
            + + +

              + +
              + + + + + + + + + + + + \ No newline at end of file diff --git a/gun-server/node_modules/gun/examples/basic/upload.html b/gun-server/node_modules/gun/examples/basic/upload.html new file mode 100755 index 0000000..f93db1b --- /dev/null +++ b/gun-server/node_modules/gun/examples/basic/upload.html @@ -0,0 +1,35 @@ + + + +
              +

              Drag & drop videos, songs, or images!

              +
              + + + + + + + \ No newline at end of file diff --git a/gun-server/node_modules/gun/examples/basic/user.html b/gun-server/node_modules/gun/examples/basic/user.html new file mode 100755 index 0000000..9e046e2 --- /dev/null +++ b/gun-server/node_modules/gun/examples/basic/user.html @@ -0,0 +1,2 @@ + +

              Moved to ./post.html!

              \ No newline at end of file diff --git a/gun-server/node_modules/gun/examples/basic/video.html b/gun-server/node_modules/gun/examples/basic/video.html new file mode 100755 index 0000000..22dc64c --- /dev/null +++ b/gun-server/node_modules/gun/examples/basic/video.html @@ -0,0 +1,62 @@ + + + +
              + + Record or +
              + + + + + + \ No newline at end of file diff --git a/gun-server/node_modules/gun/examples/chat/index.html b/gun-server/node_modules/gun/examples/chat/index.html new file mode 100755 index 0000000..ff4508f --- /dev/null +++ b/gun-server/node_modules/gun/examples/chat/index.html @@ -0,0 +1,213 @@ + + + + + Converse + + + + + + + +
              +

              Have a Conversation...

              +
                +
              • +
              + +
              +
              + + + + + +
              +
              + +
              +
            • + +

              + 0 +
              +
            • +
              +
              + + + + + + + + diff --git a/gun-server/node_modules/gun/examples/chat/user.html b/gun-server/node_modules/gun/examples/chat/user.html new file mode 100755 index 0000000..b075a80 --- /dev/null +++ b/gun-server/node_modules/gun/examples/chat/user.html @@ -0,0 +1,22 @@ + + + \ No newline at end of file diff --git a/gun-server/node_modules/gun/examples/contact/index.html b/gun-server/node_modules/gun/examples/contact/index.html new file mode 100755 index 0000000..1d76c90 --- /dev/null +++ b/gun-server/node_modules/gun/examples/contact/index.html @@ -0,0 +1,330 @@ + + + + + + + +
              + +
              +
              Welcome,
              +
              + + Enter your public username. +
              +
              + + And a long private passphrase. +
              +
              + +
              or
              + +
              + more info +
              +
              + +
              + +
              + +
              +
                +
              +
              +
            • + Alias: +
            • +
              +
              + + + +
              +
              +
              + +
              + + +
              +
              + +

              Name

              + + bio +
              + + +
              +
              +
                +
              • +
              +
              +
              + +
              +
              + +
              +

              A mysterious new example app has appeared! It is not finished/ready yet.

              +
              + +
              + +

              Hello world!

              +
              + + + + + + + + + + + \ No newline at end of file diff --git a/gun-server/node_modules/gun/examples/docs.html b/gun-server/node_modules/gun/examples/docs.html new file mode 100755 index 0000000..a5e87f1 --- /dev/null +++ b/gun-server/node_modules/gun/examples/docs.html @@ -0,0 +1,379 @@ + + + + + + + + +Docs + + + + +
              +
              +
              + + + + + + + + + + + + + \ No newline at end of file diff --git a/gun-server/node_modules/gun/examples/express.js b/gun-server/node_modules/gun/examples/express.js new file mode 100755 index 0000000..a516e18 --- /dev/null +++ b/gun-server/node_modules/gun/examples/express.js @@ -0,0 +1,17 @@ +console.log("If module not found, install express globally `npm i express -g`!"); +var port = process.env.OPENSHIFT_NODEJS_PORT || process.env.VCAP_APP_PORT || process.env.PORT || process.argv[2] || 8765; +var express = require('express'); +var Gun = require('..'); +require('../axe'); + +var app = express(); +app.use(Gun.serve); +app.use(express.static(__dirname)); + +var server = app.listen(port); +var gun = Gun({ file: 'data', web: server }); + +global.Gun = Gun; /// make global to `node --inspect` - debug only +global.gun = gun; /// make global to `node --inspect` - debug only + +console.log('Server started on port ' + port + ' with /gun'); diff --git a/gun-server/node_modules/gun/examples/game/furball.html b/gun-server/node_modules/gun/examples/game/furball.html new file mode 100755 index 0000000..6c88ced --- /dev/null +++ b/gun-server/node_modules/gun/examples/game/furball.html @@ -0,0 +1,439 @@ + + + + + + + + + +Furball + + + + + + +
              +
              +

              Neon ERA presents

              +

              Furball Forces

              + +
              + + +
              +
              +
              + + +
              + + + + +
              + +
              +
              +

              Choose Team:

              + +
              +
              + +
              +
              + +
              + +
              +

              Episode 1: Waking

              +

              "How long until they're online?"

              +

              "We're copying the soul files, almost done."

              +

              "Monsters are on the bridge, we do not have time!"

              +

              "The new body is printing now, it'll be able to outrun them all, just hold on."

              +

              "It won't know where to run! We're risking ruining the whole resistance, I need to talk to it now."

              +

              "95% done." The voice behind the glass turns to the soul in the body, "My cub, can you hear me?"

              +

              ...

              + +
              + +
              + +
              + +
              +
              + SCORE: 0% +
              +
              + LIFE: 50% +
              +
              +
              +

              A fire explodes in the room behind the glass as an AutoMecha blows the door open.

              +

              The floor shakes and the bed crashes through the wall, flying out of the building.

              +

              "Mom!!!"

              +

              There is a total free fall from 10 levels up, water down below.

              +

              ...

              + +
              + +
              + +
              + +
              +

              The water splashes, swelling and swirling all around.

              +

              ...

              +

              Rapidly tap to swim up to air:

              + +
              + +
              + +
              + +
              +

              Episode 2: Who Am I?

              +

              "Grab on!" A voice calls out from the darkness.

              +

              A life vest hits the water and floats within arm's distance.

              +

              The shivering body is pulled up onto the boat.

              +

              "Wow, you're heavier than you look. Are you OK? What's your name?"

              +

              ...

              +

              Write your reply & hit enter:

              +
              + +
              +
              + +
              + +
              + +
              +

              "Well, it's a miracle you did not die in the building explosion or from that fall."

              +

              "What is going on? What happened?"

              +

              "You can't remember? Your brain must be knocked up pretty hard."

              +

              "No, I was mid copy into this body and now my memories are glitching."

              +

              "Woah, you're one of those pro elite AREION revolutionaries? All flesh & blood! Dense, too. I would've assumed they were stealing AutoMecha tech for that instead."

              +

              "I was about to be told vital data for the resistance, but then they blew up the build--"

              +

              ...

              +

              "Hey, what's the matter?"

              +

              "My mom. She was in there. I need to go back. Please, help me and tell me everything you know."

              +

              "I'm so sorry. I can only get so close with the boat, you're gonna have to jump over a lot of broken bits. You ready?"

              +

              ...

              + +
              +
              + +
              + +
              +

              ... to be continued ...

              +
              + +
              + + +
              + +
              + +
              +

              Episode 1: Training

              +

              ...

              +
              +
              + + +
              +
              +
              +

              For You,

              +

              Crafted with love, ♥ by ERA.

              +
              +
              +
              + +
              +
              + + + \ No newline at end of file diff --git a/gun-server/node_modules/gun/examples/game/nts.html b/gun-server/node_modules/gun/examples/game/nts.html new file mode 100755 index 0000000..c52427e --- /dev/null +++ b/gun-server/node_modules/gun/examples/game/nts.html @@ -0,0 +1,19 @@ + + + + + +

              + + + + + diff --git a/gun-server/node_modules/gun/examples/game/space.html b/gun-server/node_modules/gun/examples/game/space.html new file mode 100755 index 0000000..ac25412 --- /dev/null +++ b/gun-server/node_modules/gun/examples/game/space.html @@ -0,0 +1,281 @@ + + + + +
              +
              +
              +
              +
              +

              + + + + + + + diff --git a/gun-server/node_modules/gun/examples/game/win.html b/gun-server/node_modules/gun/examples/game/win.html new file mode 100755 index 0000000..7fc5516 --- /dev/null +++ b/gun-server/node_modules/gun/examples/game/win.html @@ -0,0 +1,331 @@ + + + + + + + + + +Win + + + + + + +
              +
              +

              how to

              +

              Win at Life!

              +

              success, fame, power.

              +

              sex, ethics, & integrity.

              + +
              + + +
              +
              +
              + + +
              + + +
              + +
              + +
              +

              Step 1: Breathe

              + +
              + +
              + +
              + +
              +

              Step 2: Drink Water

              +

              + +
              + +
              + +
              + +
              +

              Step 3: Eat Once a Day

              +

              If you do not want to be eaten, do not eat things that would not want to be eaten.

              + +
              + +
              + +
              + +
              +

              Step 4: Babymaking* 😉

              +

              Find a willing player.

              +

              * This does not always make babies.

              + +
              + +
              + +
              + +
              +

              Step 5: Make Dance

              +

              Moving your body is how you express your thoughts.

              +

              What you do with your body is what others will come to know you for. So do well.

              +

              You can make art, songs, or stories; You can make science, tools, or discoveries.

              +

              Who are you?

              + + +
              + +
              + +
              +
              +

              Science: Knowing Games

              +

              If you must win one game, it should be the game of making games.

              +

              If you can make any game, then you will know how to win any game.

              + +
              + +
              + +
              +
              +

              Games have goals and play.

              +

              Play is a safe space to try new dances.

              +

              Goals try to get players to do a type of dance.

              + +
              + +
              + +
              + +
              +

              The simplest goal is to not "die" in the game.

              +

              Oh look, you've fallen into water and cannot breathe.

              +

              If you do not push the button to swim to the top, you'll lose the game.

              + +
              +
              +
              + SCORE: 0% +
              +
              + LIFE: 100% +
              +
              + +
              + +
              +
              +

              You won your first game! 🎉

              +

              See? I told you breathing is important.

              +

              You also learned the most basic dance: rapid poking.

              +

              The goal of the next game is to make the game you just won.

              + +
              + + + +
              + +
              + +
              +

              Bend these Rules if it is more Moral to do so

              +

              + +
              + +
              + +
              + +
              +

              GAME OVER

              +

              + +
              + +
              + + + \ No newline at end of file diff --git a/gun-server/node_modules/gun/examples/hapi.js b/gun-server/node_modules/gun/examples/hapi.js new file mode 100755 index 0000000..a4bcca9 --- /dev/null +++ b/gun-server/node_modules/gun/examples/hapi.js @@ -0,0 +1,58 @@ +console.log("If module not found, install hapi globally `npm i hapi inert -g`!") + +const Hapi = require('hapi') +const Inert = require('inert') +const Gun = require('..') + +const server = new Hapi.Server({ + port: 8765, + host: 'localhost', + routes: { + files: { + relativeTo: require('path').join(__dirname, '..') + } + } +}) + +async function runtime() { + + const db = new Gun({ + web: server.listener, + file: 'data.json' + }) + + await server.register(Inert) + + server.route({ + method: 'GET', + path: '/gun.js', + handler: { + file: 'gun.min.js' + } + }) + + server.route({ + method: 'GET', + path: '/gun/nts.js', + handler: { + file: 'nts.js' + } + }) + + server.route({ + method: 'GET', + path: '/{param*}', + handler: { + directory: { + path: __dirname, + redirectToSlash: true, + index: true + } + } + }) + + await server.start() + console.log('Server running at:', server.info.uri) +} + +runtime() diff --git a/gun-server/node_modules/gun/examples/http.js b/gun-server/node_modules/gun/examples/http.js new file mode 100755 index 0000000..bed7cb9 --- /dev/null +++ b/gun-server/node_modules/gun/examples/http.js @@ -0,0 +1,27 @@ +;(function(){ + var cluster = require('cluster'); + if(cluster.isMaster){ + return cluster.fork() && cluster.on('exit', function(){ cluster.fork(); require('../lib/crashed'); }); + } + + var fs = require('fs'); + var config = { + port: process.env.OPENSHIFT_NODEJS_PORT || process.env.VCAP_APP_PORT || process.env.PORT || process.argv[2] || 8765, + peers: process.env.PEERS && process.env.PEERS.split(',') || [] + }; + var Gun = require('../'); // require('gun') + + if(process.env.HTTPS_KEY){ + config.key = fs.readFileSync(process.env.HTTPS_KEY); + config.cert = fs.readFileSync(process.env.HTTPS_CERT); + config.server = require('https').createServer(config, Gun.serve(__dirname)); + } else { + config.server = require('http').createServer(Gun.serve(__dirname)); + } + + var gun = Gun({web: config.server.listen(config.port), peers: config.peers}); + + console.log('Relay peer started on port ' + config.port + ' with /gun'); + + module.exports = gun; +}()); \ No newline at end of file diff --git a/gun-server/node_modules/gun/examples/index.html b/gun-server/node_modules/gun/examples/index.html new file mode 100755 index 0000000..d773e81 --- /dev/null +++ b/gun-server/node_modules/gun/examples/index.html @@ -0,0 +1,4 @@ + +

              This is the examples folder. +

              The most basic example is ./basic/note.html!

              +

              Home page temporarily disabled.

              \ No newline at end of file diff --git a/gun-server/node_modules/gun/examples/infinite-scroll/ScrollWindow.js b/gun-server/node_modules/gun/examples/infinite-scroll/ScrollWindow.js new file mode 100755 index 0000000..4db4fda --- /dev/null +++ b/gun-server/node_modules/gun/examples/infinite-scroll/ScrollWindow.js @@ -0,0 +1,116 @@ +const DEFAULT_OPTIONS = { + size: 20, + stickTo: 'top', +}; + +class ScrollWindow { + constructor(gunNode, opts = {}) { + this.opts = Object.assign(DEFAULT_OPTIONS, opts); + this.elements = new Map(); + this.node = gunNode; + this.center = this.opts.startAt; + this.updateSubscriptions(); + } + + updateSubscriptions() { + this.upSubscription && this.upSubscription.off(); + this.downSubscription && this.downSubscription.off(); + + const subscribe = params => { + this.node.get({ '.': params}).map().on((val, key, a, eve) => { + if (params['-']) { + this.downSubscription = eve; + } else { + this.upSubscription = eve; + } + this._addElement(key, val); + }); + }; + + if (this.center) { + subscribe({ '>': this.center, '<': '\uffff' }); + subscribe({'<': this.center, '>' : '', '-': true}); + } else { + subscribe({ '<': '\uffff', '>': '', '-': this.opts.stickTo === 'top' }); + } + } + + _getSortedKeys() { + this.sortedKeys = this.sortedKeys || [...this.elements.keys()].sort(); + return this.sortedKeys; + } + + _upOrDown(n, up) { + this.opts.stickTo = null; + const keys = this._getSortedKeys(); + n = n || (keys.length / 2); + n = up ? n : -n; + const half = Math.floor(keys.length / 2); + const newMiddleIndex = Math.max(Math.min(half + n, keys.length - 1), 0); + if (this.center !== keys[newMiddleIndex]) { + this.center = keys[newMiddleIndex]; + this.updateSubscriptions(); + } + return this.center; + } + + up(n) { + return this._upOrDown(n, true); + } + + down(n) { + return this._upOrDown(n, false); + } + + _topOrBottom(top) { + this.opts.stickTo = top ? 'top' : 'bottom'; + this.center = null; + this.updateSubscriptions(); + } + + top() { + this._topOrBottom(true); + } + + bottom() { + this._topOrBottom(false); + } + + _addElement(key, val) { + if (!val || this.elements.has(key)) return; + const add = () => { + this.elements.set(key, val); + this.sortedKeys = [...this.elements.keys()].sort(); + const sortedElements = this.sortedKeys.map(k => this.elements.get(k)); + this.opts.onChange && this.opts.onChange(sortedElements); + }; + const keys = this._getSortedKeys(); + if (keys.length < this.opts.size) { + add(); + } else { + if (this.opts.stickTo === 'top' && key > keys[0]) { + this.elements.delete(keys[0]); + add(); + } else if (this.opts.stickTo === 'bottom' && key < keys[keys.length - 1]) { + this.elements.delete(keys[keys.length - 1]); + add(); + } else if (this.center) { + if (keys.indexOf(this.center) < (keys.length / 2)) { + if (key < keys[keys.length - 1]) { + this.elements.delete(keys[keys.length - 1]); + add(); + } + } else { + if (key > keys[0]) { + delete this.elements.delete(keys[0]); + add(); + } + } + } + } + } + + getElements() { + return this.elements; + } +} diff --git a/gun-server/node_modules/gun/examples/infinite-scroll/index.html b/gun-server/node_modules/gun/examples/infinite-scroll/index.html new file mode 100755 index 0000000..83ba03f --- /dev/null +++ b/gun-server/node_modules/gun/examples/infinite-scroll/index.html @@ -0,0 +1,30 @@ + + + Infinite scroll example + + + + + + + + +
              +
              + + +
              +
              + +
              +
              + +
              +
              +
              + + + + + + diff --git a/gun-server/node_modules/gun/examples/infinite-scroll/index.js b/gun-server/node_modules/gun/examples/infinite-scroll/index.js new file mode 100755 index 0000000..6da2b65 --- /dev/null +++ b/gun-server/node_modules/gun/examples/infinite-scroll/index.js @@ -0,0 +1,167 @@ +const gun = new Gun(); + +const size = 20; +const gunNode = gun.get('posts'); + +function debounce(func, wait, immediate) { + var timeout; + return function() { + var context = this, args = arguments; + var later = function() { + timeout = null; + if (!immediate) func.apply(context, args); + }; + var callNow = immediate && !timeout; + clearTimeout(timeout); + timeout = setTimeout(later, wait); + if (callNow) func.apply(context, args); + }; +}; + +let topSentinelPreviousY = 0; +let topSentinelPreviousRatio = 0; +let bottomSentinelPreviousY = 0; +let bottomSentinelPreviousRatio = 0; +let previousUpIndex = previousDownIndex = -1; + +const render = elements => { + const t = new Date(); + elements.reverse().forEach((data, j) => { + var date = new Date(data.date); + $('#date' + j).text(date.toLocaleDateString() + ' ' + date.toLocaleTimeString()); + $('#text' + j).text(data.text); + $('#img' + j).attr('src', ''); + $('#img' + j).attr('src', _getCatImg(date.getTime())); + $('#post' + j).css({visibility: 'visible'}); + }); + console.log('rendering took', new Date().getTime() - t.getTime(), 'ms'); + window.onRender && window.onRender(elements); +}; + +const onChange = debounce(render, 20); + +const scroller = new ScrollWindow(gunNode, {size, stickTo: 'top', onChange}); + +const initList = () => { + for (var n = 0; n < size; n++) { + var el = $("
              ").addClass('post').attr('id', 'post' + n).css({visibility: 'hidden'}); + el.append($('').attr('id', 'date' + n)); + el.append($('').attr('id', 'text' + n)); + el.append($('').attr('id', 'img' + n).attr('height', 100).attr('width', 100)); + $('#container').append(el); + } +} + +const _getCatImg = (n) => { + const url = "https://source.unsplash.com/collection/139386/100x100/?sig="; + return url + n % 999999; +}; + +const getNumFromStyle = numStr => Number(numStr.substring(0, numStr.length - 2)); + +const adjustPaddings = isScrollDown => { + const container = document.getElementById("container"); + const currentPaddingTop = getNumFromStyle(container.style.paddingTop); + const currentPaddingBottom = getNumFromStyle(container.style.paddingBottom); + const remPaddingsVal = 198 * (size / 2); // TODO: calculate actual element heights + if (isScrollDown) { + container.style.paddingTop = currentPaddingTop + remPaddingsVal + "px"; + container.style.paddingBottom = currentPaddingBottom === 0 ? "0px" : currentPaddingBottom - remPaddingsVal + "px"; + } else { + container.style.paddingBottom = currentPaddingBottom + remPaddingsVal + "px"; + if (currentPaddingTop === 0) { + $(window).scrollTop($('#post0').offset().top + remPaddingsVal); + } else { + container.style.paddingTop = currentPaddingTop - remPaddingsVal + "px"; + } + } +} + +const topSentCallback = entry => { + const container = document.getElementById("container"); + + const currentY = entry.boundingClientRect.top; + const currentRatio = entry.intersectionRatio; + const isIntersecting = entry.isIntersecting; + + // conditional check for Scrolling up + if ( + currentY > topSentinelPreviousY && + isIntersecting && + currentRatio >= topSentinelPreviousRatio && + scroller.center !== previousUpIndex && // stop if no new results were received + scroller.opts.stickTo !== 'top' + ) { + previousUpIndex = scroller.center; + adjustPaddings(false); + scroller.up(size / 2); + } + topSentinelPreviousY = currentY; + topSentinelPreviousRatio = currentRatio; +} + +const botSentCallback = entry => { + const currentY = entry.boundingClientRect.top; + const currentRatio = entry.intersectionRatio; + const isIntersecting = entry.isIntersecting; + + // conditional check for Scrolling down + if ( + currentY < bottomSentinelPreviousY && + currentRatio > bottomSentinelPreviousRatio && + isIntersecting && + scroller.center !== previousDownIndex && // stop if no new results were received + scroller.opts.stickTo !== 'bottom' + ) { + previousDownIndex = scroller.center; + adjustPaddings(true); + scroller.down(size / 2); + } + bottomSentinelPreviousY = currentY; + bottomSentinelPreviousRatio = currentRatio; +} + +const initIntersectionObserver = () => { + const options = { + //rootMargin: '190px', + } + + const callback = entries => { + entries.forEach(entry => { + if (entry.target.id === 'post0') { + topSentCallback(entry); + } else if (entry.target.id === `post${size - 1}`) { + botSentCallback(entry); + } + }); + } + + var observer = new IntersectionObserver(callback, options); // TODO: It's possible to quickly scroll past the sentinels without them firing. Top and bottom sentinels should extend to page top & bottom? + observer.observe(document.querySelector("#post0")); + observer.observe(document.querySelector(`#post${size - 1}`)); +} + +initList(size); +initIntersectionObserver(); + +$('#top').click(() => { + scroller.top(); + $('#container').css({'padding-top': 0, 'padding-bottom': 0}); + $(document.body).animate({ scrollTop: 0 }, 500); +}); +$('#bottom').click(() => { + scroller.bottom(); + $('#container').css({'padding-top': 0, 'padding-bottom': 0}); + $(document.body).animate({ scrollTop: $("#container").height() }, 500); +}); + +$('#generate').submit(e => { + e.preventDefault(); + const day = 24 * 60 * 60 * 1000; + const year = 365 * day; + const n = Number($('#number').val()); + for (let i = 0; i < n; i++) { + const d = new Date(40 * year + i * day).toISOString(); + gunNode.get(d).put({text: 'Hello world!', date: d}); + } +}); diff --git a/gun-server/node_modules/gun/examples/infinite-scroll/style.css b/gun-server/node_modules/gun/examples/infinite-scroll/style.css new file mode 100755 index 0000000..66513e8 --- /dev/null +++ b/gun-server/node_modules/gun/examples/infinite-scroll/style.css @@ -0,0 +1,77 @@ +html, body { + margin: 0; + padding: 0; +} + +body { + padding-top: 65px; +} + +header { + background: rgba(255,255,255,0.75); + padding: 15px; +} + +header { + position: fixed; + top: 0; left: 0; right: 0; +} + +#bottom { + position: fixed; + right: 15px; + bottom: 15px; +} + +input { + border: 0; + background-color: #efefef; + padding: 15px; + border-radius: 50px; +} + +button { + background-color: #4a4f9d; + border: 0; + padding: 15px; + color: white; + border-radius: 50px; +} + +input, button { + outline: none; + opacity: 1; +} + +input:focus, button:focus, button:hover { + opacity: 0.8; +} + +button:hover { + cursor: pointer; +} + +#top-buttons, form { + display: inline-block; + margin: 0; +} + +#top-buttons { + float: right; +} + +.post { + margin: 15px; + padding: 15px; + background-color: #9de1fe; + border-radius: 5px; +} + +.post b { + margin-right: 5; +} + +.post img { + display: block; + margin: 10px 0; +} diff --git a/gun-server/node_modules/gun/examples/install.sh b/gun-server/node_modules/gun/examples/install.sh new file mode 100755 index 0000000..79cb2b7 --- /dev/null +++ b/gun-server/node_modules/gun/examples/install.sh @@ -0,0 +1,35 @@ +#!/bin/bash + +# README +# This will install nodejs and npm on your system, +# should work on most places other than Windows. +# Set any environment variables before you run this, +# like `export RAD=false` to disable storage, or +# pass file paths of `HTTPS_CERT` & `HTTPS_KEY`, etc. +# Copy paste and run each line into your terminal. +# If you are on Windows, http://nodejs.org/download/ has +# an installer that will automatically do it for you. +# curl -o- https://raw.githubusercontent.com/amark/gun/master/examples/install.sh | bash + +#debian/ubuntu +su - +apt-get install sudo -y +sudo apt-get update -y +sudo apt-get install curl git git-core screen -y +#fedora/openSUSE +sudo yum check-update -y +sudo yum install curl git git-core screen -y + +# install nodejs +git clone http://github.com/isaacs/nave.git +sudo ./nave/nave.sh usemain stable +# If you just want nodejs and npm but not gun, stop here. + +npm install gun +cd ./node_modules/gun +npm install . + +# to start the gun examples: +screen -S relay +sudo npm start 80 # change `80` to `443` for https or `8765` for development purposes. +# You can now safely CTRL+A+D to escape without stopping the peer. To stop `killall screen` or `killall node`. diff --git a/gun-server/node_modules/gun/examples/jquery.js b/gun-server/node_modules/gun/examples/jquery.js new file mode 100755 index 0000000..b0ecadd --- /dev/null +++ b/gun-server/node_modules/gun/examples/jquery.js @@ -0,0 +1,5 @@ +/*! jQuery v1.12.4 | (c) jQuery Foundation | jquery.org/license */ +!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=a.document,e=c.slice,f=c.concat,g=c.push,h=c.indexOf,i={},j=i.toString,k=i.hasOwnProperty,l={},m="1.12.4",n=function(a,b){return new n.fn.init(a,b)},o=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};n.fn=n.prototype={jquery:m,constructor:n,selector:"",length:0,toArray:function(){return e.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:e.call(this)},pushStack:function(a){var b=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a){return n.each(this,a)},map:function(a){return this.pushStack(n.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(e.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor()},push:g,sort:c.sort,splice:c.splice},n.extend=n.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||n.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(n.isPlainObject(c)||(b=n.isArray(c)))?(b?(b=!1,f=a&&n.isArray(a)?a:[]):f=a&&n.isPlainObject(a)?a:{},g[d]=n.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray||function(a){return"array"===n.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){var b=a&&a.toString();return!n.isArray(a)&&b-parseFloat(b)+1>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==n.type(a)||a.nodeType||n.isWindow(a))return!1;try{if(a.constructor&&!k.call(a,"constructor")&&!k.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(!l.ownFirst)for(b in a)return k.call(a,b);for(b in a);return void 0===b||k.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?i[j.call(a)]||"object":typeof a},globalEval:function(b){b&&n.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b){var c,d=0;if(s(a)){for(c=a.length;c>d;d++)if(b.call(a[d],d,a[d])===!1)break}else for(d in a)if(b.call(a[d],d,a[d])===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(o,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.merge(c,"string"==typeof a?[a]:a):g.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(h)return h.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,e,g=0,h=[];if(s(a))for(d=a.length;d>g;g++)e=b(a[g],g,c),null!=e&&h.push(e);else for(g in a)e=b(a[g],g,c),null!=e&&h.push(e);return f.apply([],h)},guid:1,proxy:function(a,b){var c,d,f;return"string"==typeof b&&(f=a[b],b=a,a=f),n.isFunction(a)?(c=e.call(arguments,2),d=function(){return a.apply(b||this,c.concat(e.call(arguments)))},d.guid=a.guid=a.guid||n.guid++,d):void 0},now:function(){return+new Date},support:l}),"function"==typeof Symbol&&(n.fn[Symbol.iterator]=c[Symbol.iterator]),n.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(a,b){i["[object "+b+"]"]=b.toLowerCase()});function s(a){var b=!!a&&"length"in a&&a.length,c=n.type(a);return"function"===c||n.isWindow(a)?!1:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=ga(),z=ga(),A=ga(),B=function(a,b){return a===b&&(l=!0),0},C=1<<31,D={}.hasOwnProperty,E=[],F=E.pop,G=E.push,H=E.push,I=E.slice,J=function(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1},K="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",L="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",N="\\["+L+"*("+M+")(?:"+L+"*([*^$|!~]?=)"+L+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+M+"))|)"+L+"*\\]",O=":("+M+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+N+")*)|.*)\\)|)",P=new RegExp(L+"+","g"),Q=new RegExp("^"+L+"+|((?:^|[^\\\\])(?:\\\\.)*)"+L+"+$","g"),R=new RegExp("^"+L+"*,"+L+"*"),S=new RegExp("^"+L+"*([>+~]|"+L+")"+L+"*"),T=new RegExp("="+L+"*([^\\]'\"]*?)"+L+"*\\]","g"),U=new RegExp(O),V=new RegExp("^"+M+"$"),W={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),TAG:new RegExp("^("+M+"|[*])"),ATTR:new RegExp("^"+N),PSEUDO:new RegExp("^"+O),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+L+"*(even|odd|(([+-]|)(\\d*)n|)"+L+"*(?:([+-]|)"+L+"*(\\d+)|))"+L+"*\\)|)","i"),bool:new RegExp("^(?:"+K+")$","i"),needsContext:new RegExp("^"+L+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+L+"*((?:-\\d)?\\d*)"+L+"*\\)|)(?=[^-]|$)","i")},X=/^(?:input|select|textarea|button)$/i,Y=/^h\d$/i,Z=/^[^{]+\{\s*\[native \w/,$=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,_=/[+~]/,aa=/'|\\/g,ba=new RegExp("\\\\([\\da-f]{1,6}"+L+"?|("+L+")|.)","ig"),ca=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},da=function(){m()};try{H.apply(E=I.call(v.childNodes),v.childNodes),E[v.childNodes.length].nodeType}catch(ea){H={apply:E.length?function(a,b){G.apply(a,I.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function fa(a,b,d,e){var f,h,j,k,l,o,r,s,w=b&&b.ownerDocument,x=b?b.nodeType:9;if(d=d||[],"string"!=typeof a||!a||1!==x&&9!==x&&11!==x)return d;if(!e&&((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,p)){if(11!==x&&(o=$.exec(a)))if(f=o[1]){if(9===x){if(!(j=b.getElementById(f)))return d;if(j.id===f)return d.push(j),d}else if(w&&(j=w.getElementById(f))&&t(b,j)&&j.id===f)return d.push(j),d}else{if(o[2])return H.apply(d,b.getElementsByTagName(a)),d;if((f=o[3])&&c.getElementsByClassName&&b.getElementsByClassName)return H.apply(d,b.getElementsByClassName(f)),d}if(c.qsa&&!A[a+" "]&&(!q||!q.test(a))){if(1!==x)w=b,s=a;else if("object"!==b.nodeName.toLowerCase()){(k=b.getAttribute("id"))?k=k.replace(aa,"\\$&"):b.setAttribute("id",k=u),r=g(a),h=r.length,l=V.test(k)?"#"+k:"[id='"+k+"']";while(h--)r[h]=l+" "+qa(r[h]);s=r.join(","),w=_.test(a)&&oa(b.parentNode)||b}if(s)try{return H.apply(d,w.querySelectorAll(s)),d}catch(y){}finally{k===u&&b.removeAttribute("id")}}}return i(a.replace(Q,"$1"),b,d,e)}function ga(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ha(a){return a[u]=!0,a}function ia(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ja(a,b){var c=a.split("|"),e=c.length;while(e--)d.attrHandle[c[e]]=b}function ka(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||C)-(~a.sourceIndex||C);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function la(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function ma(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function na(a){return ha(function(b){return b=+b,ha(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function oa(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=fa.support={},f=fa.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=fa.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=n.documentElement,p=!f(n),(e=n.defaultView)&&e.top!==e&&(e.addEventListener?e.addEventListener("unload",da,!1):e.attachEvent&&e.attachEvent("onunload",da)),c.attributes=ia(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ia(function(a){return a.appendChild(n.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Z.test(n.getElementsByClassName),c.getById=ia(function(a){return o.appendChild(a).id=u,!n.getElementsByName||!n.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ba,ca);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ba,ca);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return"undefined"!=typeof b.getElementsByClassName&&p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=Z.test(n.querySelectorAll))&&(ia(function(a){o.appendChild(a).innerHTML="",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+L+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+L+"*(?:value|"+K+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),ia(function(a){var b=n.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+L+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=Z.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ia(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",O)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=Z.test(o.compareDocumentPosition),t=b||Z.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===n||a.ownerDocument===v&&t(v,a)?-1:b===n||b.ownerDocument===v&&t(v,b)?1:k?J(k,a)-J(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,g=[a],h=[b];if(!e||!f)return a===n?-1:b===n?1:e?-1:f?1:k?J(k,a)-J(k,b):0;if(e===f)return ka(a,b);c=a;while(c=c.parentNode)g.unshift(c);c=b;while(c=c.parentNode)h.unshift(c);while(g[d]===h[d])d++;return d?ka(g[d],h[d]):g[d]===v?-1:h[d]===v?1:0},n):n},fa.matches=function(a,b){return fa(a,null,null,b)},fa.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(T,"='$1']"),c.matchesSelector&&p&&!A[b+" "]&&(!r||!r.test(b))&&(!q||!q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return fa(b,n,null,[a]).length>0},fa.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},fa.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&D.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},fa.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},fa.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=fa.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=fa.selectors={cacheLength:50,createPseudo:ha,match:W,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ba,ca),a[3]=(a[3]||a[4]||a[5]||"").replace(ba,ca),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||fa.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&fa.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return W.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&U.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ba,ca).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+L+")"+a+"("+L+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=fa.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(P," ")+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h,t=!1;if(q){if(f){while(p){m=b;while(m=m[p])if(h?m.nodeName.toLowerCase()===r:1===m.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){m=q,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n&&j[2],m=n&&q.childNodes[n];while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if(1===m.nodeType&&++t&&m===b){k[a]=[w,n,t];break}}else if(s&&(m=b,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n),t===!1)while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if((h?m.nodeName.toLowerCase()===r:1===m.nodeType)&&++t&&(s&&(l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),k[a]=[w,t]),m===b))break;return t-=e,t===d||t%d===0&&t/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||fa.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ha(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=J(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ha(function(a){var b=[],c=[],d=h(a.replace(Q,"$1"));return d[u]?ha(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ha(function(a){return function(b){return fa(a,b).length>0}}),contains:ha(function(a){return a=a.replace(ba,ca),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ha(function(a){return V.test(a||"")||fa.error("unsupported lang: "+a),a=a.replace(ba,ca).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Y.test(a.nodeName)},input:function(a){return X.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:na(function(){return[0]}),last:na(function(a,b){return[b-1]}),eq:na(function(a,b,c){return[0>c?c+b:c]}),even:na(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:na(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:na(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:na(function(a,b,c){for(var d=0>c?c+b:c;++db;b++)d+=a[b].value;return d}function ra(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j,k=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(j=b[u]||(b[u]={}),i=j[b.uniqueID]||(j[b.uniqueID]={}),(h=i[d])&&h[0]===w&&h[1]===f)return k[2]=h[2];if(i[d]=k,k[2]=a(b,c,g))return!0}}}function sa(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function ta(a,b,c){for(var d=0,e=b.length;e>d;d++)fa(a,b[d],c);return c}function ua(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(c&&!c(f,d,e)||(g.push(f),j&&b.push(h)));return g}function va(a,b,c,d,e,f){return d&&!d[u]&&(d=va(d)),e&&!e[u]&&(e=va(e,f)),ha(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||ta(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:ua(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=ua(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?J(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=ua(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):H.apply(g,r)})}function wa(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=ra(function(a){return a===b},h,!0),l=ra(function(a){return J(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];f>i;i++)if(c=d.relative[a[i].type])m=[ra(sa(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return va(i>1&&sa(m),i>1&&qa(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(Q,"$1"),c,e>i&&wa(a.slice(i,e)),f>e&&wa(a=a.slice(e)),f>e&&qa(a))}m.push(c)}return sa(m)}function xa(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,o,q,r=0,s="0",t=f&&[],u=[],v=j,x=f||e&&d.find.TAG("*",k),y=w+=null==v?1:Math.random()||.1,z=x.length;for(k&&(j=g===n||g||k);s!==z&&null!=(l=x[s]);s++){if(e&&l){o=0,g||l.ownerDocument===n||(m(l),h=!p);while(q=a[o++])if(q(l,g||n,h)){i.push(l);break}k&&(w=y)}c&&((l=!q&&l)&&r--,f&&t.push(l))}if(r+=s,c&&s!==r){o=0;while(q=b[o++])q(t,u,g,h);if(f){if(r>0)while(s--)t[s]||u[s]||(u[s]=F.call(i));u=ua(u)}H.apply(i,u),k&&!f&&u.length>0&&r+b.length>1&&fa.uniqueSort(i)}return k&&(w=y,j=v),t};return c?ha(f):f}return h=fa.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=wa(b[c]),f[u]?d.push(f):e.push(f);f=A(a,xa(e,d)),f.selector=a}return f},i=fa.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(ba,ca),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=W.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(ba,ca),_.test(j[0].type)&&oa(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&qa(j),!a)return H.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,!b||_.test(a)&&oa(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ia(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ia(function(a){return a.innerHTML="","#"===a.firstChild.getAttribute("href")})||ja("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ia(function(a){return a.innerHTML="",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ja("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ia(function(a){return null==a.getAttribute("disabled")})||ja(K,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),fa}(a);n.find=t,n.expr=t.selectors,n.expr[":"]=n.expr.pseudos,n.uniqueSort=n.unique=t.uniqueSort,n.text=t.getText,n.isXMLDoc=t.isXML,n.contains=t.contains;var u=function(a,b,c){var d=[],e=void 0!==c;while((a=a[b])&&9!==a.nodeType)if(1===a.nodeType){if(e&&n(a).is(c))break;d.push(a)}return d},v=function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c},w=n.expr.match.needsContext,x=/^<([\w-]+)\s*\/?>(?:<\/\1>|)$/,y=/^.[^:#\[\.,]*$/;function z(a,b,c){if(n.isFunction(b))return n.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return n.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(y.test(b))return n.filter(b,a,c);b=n.filter(b,a)}return n.grep(a,function(a){return n.inArray(a,b)>-1!==c})}n.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?n.find.matchesSelector(d,a)?[d]:[]:n.find.matches(a,n.grep(b,function(a){return 1===a.nodeType}))},n.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;e>b;b++)if(n.contains(d[b],this))return!0}));for(b=0;e>b;b++)n.find(a,d[b],c);return c=this.pushStack(e>1?n.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(z(this,a||[],!1))},not:function(a){return this.pushStack(z(this,a||[],!0))},is:function(a){return!!z(this,"string"==typeof a&&w.test(a)?n(a):a||[],!1).length}});var A,B=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,C=n.fn.init=function(a,b,c){var e,f;if(!a)return this;if(c=c||A,"string"==typeof a){if(e="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:B.exec(a),!e||!e[1]&&b)return!b||b.jquery?(b||c).find(a):this.constructor(b).find(a);if(e[1]){if(b=b instanceof n?b[0]:b,n.merge(this,n.parseHTML(e[1],b&&b.nodeType?b.ownerDocument||b:d,!0)),x.test(e[1])&&n.isPlainObject(b))for(e in b)n.isFunction(this[e])?this[e](b[e]):this.attr(e,b[e]);return this}if(f=d.getElementById(e[2]),f&&f.parentNode){if(f.id!==e[2])return A.find(a);this.length=1,this[0]=f}return this.context=d,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):n.isFunction(a)?"undefined"!=typeof c.ready?c.ready(a):a(n):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),n.makeArray(a,this))};C.prototype=n.fn,A=n(d);var D=/^(?:parents|prev(?:Until|All))/,E={children:!0,contents:!0,next:!0,prev:!0};n.fn.extend({has:function(a){var b,c=n(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(n.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=w.test(a)||"string"!=typeof a?n(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&n.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?n.uniqueSort(f):f)},index:function(a){return a?"string"==typeof a?n.inArray(this[0],n(a)):n.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(n.uniqueSort(n.merge(this.get(),n(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function F(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}n.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return u(a,"parentNode")},parentsUntil:function(a,b,c){return u(a,"parentNode",c)},next:function(a){return F(a,"nextSibling")},prev:function(a){return F(a,"previousSibling")},nextAll:function(a){return u(a,"nextSibling")},prevAll:function(a){return u(a,"previousSibling")},nextUntil:function(a,b,c){return u(a,"nextSibling",c)},prevUntil:function(a,b,c){return u(a,"previousSibling",c)},siblings:function(a){return v((a.parentNode||{}).firstChild,a)},children:function(a){return v(a.firstChild)},contents:function(a){return n.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:n.merge([],a.childNodes)}},function(a,b){n.fn[a]=function(c,d){var e=n.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=n.filter(d,e)),this.length>1&&(E[a]||(e=n.uniqueSort(e)),D.test(a)&&(e=e.reverse())),this.pushStack(e)}});var G=/\S+/g;function H(a){var b={};return n.each(a.match(G)||[],function(a,c){b[c]=!0}),b}n.Callbacks=function(a){a="string"==typeof a?H(a):n.extend({},a);var b,c,d,e,f=[],g=[],h=-1,i=function(){for(e=a.once,d=b=!0;g.length;h=-1){c=g.shift();while(++h-1)f.splice(c,1),h>=c&&h--}),this},has:function(a){return a?n.inArray(a,f)>-1:f.length>0},empty:function(){return f&&(f=[]),this},disable:function(){return e=g=[],f=c="",this},disabled:function(){return!f},lock:function(){return e=!0,c||j.disable(),this},locked:function(){return!!e},fireWith:function(a,c){return e||(c=c||[],c=[a,c.slice?c.slice():c],g.push(c),b||i()),this},fire:function(){return j.fireWith(this,arguments),this},fired:function(){return!!d}};return j},n.extend({Deferred:function(a){var b=[["resolve","done",n.Callbacks("once memory"),"resolved"],["reject","fail",n.Callbacks("once memory"),"rejected"],["notify","progress",n.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return n.Deferred(function(c){n.each(b,function(b,f){var g=n.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&n.isFunction(a.promise)?a.promise().progress(c.notify).done(c.resolve).fail(c.reject):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?n.extend(a,d):d}},e={};return d.pipe=d.then,n.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=e.call(arguments),d=c.length,f=1!==d||a&&n.isFunction(a.promise)?d:0,g=1===f?a:n.Deferred(),h=function(a,b,c){return function(d){b[a]=this,c[a]=arguments.length>1?e.call(arguments):d,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(d>1)for(i=new Array(d),j=new Array(d),k=new Array(d);d>b;b++)c[b]&&n.isFunction(c[b].promise)?c[b].promise().progress(h(b,j,i)).done(h(b,k,c)).fail(g.reject):--f;return f||g.resolveWith(k,c),g.promise()}});var I;n.fn.ready=function(a){return n.ready.promise().done(a),this},n.extend({isReady:!1,readyWait:1,holdReady:function(a){a?n.readyWait++:n.ready(!0)},ready:function(a){(a===!0?--n.readyWait:n.isReady)||(n.isReady=!0,a!==!0&&--n.readyWait>0||(I.resolveWith(d,[n]),n.fn.triggerHandler&&(n(d).triggerHandler("ready"),n(d).off("ready"))))}});function J(){d.addEventListener?(d.removeEventListener("DOMContentLoaded",K),a.removeEventListener("load",K)):(d.detachEvent("onreadystatechange",K),a.detachEvent("onload",K))}function K(){(d.addEventListener||"load"===a.event.type||"complete"===d.readyState)&&(J(),n.ready())}n.ready.promise=function(b){if(!I)if(I=n.Deferred(),"complete"===d.readyState||"loading"!==d.readyState&&!d.documentElement.doScroll)a.setTimeout(n.ready);else if(d.addEventListener)d.addEventListener("DOMContentLoaded",K),a.addEventListener("load",K);else{d.attachEvent("onreadystatechange",K),a.attachEvent("onload",K);var c=!1;try{c=null==a.frameElement&&d.documentElement}catch(e){}c&&c.doScroll&&!function f(){if(!n.isReady){try{c.doScroll("left")}catch(b){return a.setTimeout(f,50)}J(),n.ready()}}()}return I.promise(b)},n.ready.promise();var L;for(L in n(l))break;l.ownFirst="0"===L,l.inlineBlockNeedsLayout=!1,n(function(){var a,b,c,e;c=d.getElementsByTagName("body")[0],c&&c.style&&(b=d.createElement("div"),e=d.createElement("div"),e.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(e).appendChild(b),"undefined"!=typeof b.style.zoom&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",l.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(e))}),function(){var a=d.createElement("div");l.deleteExpando=!0;try{delete a.test}catch(b){l.deleteExpando=!1}a=null}();var M=function(a){var b=n.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b},N=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,O=/([A-Z])/g;function P(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(O,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:N.test(c)?n.parseJSON(c):c}catch(e){}n.data(a,b,c)}else c=void 0; +}return c}function Q(a){var b;for(b in a)if(("data"!==b||!n.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function R(a,b,d,e){if(M(a)){var f,g,h=n.expando,i=a.nodeType,j=i?n.cache:a,k=i?a[h]:a[h]&&h;if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||n.guid++:h),j[k]||(j[k]=i?{}:{toJSON:n.noop}),"object"!=typeof b&&"function"!=typeof b||(e?j[k]=n.extend(j[k],b):j[k].data=n.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[n.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[n.camelCase(b)])):f=g,f}}function S(a,b,c){if(M(a)){var d,e,f=a.nodeType,g=f?n.cache:a,h=f?a[n.expando]:n.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){n.isArray(b)?b=b.concat(n.map(b,n.camelCase)):b in d?b=[b]:(b=n.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!Q(d):!n.isEmptyObject(d))return}(c||(delete g[h].data,Q(g[h])))&&(f?n.cleanData([a],!0):l.deleteExpando||g!=g.window?delete g[h]:g[h]=void 0)}}}n.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?n.cache[a[n.expando]]:a[n.expando],!!a&&!Q(a)},data:function(a,b,c){return R(a,b,c)},removeData:function(a,b){return S(a,b)},_data:function(a,b,c){return R(a,b,c,!0)},_removeData:function(a,b){return S(a,b,!0)}}),n.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=n.data(f),1===f.nodeType&&!n._data(f,"parsedAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),P(f,d,e[d])));n._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){n.data(this,a)}):arguments.length>1?this.each(function(){n.data(this,a,b)}):f?P(f,a,n.data(f,a)):void 0},removeData:function(a){return this.each(function(){n.removeData(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=n._data(a,b),c&&(!d||n.isArray(c)?d=n._data(a,b,n.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=n.queue(a,b),d=c.length,e=c.shift(),f=n._queueHooks(a,b),g=function(){n.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return n._data(a,c)||n._data(a,c,{empty:n.Callbacks("once memory").add(function(){n._removeData(a,b+"queue"),n._removeData(a,c)})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.lengthh;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},Z=/^(?:checkbox|radio)$/i,$=/<([\w:-]+)/,_=/^$|\/(?:java|ecma)script/i,aa=/^\s+/,ba="abbr|article|aside|audio|bdi|canvas|data|datalist|details|dialog|figcaption|figure|footer|header|hgroup|main|mark|meter|nav|output|picture|progress|section|summary|template|time|video";function ca(a){var b=ba.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}!function(){var a=d.createElement("div"),b=d.createDocumentFragment(),c=d.createElement("input");a.innerHTML="
              a",l.leadingWhitespace=3===a.firstChild.nodeType,l.tbody=!a.getElementsByTagName("tbody").length,l.htmlSerialize=!!a.getElementsByTagName("link").length,l.html5Clone="<:nav>"!==d.createElement("nav").cloneNode(!0).outerHTML,c.type="checkbox",c.checked=!0,b.appendChild(c),l.appendChecked=c.checked,a.innerHTML="",l.noCloneChecked=!!a.cloneNode(!0).lastChild.defaultValue,b.appendChild(a),c=d.createElement("input"),c.setAttribute("type","radio"),c.setAttribute("checked","checked"),c.setAttribute("name","t"),a.appendChild(c),l.checkClone=a.cloneNode(!0).cloneNode(!0).lastChild.checked,l.noCloneEvent=!!a.addEventListener,a[n.expando]=1,l.attributes=!a.getAttribute(n.expando)}();var da={option:[1,""],legend:[1,"
              ","
              "],area:[1,"",""],param:[1,"",""],thead:[1,"","
              "],tr:[2,"","
              "],col:[2,"","
              "],td:[3,"","
              "],_default:l.htmlSerialize?[0,"",""]:[1,"X
              ","
              "]};da.optgroup=da.option,da.tbody=da.tfoot=da.colgroup=da.caption=da.thead,da.th=da.td;function ea(a,b){var c,d,e=0,f="undefined"!=typeof a.getElementsByTagName?a.getElementsByTagName(b||"*"):"undefined"!=typeof a.querySelectorAll?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||n.nodeName(d,b)?f.push(d):n.merge(f,ea(d,b));return void 0===b||b&&n.nodeName(a,b)?n.merge([a],f):f}function fa(a,b){for(var c,d=0;null!=(c=a[d]);d++)n._data(c,"globalEval",!b||n._data(b[d],"globalEval"))}var ga=/<|&#?\w+;/,ha=/r;r++)if(g=a[r],g||0===g)if("object"===n.type(g))n.merge(q,g.nodeType?[g]:g);else if(ga.test(g)){i=i||p.appendChild(b.createElement("div")),j=($.exec(g)||["",""])[1].toLowerCase(),m=da[j]||da._default,i.innerHTML=m[1]+n.htmlPrefilter(g)+m[2],f=m[0];while(f--)i=i.lastChild;if(!l.leadingWhitespace&&aa.test(g)&&q.push(b.createTextNode(aa.exec(g)[0])),!l.tbody){g="table"!==j||ha.test(g)?""!==m[1]||ha.test(g)?0:i:i.firstChild,f=g&&g.childNodes.length;while(f--)n.nodeName(k=g.childNodes[f],"tbody")&&!k.childNodes.length&&g.removeChild(k)}n.merge(q,i.childNodes),i.textContent="";while(i.firstChild)i.removeChild(i.firstChild);i=p.lastChild}else q.push(b.createTextNode(g));i&&p.removeChild(i),l.appendChecked||n.grep(ea(q,"input"),ia),r=0;while(g=q[r++])if(d&&n.inArray(g,d)>-1)e&&e.push(g);else if(h=n.contains(g.ownerDocument,g),i=ea(p.appendChild(g),"script"),h&&fa(i),c){f=0;while(g=i[f++])_.test(g.type||"")&&c.push(g)}return i=null,p}!function(){var b,c,e=d.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(l[b]=c in a)||(e.setAttribute(c,"t"),l[b]=e.attributes[c].expando===!1);e=null}();var ka=/^(?:input|select|textarea)$/i,la=/^key/,ma=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,na=/^(?:focusinfocus|focusoutblur)$/,oa=/^([^.]*)(?:\.(.+)|)/;function pa(){return!0}function qa(){return!1}function ra(){try{return d.activeElement}catch(a){}}function sa(a,b,c,d,e,f){var g,h;if("object"==typeof b){"string"!=typeof c&&(d=d||c,c=void 0);for(h in b)sa(a,h,c,d,b[h],f);return a}if(null==d&&null==e?(e=c,d=c=void 0):null==e&&("string"==typeof c?(e=d,d=void 0):(e=d,d=c,c=void 0)),e===!1)e=qa;else if(!e)return a;return 1===f&&(g=e,e=function(a){return n().off(a),g.apply(this,arguments)},e.guid=g.guid||(g.guid=n.guid++)),a.each(function(){n.event.add(this,b,e,d,c)})}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=n.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return"undefined"==typeof n||a&&n.event.triggered===a.type?void 0:n.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(G)||[""],h=b.length;while(h--)f=oa.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=n.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=n.event.special[o]||{},l=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},i),(m=g[o])||(m=g[o]=[],m.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,l):m.push(l),n.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n.hasData(a)&&n._data(a);if(r&&(k=r.events)){b=(b||"").match(G)||[""],j=b.length;while(j--)if(h=oa.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=m.length;while(f--)g=m[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(m.splice(f,1),g.selector&&m.delegateCount--,l.remove&&l.remove.call(a,g));i&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(k)&&(delete r.handle,n._removeData(a,"events"))}},trigger:function(b,c,e,f){var g,h,i,j,l,m,o,p=[e||d],q=k.call(b,"type")?b.type:b,r=k.call(b,"namespace")?b.namespace.split("."):[];if(i=m=e=e||d,3!==e.nodeType&&8!==e.nodeType&&!na.test(q+n.event.triggered)&&(q.indexOf(".")>-1&&(r=q.split("."),q=r.shift(),r.sort()),h=q.indexOf(":")<0&&"on"+q,b=b[n.expando]?b:new n.Event(q,"object"==typeof b&&b),b.isTrigger=f?2:3,b.namespace=r.join("."),b.rnamespace=b.namespace?new RegExp("(^|\\.)"+r.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=e),c=null==c?[b]:n.makeArray(c,[b]),l=n.event.special[q]||{},f||!l.trigger||l.trigger.apply(e,c)!==!1)){if(!f&&!l.noBubble&&!n.isWindow(e)){for(j=l.delegateType||q,na.test(j+q)||(i=i.parentNode);i;i=i.parentNode)p.push(i),m=i;m===(e.ownerDocument||d)&&p.push(m.defaultView||m.parentWindow||a)}o=0;while((i=p[o++])&&!b.isPropagationStopped())b.type=o>1?j:l.bindType||q,g=(n._data(i,"events")||{})[b.type]&&n._data(i,"handle"),g&&g.apply(i,c),g=h&&i[h],g&&g.apply&&M(i)&&(b.result=g.apply(i,c),b.result===!1&&b.preventDefault());if(b.type=q,!f&&!b.isDefaultPrevented()&&(!l._default||l._default.apply(p.pop(),c)===!1)&&M(e)&&h&&e[q]&&!n.isWindow(e)){m=e[h],m&&(e[h]=null),n.event.triggered=q;try{e[q]()}catch(s){}n.event.triggered=void 0,m&&(e[h]=m)}return b.result}},dispatch:function(a){a=n.event.fix(a);var b,c,d,f,g,h=[],i=e.call(arguments),j=(n._data(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=n.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,c=0;while((g=f.handlers[c++])&&!a.isImmediatePropagationStopped())a.rnamespace&&!a.rnamespace.test(g.namespace)||(a.handleObj=g,a.data=g.data,d=((n.event.special[g.origType]||{}).handle||g.handler).apply(f.elem,i),void 0!==d&&(a.result=d)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&("click"!==a.type||isNaN(a.button)||a.button<1))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(d=[],c=0;h>c;c++)f=b[c],e=f.selector+" ",void 0===d[e]&&(d[e]=f.needsContext?n(e,this).index(i)>-1:n.find(e,this,null,[i]).length),d[e]&&d.push(f);d.length&&g.push({elem:i,handlers:d})}return h]","i"),va=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi,wa=/\s*$/g,Aa=ca(d),Ba=Aa.appendChild(d.createElement("div"));function Ca(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function Da(a){return a.type=(null!==n.find.attr(a,"type"))+"/"+a.type,a}function Ea(a){var b=ya.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function Fa(a,b){if(1===b.nodeType&&n.hasData(a)){var c,d,e,f=n._data(a),g=n._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)n.event.add(b,c,h[c][d])}g.data&&(g.data=n.extend({},g.data))}}function Ga(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!l.noCloneEvent&&b[n.expando]){e=n._data(b);for(d in e.events)n.removeEvent(b,d,e.handle);b.removeAttribute(n.expando)}"script"===c&&b.text!==a.text?(Da(b).text=a.text,Ea(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),l.html5Clone&&a.innerHTML&&!n.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&Z.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:"input"!==c&&"textarea"!==c||(b.defaultValue=a.defaultValue)}}function Ha(a,b,c,d){b=f.apply([],b);var e,g,h,i,j,k,m=0,o=a.length,p=o-1,q=b[0],r=n.isFunction(q);if(r||o>1&&"string"==typeof q&&!l.checkClone&&xa.test(q))return a.each(function(e){var f=a.eq(e);r&&(b[0]=q.call(this,e,f.html())),Ha(f,b,c,d)});if(o&&(k=ja(b,a[0].ownerDocument,!1,a,d),e=k.firstChild,1===k.childNodes.length&&(k=e),e||d)){for(i=n.map(ea(k,"script"),Da),h=i.length;o>m;m++)g=k,m!==p&&(g=n.clone(g,!0,!0),h&&n.merge(i,ea(g,"script"))),c.call(a[m],g,m);if(h)for(j=i[i.length-1].ownerDocument,n.map(i,Ea),m=0;h>m;m++)g=i[m],_.test(g.type||"")&&!n._data(g,"globalEval")&&n.contains(j,g)&&(g.src?n._evalUrl&&n._evalUrl(g.src):n.globalEval((g.text||g.textContent||g.innerHTML||"").replace(za,"")));k=e=null}return a}function Ia(a,b,c){for(var d,e=b?n.filter(b,a):a,f=0;null!=(d=e[f]);f++)c||1!==d.nodeType||n.cleanData(ea(d)),d.parentNode&&(c&&n.contains(d.ownerDocument,d)&&fa(ea(d,"script")),d.parentNode.removeChild(d));return a}n.extend({htmlPrefilter:function(a){return a.replace(va,"<$1>")},clone:function(a,b,c){var d,e,f,g,h,i=n.contains(a.ownerDocument,a);if(l.html5Clone||n.isXMLDoc(a)||!ua.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(Ba.innerHTML=a.outerHTML,Ba.removeChild(f=Ba.firstChild)),!(l.noCloneEvent&&l.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(d=ea(f),h=ea(a),g=0;null!=(e=h[g]);++g)d[g]&&Ga(e,d[g]);if(b)if(c)for(h=h||ea(a),d=d||ea(f),g=0;null!=(e=h[g]);g++)Fa(e,d[g]);else Fa(a,f);return d=ea(f,"script"),d.length>0&&fa(d,!i&&ea(a,"script")),d=h=e=null,f},cleanData:function(a,b){for(var d,e,f,g,h=0,i=n.expando,j=n.cache,k=l.attributes,m=n.event.special;null!=(d=a[h]);h++)if((b||M(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)m[e]?n.event.remove(d,e):n.removeEvent(d,e,g.handle);j[f]&&(delete j[f],k||"undefined"==typeof d.removeAttribute?d[i]=void 0:d.removeAttribute(i),c.push(f))}}}),n.fn.extend({domManip:Ha,detach:function(a){return Ia(this,a,!0)},remove:function(a){return Ia(this,a)},text:function(a){return Y(this,function(a){return void 0===a?n.text(this):this.empty().append((this[0]&&this[0].ownerDocument||d).createTextNode(a))},null,a,arguments.length)},append:function(){return Ha(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=Ca(this,a);b.appendChild(a)}})},prepend:function(){return Ha(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=Ca(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return Ha(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return Ha(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&n.cleanData(ea(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&n.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return n.clone(this,a,b)})},html:function(a){return Y(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(ta,""):void 0;if("string"==typeof a&&!wa.test(a)&&(l.htmlSerialize||!ua.test(a))&&(l.leadingWhitespace||!aa.test(a))&&!da[($.exec(a)||["",""])[1].toLowerCase()]){a=n.htmlPrefilter(a);try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(ea(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=[];return Ha(this,arguments,function(b){var c=this.parentNode;n.inArray(this,a)<0&&(n.cleanData(ea(this)),c&&c.replaceChild(b,this))},a)}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=0,e=[],f=n(a),h=f.length-1;h>=d;d++)c=d===h?this:this.clone(!0),n(f[d])[b](c),g.apply(e,c.get());return this.pushStack(e)}});var Ja,Ka={HTML:"block",BODY:"block"};function La(a,b){var c=n(b.createElement(a)).appendTo(b.body),d=n.css(c[0],"display");return c.detach(),d}function Ma(a){var b=d,c=Ka[a];return c||(c=La(a,b),"none"!==c&&c||(Ja=(Ja||n("